Writing automatic tests requiring external resources

Introduction

Some automatic tests, as integration tests, can require external resources. Junit provides a mechanism to simplify the management of these external resources in an automatic test context: Rules.

The Petals JUnit Framework comes with several external resources ready to use:

  • a Web server,
  • a FTP server.
Contributors
No contributors found for: authors on selected page(s)

A Web server as external resource

The WebServer rule allows creation of files and folders that are guaranteed to be deleted when the test method finishes (whether it passes or fails):

public static class HasWebServer {
  @Rule
  public WebServer webServer = new WebServer();

  @Test
  public void testUsingWebServer() throws IOException {

    // ...
    this.webServer.addServlet(servlet, servletPath);
    // ...
  }
}

Creating the web-server

The creation of the web-server requires the HTTP port on which it will listen. The default listening port is '{{WebServer.DEFAULT_HTTP_PORT}'. You can use your own HTTP port using the right constructor:

  // A web server listening on the default HTTP port
  @Rule
  public WebServer webServer = new WebServer();

  // A web server listening on your own HTTP port
  @Rule
  public WebServer webServer = new WebServer(8080);

Registering servlet

A web-server maps URLs on servlets. If your test requires a servlet, you can register a servlet through the API 'WebServer.addServlet(httpServlet, path)', where 'httpServlet' is your servlet to map on the URL path part '{path}}':

public static class HasWebServer {
  @Rule
  public WebServer webServer = new WebServer();

  @Test
  public void testUsingWebServer() throws IOException {

    // ...
    this.webServer.addServlet(servlet, servletPath);
    // ...
  }
} 

Pre-defined servlets

Several servlets are provided into the Petals JUnit Framework:

  • FileServlet that replies with the content of a file,
  • TextServlet that replies with a plain-text content.

Working with FileServlet

The reply of this servlet is the content of a file:


public static class HasWebServer {
  @Rule
  public WebServer webServer = new WebServer();

  @Test
  public void testUsingWebServer() throws IOException {

    // ...

final AbstractHttpServlet fileServlet = new FileServlet(localArtifact, MimeTypeConstants.APPLICATION_ZIP);
    this.webServer.addServlet(servlet, servletPath);
    // ...
  }
}
Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.