0

I am trying to write a test for a URL /rdrct which redirects to another URL, say /test on the same host. On the application, the redirect works fine and I see a HTTP 302 in the Network Inspector but when I write a Java test, it fails and I get the following error.

expected: <200> but was: <302>

@Test
public void testRedirect() throws Exception { 
    String uri = "http://localhost:" + port + "/rdrct";
    URL url = new URL(uri);

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setInstanceFollowRedirects(true);
    connection.setRequestProperty("Accept",
        "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,"
        + "image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7");
    connection.connect();
    int responseCode = connection.getResponseCode();
    assertEquals(responseCode, 302); 
}

What am I missing or doing wrong?

8
  • Minor point, the first argument to assertEquals should be the expected value, which would make the message say what it should. Commented Aug 11, 2023 at 3:19
  • 1
    And I think the answer to your question is that the redirect is being followed, and /test returns a 200 status. Commented Aug 11, 2023 at 3:20
  • 200 is "ok" 302 is a little more odd but for some , the same as 200 re: developer.mozilla.org/en-US/docs/Web/HTTP/Status/302 Commented Aug 11, 2023 at 3:24
  • @SamuelMarchant No it isn't. 302 means a redirect to a URL specified in another header. 200 means success and is accompanied by the desired payload. Your source code does not support your assertion. Commented Aug 11, 2023 at 3:51
  • 1
    @OP As you are following redirects, you won't see the 302. If you want to see it, don't set the connection to follow redirects, in which case you will have to follow them yourself. Commented Aug 11, 2023 at 3:53

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.