测试控制器方法时,Spring MVC版本4.2.6似乎没有将模拟服务注入控制器



我真的搜索并遵循了为Spring MVC控制器创建单元测试类的步骤,但是单位测试正在使用绿色通行标志运行,但是该框架使用原始服务类,并调用到数据库。我嘲笑了该类,并与 MockitoAnnotations.initMocks(this) 一起使用了 @InjectMocks 。当测试运行时,控制器使用原始服务对象而不是模拟对象。我真的很感激是否有人能帮助我。

这是 UserManager service 类), UserRegisterController controller ), TestUserRegisterController test 类)类,带有 eclipse 软件包结构的图片

服务:

 @Service
    public class UserManager {
            protected Map<String, String> getAllCertificates() {
                Map<String, String> allCertificates = new HashMap<String, String>();
                //call to database
                return allCertificates;
            }


            protected User getUser(int userId) {
                //create session
                User user = session.get(User.class, userId);
                //close session
                return user;
            }
            }

控制器:

 @Controller
        public class UserRegisterController {
        @Autowired
        private UserManager manager;
        @InitBinder
        public void initBinder(WebDataBinder binder) {
            //do some work
        }
        @RequestMapping(value = "/user.html", method = RequestMethod.GET)
        public ModelAndView getUser(@RequestParam(value="userId",   defaultValue="-1") String userId) {
            User user1;
            user1 = this.manager.getUser(Integer.parseInt(userId));
            if (user1 == null) {
                user1 = new User();
            }
            ModelAndView view = new ModelAndView("User", "user1", user1);
            view.addObject("allCertificatesMap", this.manager.getAllCertificates());
            return view;
        }
        @ModelAttribute
        public void setModelAttribute(Model model) {
            model.addAttribute("PageHeader", "lable.pageHeader");
        }
    }

测试类:

   @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("test-spring-dispatcher-servlet.xml")
    @WebAppConfiguration
    public class TestUserRegisterController {
        @Mock
        private UserManager userManager;
        @InjectMocks
        private UserRegisterController userRegisterController;
        @Autowired
        private WebApplicationContext wac;
        private MockMvc mockMvc;
        @Before
        public void setUp() throws Exception {
            // Process mock annotations
            MockitoAnnotations.initMocks(this);
            User user2 = new User();
            user2.setUserId(10006);
            user2.setUserName("Reza");
            user2.setHobby("Quadcopter");
            user2.setPhone("4032376295");
            when(this.userManager.getUser(10006)).thenReturn(user2);
            when(this.userManager.getAllCertificates()).thenReturn(new HashMap<String, String>());
            this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
        }
        @Test
        public void getUser() {
            try {
                this.mockMvc.perform(get("/user.html").param("userId", "10006"))
                    .andExpect(status().isOk())
                    .andExpect(forwardedUrl("/WEB-INF/jsp/User.jsp"))
                    .andExpect(MockMvcResultMatchers.view().name("User"))
                    .andExpect(model().attributeExists("allCertificatesMap"));
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }

软件包层次结构

使用@RunWith(MockitoJUnitRunner.class)获取@InjectMocks和其他注释工作

最新更新