Unit Test Failure: Error 415 - Unsupported Media Type

149 Views Asked by At

I'm facing an issue with the unit tests for my Spring Boot application. When running the unit tests, I encounter the following error: "java.lang.AssertionError: Range for response status value 415 expected: but was:<CLIENT_ERROR>".

When I manually test the application using Postman, the endpoints work fine and return the expected results.

I have a UserController class with a createUser method that handles the creation of a user. Inside this method, the user's password is hashed using the HashingUtil.hashWithMD5 method before saving it to the repository.

Here's an example of the createUser method in the UserController:

@PostMapping("/users")
public ResponseEntity<User> createUser(@RequestBody User user){
    user.setPassword(HashingUtil.hashWithMD5(user.getPassword()));
    return ResponseEntity.ok(this.userRepository.save(user));
}

In my test class, I have a test method createUser that sends a POST request to the /users endpoint with a JSON payload containing the username and password. Here's an example of the relevant parts from the test class:

@BeforeEach
void init()
{
    this.username = "myfirstUser";
    String password = "savepassword";
    this.encodedPassword = this.encodeMD5(password);
    this.userJson = String.format("{\"username\":\"%s\", \"password\":\"%s\"}", this.username, password);
}

@Test
void createUser() throws Exception
{
    this.mvc.perform(MockMvcRequestBuilders.post("/users").content(this.userJson))
        .andExpect(MockMvcResultMatchers.status().is2xxSuccessful());
}

I suspect that the issue might be related to how the server is handling the data during the unit tests, specifically the media type or content type. I have tried adding the consumes attribute with MediaType.APPLICATION_JSON_VALUE to the createUser method in the UserController, but it didn't resolve the issue.

Hint: Please, I am looking for a solution that can be implemented from the other classes without modifying the test class itself.

0

There are 0 best solutions below