java 如何用Micronaut在Spock中模拟ReadTimeoutException

y0u0uwnf  于 2022-12-17  发布在  Java
关注(0)|答案(1)|浏览(157)

我试图用Spock模拟io.micronaut.http.client.exceptions.ReadTimeoutException,但是显式地不能抛出异常,因为不能从测试类访问它。
我想测试的代码如下所示:

try {
             res = httpClient.toBlocking().exchange(
                    HttpRequest.GET(url)
                            .header("env", "internal")
                            .header("Content-Type", "application/json"),
                    TokenResponseBody.class
            );

        } catch (HttpClientResponseException e) {
            LOGGER.error("Visa Token get request", e);
            throw new CardTokenException(String.valueOf(e.getStatus().getCode()), e.getMessage());
        } catch (ReadTimeoutException re) {
            LOGGER.error("Visa Token get request", re);
            throw new CardTokenException(re.getMessage(), "Tokens client read timeout");
        }

因此,我尝试将httpClient.toBlocking()返回的BlockingHttpClient存根为:

BlockingHttpClient blockingHttpClientStub = Stub(BlockingHttpClient.class)
blockingHttpClientStub.exchange(
        _ as MutableHttpRequest, TokenResponseBody.class
) >> {
      MutableHttpRequest obj, Class classType -> new Thread().sleep(15000)
}
httpClient.toBlocking() >> blockingHttpClientStub

默认的配置持续时间是10秒,所以我假设sleep方法会中断它15秒,并且会抛出ReadTimeoutException。如果有任何方法可以模拟ReadTimeoutException,请帮助我。

d5vmydt9

d5vmydt91#

你怎么知道new Thread().sleep(15000)会阻塞任何东西?你创建了一个单独的线程,然后在它启动之前尝试休眠。你可以尝试Thread.currentThread().sleep()。但是,你基本上是替换了整个实现,所以没有什么可以抛出异常的。
为什么不直接抛出异常呢?

BlockingHttpClient blockingHttpClientStub = Stub(BlockingHttpClient) {
    exchange(_ as MutableHttpRequest, TokenResponseBody) >> {
        throw io.micronaut.http.client.exceptions.ReadTimeoutException.TIMEOUT_EXCEPTION
    }
}
httpClient.toBlocking() >> blockingHttpClientStub

相关问题