【发布时间】:2021-04-10 05:56:54
【问题描述】:
在为我的 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>
【问题讨论】:
标签: spring-boot java-8 jackson timezone-offset spring-webclient