Search code examples
javaspring-bootjunitobjectmapper

Cannot send request body to integration test method in Spring Boot JUnit (objectMapper.writeValueAsString Issue)


I have a problem to handle with sending request body to integration test in Spring Boot JUnit. I got 400 Bad Request instead of 200 Ok.

Here is the AdminRefreshTokenRequest shown below

import jakarta.validation.constraints.NotBlank;
import lombok.Builder;
import lombok.Data;

@Data
@Builder
public class AdminRefreshTokenRequest {

    @NotBlank
    private String refreshToken;
}

Here is the refreshToken method shown below

@PostMapping("/refreshtoken")
    public ResponseEntity<?> refreshToken(@RequestBody AdminRefreshTokenRequest refreshTokenRequest) {
  .....
}

Here is the relevant part of integration test method shown below

@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;

AdminRefreshTokenRequest refreshTokenRequest = AdminRefreshTokenRequest.builder()
                .refreshToken("RefreshToken")
                .build();

mockMvc.perform(post(ADMIN_CONTROLLER_BASEURL + "/refreshtoken")
                        .contentType("application/json")
                        .content(objectMapper.writeValueAsString(refreshTokenRequest)))
                .andDo(print())
                .andExpect(status().isOk())

I get this issue shown below

MockHttpServletResponse:
           Status = 400
    Error message = null
          Headers = [Content-Type:"application/problem+json"]
     Content type = application/problem+json
             Body = {"type":"about:blank","title":"Bad Request","status":400,"detail":"Failed to read request","instance":"/api/v1/refreshtoken"}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

java.lang.AssertionError: Status expected:<200> but was:<400>
Expected :200
Actual   :400

The value assigning to refreshTokenRequest in refreshToken method of controller is null when mockMvc try to call the method after I delete @RequestBody.

How can I fix it?


Solution

  • Here is the solution shown below.

    After deleting @Builder which is used for more than one variable, I defined both @NoArgsConstructor and @AllArgsConstructor. Next, the issue disappeared.

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class AdminRefreshTokenRequest {
    
        @NotBlank
        private String refreshToken;
    }