【发布时间】:2019-08-12 14:45:06
【问题描述】:
我的 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 响应失败)。
【问题讨论】:
-
你有异常吗?
@Test有一个参数来断言抛出了异常,例如@Test(expected = IOException.class)。 -
是的,它应该给出错误消息的异常。这行得通,谢谢。请写下这个答案,以便我接受并给你积分。
标签: java spring-boot http junit assert