Jakarta EETestingTestcontainers

Zero-Boilerplate Tests of Database and UI, with TestContainers, FlowLogix and Jakarta EE

Zero-Boilerplate Tests of Database and UI, with TestContainers, FlowLogix and Jakarta EE

This work was sponsored by Flow Logix. Generate a ready-to-run Jakarta EE project at start.flowlogix.com.

Arquillian runs your tests inside a real application server. Your test gets real injection, real transactions and a real database connection, with nothing mocked. That is the best way to test a Jakarta EE application.

It also used to be hard to set up. That is no longer true. This article shows a complete integration test, and then a browser test, with no boilerplate code at all.

The whole test, today

@AppServerLifecycle
@ArquillianSuiteDeployment
class GreeterIT {
    @Inject
    Greeter greeter;

    @Test
    void greets() {
        assertThat(greeter.greet("Duke")).isEqualTo("Hi, Duke!");
    }
}

That is all of it. There is no @Deployment method, no server code and no configuration to write. Run it with ./mvnw verify.

Note
The snippets in this article leave out packages and imports so they are easy to read.

What it used to take before FlowLogix was on the scene

Before you could write the first assertion, you needed all of this:

  • A dozen or more test dependencies in the POM, with versions that had to agree with each other

  • An arquillian.xml file and a container adapter

  • A server, installed and started by hand or by a script

  • Failsafe plugin configuration

  • For browser tests, Selenium driver setup and browser lifecycle code

And in every test class, a method like this one:

@Deployment
static WebArchive createDeployment() {
    return ShrinkWrap.create(WebArchive.class, "test.war")
            .addClass(Greeter.class)
            .addClass(FriendlyGreeter.class)
            .addClass(GreetingResource.class)
            .addClass(RestApplication.class)
            .addClass(User.class)
            .addClass(UserService.class)
            .addClass(GreeterIT.class)
            .addAsLibrary(new File("lib/omnifaces-5.0.jar"))
            .addAsLibrary(new File("lib/primefaces-15.0.0-jakarta.jar"))
            .addAsResource("META-INF/persistence.xml")
            .addAsWebInfResource("beans.xml")
            .addAsWebInfResource("web.xml");
}

You have to list every class and every library by hand. Add a class to the application and forget to add it here, and the test fails.

Where the setup went

Three small open source pieces from Flow Logix hold everything that used to be in your project.

Base POM is the parent of your POM. It configures the build plugins, including the integration test run, and it manages the server. Use payara-pom for Payara or glassfish-pom for GlassFish.

Dependency chains turn a long list of test dependencies into one. The integration-test chain brings JUnit, AssertJ, Mockito, Arquillian, ShrinkWrap, TestContainers and the suite extension, in versions that work together.

FlowLogix Jakarta EE components build the deployment for you. If a test has no @Deployment method, FlowLogix creates the archive from your Maven POM: your classes, your web resources and your runtime dependencies.

This is the test-related part of the POM:

<parent>
    <groupId>com.flowlogix</groupId>
    <artifactId>payara-pom</artifactId>
    <version>150</version>
</parent>

<dependency>
    <groupId>com.flowlogix.depchain</groupId>
    <artifactId>integration-test</artifactId>
    <version>135</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>com.flowlogix</groupId>
    <artifactId>flowlogix-jee</artifactId>
    <version>11.7.6</version>
    <scope>test</scope>
</dependency>

You do not have to type that either. start.flowlogix.com generates the project, with arquillian.xml already in place.

One deployment for the whole suite

By default, Arquillian deploys your application before each test class and removes it afterwards. With twenty test classes, that is twenty deployments of the same application. Most of the test run is spent waiting for them.

The Arquillian Suite extension fixes that with one annotation. Put @ArquillianSuiteDeployment on one class, and the application is deployed once for all of them.

We measured a sample run with ten test classes. These are the results, and your mileage may vary:

  • The whole test run was 2.4 times faster with the annotation.

  • Each test class after the first took 0.01 seconds instead of 2.4 seconds.

The more test classes you have, the bigger the difference.

One annotation, three ways to run the server

@AppServerLifecycle makes sure there is a server to test against. The test code is the same in every case. The Maven command decides where the server comes from.

CommandWhat happens

./mvnw verify

Base POM downloads Payara or GlassFish, starts it before the integration tests and stops it afterwards. Nothing has to be installed.

./mvnw verify -Pserver-docker

@AppServerLifecycle starts the server in a container with TestContainers and points Arquillian at it. The container is removed when the tests finish.

./mvnw verify -Pserver-local

The tests use a server that is already running on your machine. This is the fastest choice while you are developing.

TestContainers is used only when you ask for it. The annotation does nothing in the other two cases, so the same test class works on a laptop with no Docker and in a CI job that has nothing but Docker.

Database tests

A database test needs nothing extra. The test runs inside the server, so it uses the same data source, the same persistence unit and the same transactions as the application.

Here is an entity and a service from the application. Lombok and @Transactional keep them free of boilerplate too:

@Entity
@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Customer {
    @Id
    @GeneratedValue
    Long id;
    String name;
}

@Transactional
@ApplicationScoped
public class CustomerService {
    @Inject
    EntityManager em;

    public void save(Customer customer) {
        em.persist(customer);
    }

    public List<String> names() {
        return em.createQuery("select c.name from Customer c", String.class)
                .getResultList();
    }
}

And the test:

@AppServerLifecycle
class CustomerIT {
    @Inject
    CustomerService customers;

    @Test
    void savesCustomer() {
        customers.save(Customer.builder().name("Duke").build());
        assertThat(customers.names()).containsExactly("Duke");
    }
}

There is no transaction code, no test data source and no mock. The row goes into a real database through the real service, in a real transaction.

UI tests: Drone and Graphene handle Selenium

Selenium is powerful, but it has hard edges. You have to create the driver, configure the browser, share it between tests and close it when the run ends, including when a test fails.

Arquillian Drone does all of that. You ask for a browser and you get one:

@RunAsClient
@AppServerLifecycle
class IndexPageIT {
    @Test
    void title(@Drone WebDriver browser, @ArquillianResource URL baseURL) {
        browser.get(baseURL + "index");
        assertThat(browser.getTitle()).isEqualTo("Starter Project Index page");
    }
}

There is no driver setup and no teardown method. Which browser runs is a build property, drone.browser, and the default is headless Chrome. baseURL is the address of the deployed application, wherever the server happens to be.

Page objects with Graphene

Tests that are full of element lookups are hard to read and break when the page changes. Arquillian Graphene lets you describe a page once, as a page object:

@Location("index")
public class IndexPage {
    @FindBy(tagName = "h1")
    private WebElement heading;

    public String heading() {
        return heading.getText();
    }
}

The test asks for the page. Graphene opens it and fills in the elements:

@Test
void heading(@InitialPage IndexPage page) {
    assertThat(page.heading()).isEqualTo("Heading for Starter Project");
}

If the test should decide when to open the page, use a field with @Page instead. Graphene.goTo opens the page at its @Location:

@Page
IndexPage page;

@Test
void heading() {
    Graphene.goTo(IndexPage.class);
    assertThat(page.heading()).isEqualTo("Heading for Starter Project");
}

Waits are optional

Notice that none of the tests above wait for anything. A normal page load does not need wait code.

You need a wait only when JavaScript changes the page after an action, for example when a button sends an AJAX request. Graphene has a one-word answer for that:

guardAjax(saveButton).click();
assertThat(message.getText()).isEqualTo("Saved");

guardAjax clicks and returns when the AJAX request has finished. There are no sleeps and no polling loops in your test.

When you need more

The defaults cover most tests. When a test needs a different archive, for example an extra configuration file, write the @Deployment method for that one test. It is still short, because FlowLogix builds the archive from the POM:

@Deployment
static WebArchive deploy() {
    return ShrinkWrapManipulator.<WebArchive>createDeployment()
            .addAsResource("test-config.properties");
}

What it runs on

  • Modern Java. The build targets Java 25 by default. With -Pserver-docker it also runs on Java 27, because the server lives in the container.

  • Maven 3 and Maven 4.

  • Modern application servers. Payara 7 and GlassFish 8, both Jakarta EE 11.

  • JUnit 5/6 or TestNG is supported using FlowLogix dependency chains.

Common objections

  • "Arquillian is slow." Not anymore. The application is deployed once for the whole suite, and with -Pserver-local the server is already running. After the first deployment, each test class takes a fraction of a second.

  • "These are not real tests, the archive is assembled by hand." That was true of the hand-written @Deployment method, which could differ from what you ship. Here the archive comes from the same Maven POM as the real application, so the test runs what production runs.

  • "Arquillian is the old way, TestContainers is the new way." This setup uses TestContainers. The server runs in a container with -Pserver-docker, and your tests still run inside it with real injection.

Try it

Removing boilerplate is the number one motto of Flow Logix. Go to start.flowlogix.com, keep "Enable Selenium / Drone / Graphene UI Tests" selected, and generate a project. Then run:

./mvnw verify

You get a Jakarta EE application with a passing integration test, and a place to add your first UI test in a few lines.

Example on GitHub

A complete, runnable example is at flowlogix/test-arq-suite on GitHub. It has an extension that checks that only a single deployment is made for the whole suite, and runs a few simple tests. It comes in both flavors:

Run either one with mvn verify. It uses Testcontainers by default.

About the author

Lenny Primak is an open source maintainer, the Apache Shiro PMC Chair, and a contributor to Jakarta EE, Jersey, Weld, Grizzly and Arquillian. Find him on GitHub and LinkedIn.

His Jakarta EE work is sponsored by Flow Logix, which builds open source components for Jakarta EE applications. See the projects at github.com/flowlogix.

This work is unpaid. If it was useful to you, you can support it through GitHub Sponsors: Flow Logix.

Share this page

Found a mistake, or something to add? Edit this page on GitHub

Written by

Lenny Primak

Lenny Primak is an open source maintainer, the Apache Shiro PMC Chair, and a contributor to Jakarta EE, Jersey, Weld, Grizzly and Arquillian. He is also a professional jet pilot based in Nebraska. His open source work is sponsored by Flow Logix.

Related posts

Join the discussion