记@AutoConfigureWebTestClient引发的一个坑

在spring boot项目调试单测时,默认webTestClient的请求超时时间为5秒,稍微在断点出停留,便会触发请求超时的异常

Timeout on blocking read for 5000000000 NANOSECONDS
java.lang.IllegalStateException: Timeout on blocking read for 5000000000 NANOSECONDS
	at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:123)
	at reactor.core.publisher.Mono.block(Mono.java:1731)

因此会在类上添加修改超时时间
@AutoConfigureWebTestClient(timeout = “PT10M”)

@ContextConfiguration
@ComponentScan("com.crypto.reward.ops")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ExtendWith(TestDataSetup.class)
@AutoConfigureWebTestClient(timeout = "PT10M")
public abstract class ApplicationTest {
...
}

然而,项目的jackson配置的是snake格式,

@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
    return builder -> builder.modules(modules())
            .failOnUnknownProperties(false)
            .propertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE)
            .serializationInclusion(JsonInclude.Include.NON_ABSENT)
            .featuresToEnable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE)
            ;
}

此时mock的数据便会无法正常解析,因为@AutoConfigureWebTestClient注解引入后,导致response.bodyToMono按照camel格式解析,造成无法正常反序列化

public <T> Mono<Result<T>> getResultMono(ParameterizedTypeReference<Result<T>> resultType, String uri) {
        return webClient.get()
                .uri(uri)
                .exchangeToMono(response -> {
                    if (response.statusCode().equals(HttpStatus.OK)) {

                        return response.bodyToMono(resultType);
                    } else {
                        return response.createException()
                                .flatMap(e -> Mono.just(Result.ofFail(e.getStatusText(), e.getMessage())));
                    }
                });
    }

测试用例如

PageRespDto<CountByProductDto> respDto = new PageRespDto<>();
Result<PageRespDto<CountByProductDto>> resp = Result.ofSuccess(respDto);
mockWebServer.enqueue(new MockResponse()
        .setResponseCode(200)
        .setBody(objectMapper.writeValueAsString(resp))
        .addHeader("Content-Type", "Application/json"));
webTestClient.method(httpMethod).uri(uri)
        .cookie(cookieName, sessionId)
        .exchange()
        .expectStatus()
        .value(status -> {
            assertThat(status).isEqualTo(HttpStatus.OK.value());
        })
        .expectBody(type)
        .value(result -> {
            assertThat(result.isOk()).isTrue();
        });

具体原理还未知,有知道的大佬麻烦评论告知,thanks~~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值