title: How to write a unit test for a REST login web service using spring boot
body: <p>I am developing one application using spring boot. I would like to unit test my Rest service login(), my service works well (I used postman). please take a look at what I tried for my unite test.
  for example when I type a correct username and password I got a token as a return value:</p>
  
  <p><a href="https://i.stack.imgur.com/yteGK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yteGK.png" alt="enter image description here"></a></p>
  
  <p>and when I enter a false username and password I got this:</p>
  
  <p><a href="https://i.stack.imgur.com/zjNQg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zjNQg.png" alt="enter image description here"></a></p>
  
  <p>these is my architecture of my app:</p>
  
  <pre><code>app
   |
  src/main/java
   |--DemoApplication.java
   |--dao.package
           |--UserRepository.java
   |--jwt.package
           |--UserController.java
  src/test/java
   |--jwt.package.test
           |--UserControllerTest.java
  </code></pre>
  
  <p><strong>DemoApplication.java</strong></p>
  
  <pre><code>@SpringBootApplication
  public class DemoApplication implements CommandLineRunner {
  
  
      public static void main(String[] args) {
  
          SpringApplication.run(DemoApplication.class, args);
      }
  
      @Override
      public void run(String... args) throws Exception {
  
      }
  }
  </code></pre>
  
  <p><strong>UserController.java</strong></p>
  
  <pre><code>@RestController
  @RequestMapping("/user")
  public class UserController {
  
      @Autowired
      private UserRepository userRepository;
  
      @PostMapping("login")
      public LoginResponse login(@RequestBody final UserLogin login)
          throws ServletException,
              UnsupportedEncodingException {
  
          User user = userRepository.findByUsernameAndPassword(login.username,
              login.password);
  
          if (user == null)
              throw new ServletException("Invalid login");
  
          StringBuilder roles = new StringBuilder();
          user.getRoles()
              .forEach(role -&gt; roles.append(role.getName()).append(","));
          return new LoginResponse(Jwts.builder().setSubject(login.username)
              .claim("roles", roles).setIssuedAt(new Date())
              .signWith(SignatureAlgorithm.HS256, "accenture".getBytes("UTF-8"))
              .compact());
      }
  
      private static class UserLogin {
  
          public String username;
  
          public String password;
      }
  
      private static class LoginResponse {
  
          public String token;
  
          public LoginResponse(final String token) {
              this.token = token;
          }
      }
  }
  </code></pre>
  
  <p>I tried to test my login web service but still not correct. Anyone could help me please to unit test my login service</p>
  
  <p><strong>UserControllerTest.java:</strong></p>
  
  <pre><code>@RunWith(SpringRunner.class)
  @WebMvcTest(value = UserController.class, secure = false)
  public class UserControllerTest {
  
      @Autowired
      private MockMvc mockMvc;
  
      @MockBean
      private UserRepository userRepository;
  
      User mockUser = new User("test", "test");
  
      String exampleUserJson = "{\"username\":\"toto\",\"password\":\"toto\"}";
  
  
      @Test
      public void loginTest() throws Exception {
  
  
          User mockUser = new User("test", "test");
  
      Mockito.when(
              userRepository.findByUsernameAndPassword(Mockito.anyString(),
                  Mockito.anyString())).thenReturn(mockUser);
  
      // Send course as body to /students/Student1/courses
      RequestBuilder requestBuilder = MockMvcRequestBuilders
              .post("/user/login")
              .accept(MediaType.APPLICATION_JSON).content(exampleUserJson)
              .contentType(MediaType.APPLICATION_JSON);
  
      MvcResult result = mockMvc.perform(requestBuilder).andReturn();
  
      MockHttpServletResponse response = result.getResponse();
  
      assertEquals(HttpStatus.INTERNAL_SERVER_ERROR.value(), response.getStatus());
  
      assertEquals("http://localhost/user/login",
              response.getHeader(HttpHeaders.LOCATION));
  
      }
  </code></pre>