Can we use JUNIT for Automated Integration Testing?

I’ve used JUnit for doing a lot of integration testing. Integration testing can, of course, mean many different things. For more system level integration tests, I prefer to let scripts drive my testing process from outside.

Here’s an approach that works well for me for applications that use http and databases and I want to verify the whole stack:

  1. Use Hypersonic or H2 in in-memory mode as a replacement for the database (this works best for ORMs)
  2. Initialize the database in @BeforeSuite or equivalent (again: easiest with ORMs)
  3. Use Jetty to start an in-process web server.
  4. @Before each test, clear the database and initialize with the necessary data
  5. Use JWebUnit to execute HTTP requests towards Jetty

This gives you integration tests that can run without any setup of database or application server and that exercises the stack from http down. Since it has no dependencies on external resources, this test runs fine on the build server.

Here some of the code I use:

@BeforeClass
public static void startServer() throws Exception {
    System.setProperty("hibernate.hbm2ddl.auto", "create");
    System.setProperty("hibernate.dialect", "...");
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setJdbcUrl("jdbc:hsqldb:mem:mytest");
    new org.mortbay.jetty.plus.naming.Resource(
             "jdbc/primaryDs", dataSource);


    Server server = new Server(0);
    WebAppContext webAppContext = new WebAppContext("src/main/webapp", "https://stackoverflow.com/");
    server.addHandler(webAppContext);
    server.start();
    webServerPort = server.getConnectors()[0].getLocalPort();
}

// From JWebUnit
private WebTestCase tester = new WebTestCase();

@Before
public void createTestContext() {
    tester.getTestContext().setBaseUrl("http://localhost:" + webServerPort + "https://stackoverflow.com/");
    dao.deleteAll(dao.find(Product.class));
    dao.flushChanges();
}

@Test
public void createNewProduct() throws Exception {
    String productName = uniqueName("product");
    int price = 54222;

    tester.beginAt("/products/new.html");
    tester.setTextField("productName", productName);
    tester.setTextField("price", Integer.toString(price));
    tester.submit("Create");

    Collection<Product> products = dao.find(Product.class);
    assertEquals(1, products.size());
    Product product = products.iterator().next();
    assertEquals(productName, product.getProductName());
    assertEquals(price, product.getPrice());
}

For those who’d like to know more, I’ve written an article about Embedded Integration Tests with Jetty and JWebUnit on Java.net.

Leave a Comment