Spring Error loading invalid status code only in Unit Test

I am developing a REST API using Spring Boot.

I have a controller to create a new user who is responsible for 201 (CREATED) when the user is created. The answer has no body content.

Using Postman or any browser, I got a 201 response. But when I try to use unit test (Mockito), the answer is 200.

Here is my code:

controller

public CompletableFuture<ResponseEntity<Void>> registerNewUser(
    @RequestBody @Valid RegisterUserDto newUser
) throws ExecutionException, InterruptedException {

  // user service return a completable future void 
  return userService.registerNewUser(newUser).thenApply(u -> new ResponseEntity<>(u, HttpStatus.CREATED));
}

The user service returns a terminating future void when the registration process is completed.

@Async
CompletableFuture<Void> registerNewUser(NewUserDto newUserDto) throws ExecutionException, InterruptedException;

Then in my unit test, I have the following code:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class UsersControllerTest {

  @Autowired
  private MockMvc mvc;

  @Mock
  private UsersService userService;

  @InjectMocks
  private UsersControllers usersController;

  @Before
  public void init() {
    MockitoAnnotations.initMocks(this);
    this.mvc = MockMvcBuilders.standaloneSetup(usersController).build();
  }

  @Test
  public void mustCreateANewUser() throws Exception {
    NewUserDto userMock = new NewUserDto("firstname", "lastname", "login", "password");

    when(userService.registerNewUser(any(NewUserDto.class)))
      .thenReturn(CompletableFuture.completedFuture(null));

    mvc.perform(post("/api/users/new")
                    .content(TestHelpers.convertToJson(userMock))
                    .contentType(TestHelpers.getJsonMediaType()))
        .andExpect(status().isCreated());
  }
}

TestHelpers.convertToJson and TestHelpers.getJsonMediaType are static methods.

public static MediaType getJsonMediaType() {
  return new MediaType(MediaType.APPLICATION_JSON.getType(),
                       MediaType.APPLICATION_JSON.getSubtype(),
                       Charset.forName("utf8"));
}

public static String convertToJson(Object o) throws IOException {
  ObjectMapper mapper = new ObjectMapper();
  return mapper.writeValueAsString(o);
}

I don't understand why the response code was 200 on unit test. In any part of my controller, service or controller board, I have a 200 OK response.

+4
1

, async, unit test .

unit test :

MvcResult result = mvc.perform(post("/api/users/new")
  .content(TestHelpers.convertToJson(registroMock))
  .contentType(TestHelpers.getJsonMediaType()))
  .andReturn();

mvc.perform(asyncDispatch(result))
   .andExpect(status().isCreated());
+1

Source: https://habr.com/ru/post/1688079/


All Articles