简体   繁体   中英

Junit Asserting failed HTTP post request

I have an HTTPClient test for my spring boot app. I have a class that throws an exception if the a POST request to the server is in a string 2048 bytes or over.

@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);

    }


}

I created a unit test for it but I am not sure how I can write an assert statement to check if it fails to post the request.

Right now I have this so far in my test class

@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();

    }

This test fails which is what I want but I want to create an assert so it passes (assert that it fails the http response due to being over the byte limit).

You can surround the failing part with a try/catch, and call fail() at the end of the try block. If an exception is thrown, the fail() instruction should not be reached, and your test should pass.

@Test has an argument to assert that a particular exception gets thrown, you could write your test like eg :

    @Test(expected = IOException.class)
    public void testSize() throws ClientProtocolException, IOException {
    ...
    }

There are 3 ways you can achieve that:

1) Use @Test(expected = .... ) annotation where you provide class of exception you want to check.

@Test(expected = IOException.class)
public void test() {
  //... your test logic
}

This is not a recommended way of exception testing unless your test is really really small and does one thing only. Otherwise, you may get an IOException thrown but you won't be sure which part of test code exactly caused it.

2) Use @Rule annotation with ExpectedException class:

@Rule
public ExpectedException exceptionRule = ExpectedException.none();

@Test
public void testExpectedException() {
    exceptionRule.expect(IOException.class);
    exceptionRule.expectMessage("Request too big.");
//... rest of your test logic here
}

Please note that exceptionRule has to be public .

3) And last one, quite old-fashioned way:

@Test
public void test() {
  try {
    // your test logic
    fail(); // if we get to that point it means that exception was not thrown, therefore test should fail.
  } catch (IOException e) {
    // if we get here, test is successfull and code seems to be ok.
  }
}

It's an old fashioned way that adds some unnecessary code to your test that is supposed to be clean.

There is another solution, not already presented in these answers, and is my personal preference. assertThatThrownBy

in your case

@Test
public void testSizeException(){
  assertThatThrownBy(()-> Request.Post(mockAddress)
                  .connectTimeout(2000)
                  .socketTimeout(2000)
                  .bodyString(s, ContentType.TEXT_PLAIN)
                  .execute().returnContent().asString())
                  .isInstanceOf(IOException.class)
                  .hasMessageContaining("Request content exceeded limit of 2048 
  bytes");
}

*Disclaimer, above code written directly into SO editor

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM