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:

public static void startServer() throws Exception {
    System.setProperty("", "create");
    System.setProperty("hibernate.dialect", "...");
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
             "jdbc/primaryDs", dataSource);

    Server server = new Server(0);
    WebAppContext webAppContext = new WebAppContext("src/main/webapp", "");
    webServerPort = server.getConnectors()[0].getLocalPort();

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

public void createTestContext() {
    tester.getTestContext().setBaseUrl("http://localhost:" + webServerPort + "");

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

    tester.setTextField("productName", productName);
    tester.setTextField("price", Integer.toString(price));

    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

Leave a Comment