我想这是一个简单的问题,但我无法解决它。这是我需要编写测试用例的类
@Controller
@SessionAttributes
public class LoginController {
@RequestMapping(value = "/Login", method = RequestMethod.GET)
public ModelAndView displayLogin(@RequestParam(value = "error", required = false) String error,
@RequestParam(value = "logout", required = false) String logout,
HttpServletRequest request,
HttpServletResponse response) {
ModelAndView modelForLogin = new ModelAndView();
if (error != null) {
// Include login failure message
modelForLogin.addObject("loginFailure", "Invalid username and password!");
}
if ("user".equals(logout)) {
// Include logout message
modelForLogin.addObject("msg", "You've been logged out successfully.");
}
else {
modelForLogin.addObject("msg","");
}
modelForLogin.setViewName("Login");
return modelForLogin;
}
}
这就是我到目前为止所得到的......
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration({ " servlet-xml "})
public class LoginControllerTest {
@Mock HttpServletRequest request;
@Mock HttpServletResponse response;
@Mock HttpSession session;
private MockMvc mockMvc;
@Before
protected void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
ModelAndView modelForLogin = mockito.mock(ModelAndView.class);
mockito.when(modelForLogin.error()).thenReturn("error");
mockito.when(modelForLogin.logout()).thenReturn("logout");
}
@Test
public void TestLoginError() throws Exception {
mockMvc.perform(get("/Login").param()).andExpect(status().isOk()).andExpect(model().attributeExists("msg"));
}
@Test
public void testLogin() throws Exception {
mockMvc.perform(get("/Login")).andExpect(status().isOk());
mockMvc.perform(get("/Login").param("logout", "log")).andExpect(status().isOk()).andExpect(model().attributeExists("msg"));
mockMvc.perform(get("/Login").param("error", "log")).andExpect(status().isOk()).andExpect(model().attributeExists("error"));
mockMvc.perform(get("/Login").param("logout", "log").param("error", "log")).andExpect(status().isOk()).andExpect(model().attributeExists("msg")).andExpect(model().attributeExists("error"));
mockMvc.perform(get("/Login")).andExpect(status().isOk()).andExpect(view().name("login"));
}
}
任何人都可以让我知道为此编写测试用例的正确方法吗?
最佳答案
鉴于您拥有的代码,无需进行模拟。示例测试用例如下所示:
ModelAndView mvw = displayLogin("error", null, null, null);
assertEquals("Invalid username and password!", mvw.getModelMap().get("loginFailure"));
关于java - 使用mockito进行登录页面Junit测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30653613/