October 22, 2024
Chicago 12, Melborne City, USA
java

Unexpected 401 error at testing RestController


`

I’m trying to test the login method by adding a user, and when I want to login, I get a 401 response insted of 200

UserController

/**
 * Login form
 * @param user the user we are trying to log in with
 * @return JWT
 */
@PostMapping("/login")
public String login(@RequestBody User user){
    System.out.println(user);
    return userService.login(user);
}

@Test
@DisplayName("Should Login Successful")
public void shouldLoginSuccessful() throws Exception {               
    User user = new User( VALID_USERNAME_EXAMPLE, VALID_PASSWORD_INPUT_EXAMPLE ); 
    assertDoesNotThrow(() -> userService.register(user));
    assertFalse(userRepository.findAll().isEmpty()); // Verify the list is not empty
    assertEquals(1, userRepository.findAll().size()); // Verify there is just one user


    String userJson = objectMapper.writeValueAsString(user);

    mockMvc.perform(MockMvcRequestBuilders
                    .post("/login")
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(userJson)) // Attach the JSON payload
            .andExpect(status().isOk());
}`

I tried to acces the endpoint "/login" and I should get a 200 response, but I get a 401 UNAUTHORIZED response



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video