Spring Boot仅在单元测试中返回错误的状态代码 [英] Spring Boot returning wrong Status Code only in Unit Test
问题描述
我正在使用Spring Boot开发REST API.
I'm developing a REST API with Spring Boot.
我有一个控制器来创建一个新用户,该用户创建后会响应201(创建).响应中没有正文内容.
I have a controller to create a new user, that responds with 201 (CREATED) when the user is created. The response has no body content.
使用邮递员或任何浏览器,我收到了201的回复. 但是,当我尝试使用单元测试(Mockito)时,响应为200.
Using Postman, or any browser, I got a 201 response. But when I try with unit test (Mockito), the response is 200.
这是我的代码:
控制器:
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 completable future void when the register 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和TestHelpers.getJsonMediaType是静态方法.
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);
}
我不明白为什么单元测试中的响应代码为200.在我的控制器,服务或控制器建议的任何部分,我都有200的响应.
I do not understand why the response code was 200 on unit test. In any part of my controller, service, or controller advice I have a response 200 OK.
推荐答案
问题是因为我的控制器和服务是异步的,所以我的单元测试没有等待正确的响应.
The problem was because my controller and service are async, so my unit test it's not waiting for the correct response.
将我的单元测试更改为:
Changed my unit test to:
MvcResult result = mvc.perform(post("/api/users/new")
.content(TestHelpers.convertToJson(registroMock))
.contentType(TestHelpers.getJsonMediaType()))
.andReturn();
mvc.perform(asyncDispatch(result))
.andExpect(status().isCreated());
这篇关于Spring Boot仅在单元测试中返回错误的状态代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!