title: Login page Junit test with mockito
body: <p>I guess this is simple problem, but I am unable to get my head around it. this is the class for which I need to write test case</p>
  
  <pre><code>@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;
  
  }
  </code></pre>
  
  <p>}</p>
  
  <p>This is what I have got till now...</p>
  
  <pre><code>@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"));
  }
  </code></pre>
  
  <p>}</p>
  
  <p>Can anyone please let me know proper way to write test case for this?</p>