在测试控制器方法

时间:2016-06-20 22:10:25

标签: spring unit-testing model-view-controller controller mockito

我真的搜索并按照为spring MVC控制器创建单元测试类的步骤,但是单元测试使用绿色通过标志运行,但框架使用原始服务类并调用数据库。我嘲笑了这个类,并将 @InjectMocks MockitoAnnotations.initMocks(this) 一起使用。仍然在测试运行时,控制器使用原始服务对象而不是模拟对象。如果有人能在这方面帮助我,我真的很感激。

以下是 UserManager 服务类), 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();
            }

    }

Package hierarchy

1 个答案:

答案 0 :(得分:0)

使用@RunWith(MockitoJUnitRunner.class)@InjectMocks和其他注释生效