gpt4 book ai didi

java - Junit 断言 HTTP post 请求失败

转载 作者:行者123 更新时间:2023-12-01 16:43:39 25 4
gpt4 key购买 nike

我有一个针对我的 Spring Boot 应用程序的 HTTPClient 测试。我有一个类,如果对服务器的 POST 请求的字符串长度为 2048 字节或以上,则会引发异常。

@Component
public class ApplicationRequestSizeLimitFilter extends OncePerRequestFilter {

@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
System.out.println(request.getContentLength());
if (request.getContentLengthLong() >= 2048) {
throw new IOException("Request content exceeded limit of 2048 bytes");
}
filterChain.doFilter(request, response);

}


}

我为它创建了一个单元测试,但我不确定如何编写断言语句来检查它是否无法发布请求。

现在我的测试类已经有了这个

@Test
public void testSize() throws ClientProtocolException, IOException {
Random r = new Random(123);
long start = System.currentTimeMillis();
String s = "";
for (int i = 0; i < 65536; i++)
s += r.nextInt(2);
String result = Request.Post(mockAddress)
.connectTimeout(2000)
.socketTimeout(2000)
.bodyString(s, ContentType.TEXT_PLAIN)
.execute().returnContent().asString();

}

这个测试失败了,这正是我想要的,但我想创建一个断言,以便它通过(断言它由于超过字节限制而导致 http 响应失败)。

最佳答案

您可以用 try/catch 包围失败部分,并在 try block 末尾调用fail()。如果抛出异常,则不应到达fail()指令,并且您的测试应该通过。

关于java - Junit 断言 HTTP post 请求失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57463384/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com