Skip to content

JUnit5 tests

Dmytro Mykhaliev edited this page Aug 13, 2019 · 1 revision

Prerequisite

This example uses CodeSV Junit5 VirtualServerResolver.class extension:

JUnit5 example:

@ExtendWith({VirtualServerResolver.class})
public class JUnit5CodeSVTest {

  private static final String URL = "http://www.ca.com/portfolio";

  private static String RESPONSE_BODY_GET = "Response body from virtualized service.";
  private static int CUSTOM_STATUS_CODE = 258;

  @Test
  public void testSimpleHttpGetWithResponseCodeAndStringBody() throws IOException {
    forGet(URL).doReturn(
        aMessage(CUSTOM_STATUS_CODE)
            .withStringBody(RESPONSE_BODY_GET)
    );

    HttpGet httpGet = new HttpGet(URL);
    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpResponse httpResponse = httpClient.execute(httpGet);

    assertEquals(CUSTOM_STATUS_CODE, httpResponse.getStatusLine().getStatusCode());

    BufferedReader reader = new BufferedReader(
        new InputStreamReader(httpResponse.getEntity().getContent()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = reader.readLine()) != null) {
      response.append(inputLine);
    }
    reader.close();

    assertEquals(response.toString(), RESPONSE_BODY_GET);
  }

}