在为我的Web服务编写测试用例时,我遇到了与OffsetDateTimeStamp相关的问题。当我从浏览器进行测试时,它给出了正确的响应,但在编写测试用例时,它没有显示偏移量,因此它失败了。
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class TestControllerTest {
@LocalServerPort
private int port;
private WebClient client;
@Test
public void test() {
Person person = new Person();
person.setId(1);
person.setBirthDate(OffsetDateTime.now());
person.setMobile(9090909090L);
person.setName("Tempo");
client = WebClient.create("http://localhost:"+port);
Person response = client.post().uri("/test1")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(person))
.retrieve()
.bodyToMono(Person.class)
.block();
Assertions.assertEquals(person.getBirthDate(), response.getBirthDate());
}
}
控制器代码
@RestController
public class TestController {
@PostMapping("/test1")
public Mono<Person> test1(@RequestBody Person person) {
System.out.println(person.getBirthDate());
return Mono.just(person);
}
}
邮件应用程序代码
@SpringBootApplication
public class TestAppApplication {
public static void main(String[] args) {
SpringApplication.run(TestAppApplication.class, args);
}
@Bean
public Module javaTimeModule() {
return new JavaTimeModule();
}
@Bean
public Jackson2ObjectMapperBuilderCustomizer jacksonObjectMapperCustomization() {
return jacksonObjectMapperBuilder -> jacksonObjectMapperBuilder.timeZone(TimeZone.getDefault());
}
}
Person.java
public class Person {
private int id;
private String name;
private long mobile;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
private OffsetDateTime birthDate;
public Person() {}
}
application.properties
spring.jackson.serialization.write-dates-as-timestamps=false
spring.jackson.deserialization.adjust-dates-to-context-time-zone=false
spring.jackson.serialization.write-dates-with-zone-id=true
测试用例的输出
org.opentest4j.AssertionFailedError:
Expected :2021-01-04T17:43:51.817+05:30
Actual :2021-01-04T12:13:51.817Z
<Click to see difference>
如何在Person
实体类中定义属性birthDate
?您需要在那里定义格式。你可以这样做:
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
private OffsetDateTime birthDate;
...
public OffsetDateTime getBirthDate() {
return birthDate;
}
请参阅此问题的答案中的更多详细信息:用于json序列化的SpringDataJPA-ZonedDateTime格式