【发布时间】:2022-01-13 14:29:42
【问题描述】:
我需要测试一个包含 java.time.Instant 字段的 Rest API 响应正文。不幸的是,由于实际时间戳和预期时间戳之间存在毫秒差异,因此无法通过测试。我只是想知道如何模拟系统时钟或以某种方式配置测试上下文以使测试通过:
响应正文类:
public class ApiError {
private HttpStatus httpStatus;
private Instant timestamp;
private List<ErrorDetail> errorDetails;
public ApiError(HttpStatus httpStatus) {
this.httpStatus = httpStatus;
this.timestamp = Instant.now();
}
// the rest of class is omitted for brevity
}
测试类:
@WebMvcTest(controllers = UserController.class)
class UserControllerTest {
@Autowired MockMvc mockMvc;
@Autowired ObjectMapper mapper;
ApiError apiError;
@Test
public void givenBlankField_WhenRequestIsReceived_ThenApiErrorGenerated() throws Exception {
SignUpRequest request = new SignUpRequest()
.setFirstName(" ") //validation error occurs
.setLastName("Doe")
.setPassword("123")
.setConfirmPassword("123")
.setEmail("john.doe@something.com")
.setConfirmEmail("john.doe@something.com");
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/api/users/signup")
.content(mapper.writeValueAsString(request))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isBadRequest()).andReturn();
String actualResponseBody = result.getResponse().getContentAsString();
// Excpected response body:
apiError = new ApiError(HttpStatus.BAD_REQUEST);
FieldValidationErrorDetail errorDetail = new FieldValidationErrorDetail.Detail()
.field("firstName").message("{NotBlank.firstName}").rejectedValue(" ").build();
apiError.setErrorDetails(List.of(errorDetail));
String expectedResponseBody = mapper.writeValueAsString(apiError);
assertEquals(expectedResponseBody, actualResponseBody); //fails due to milliseconds difference between actual timestamp and expected timestamp
}
}
【问题讨论】:
标签: java json spring-boot unit-testing mocking