Testing a MicroProfile or Jakarta EE application

duration 20 minutes

Prerequisites:

Learn how to use MicroShed Testing to test a MicroProfile or Jakarta EE application.

What you’ll learn

You’ll start with an existing REST application that runs on Open Liberty and use MicroShed Testing to write tests for the application that exercise the application in a Docker container.

Sometimes tests might pass in development and testing (dev/test) environments, but fail in production because the application runs differently in production than in dev/test. Fortunately, you can minimize these differences between dev/test and production by testing your application in the same Docker container that you’ll use in production.

What is Docker?

Docker is a tool that you can use to deploy and run applications with containers. You can think of Docker as a virtual machine that runs various applications. However, unlike with a typical virtual machine, you can run these applications simultaneously on a single system and independent of one another.

Learn more about Docker on the official Docker website.

Additional prerequisites

Before you begin, Docker needs to be installed. For installation instructions, refer to the official Docker documentation. You’ll test the application in Docker containers.

Make sure to start your Docker daemon before you proceed.

Getting started

The fastest way to work through this guide is to clone the Git repository and use the projects that are provided inside:

git clone https://github.com/openliberty/guide-microshed-testing.git
cd guide-microshed-testing

The start directory contains the starting project that you will build upon.

The finish directory contains the finished project that you will build.

Before you begin, make sure you have all the necessary prerequisites.

Try what you’ll build

The finish directory in the root of this guide contains the finished application. Give it a try before you proceed.

First, review the PersonServiceIT class to see what the tests look like:

PersonServiceIT.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2019, 2021 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License v1.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-v10.html
  8 *
  9 * Contributors:
 10 *     IBM Corporation - Initial implementation
 11 *******************************************************************************/
 12// end::copyright[]
 13package io.openliberty.guides.testing;
 14
 15import static org.junit.jupiter.api.Assertions.assertEquals;
 16import static org.junit.jupiter.api.Assertions.assertNotNull;
 17import static org.junit.jupiter.api.Assertions.assertTrue;
 18
 19import java.util.Collection;
 20
 21import org.junit.jupiter.api.Test;
 22// tag::importSharedContainerConfig[]
 23import org.microshed.testing.SharedContainerConfig;
 24// end::importSharedContainerConfig[]
 25import org.microshed.testing.jaxrs.RESTClient;
 26import org.microshed.testing.jupiter.MicroShedTest;
 27
 28@MicroShedTest
 29// tag::sharedContainerConfig[]
 30@SharedContainerConfig(AppDeploymentConfig.class)
 31// end::sharedContainerConfig[]
 32public class PersonServiceIT {
 33
 34    @RESTClient
 35    public static PersonService personSvc;
 36
 37    @Test
 38    public void testCreatePerson() {
 39        Long createId = personSvc.createPerson("Hank", 42);
 40        assertNotNull(createId);
 41    }
 42
 43    @Test
 44    public void testMinSizeName() {
 45        Long minSizeNameId = personSvc.createPerson("Ha", 42);
 46        assertEquals(new Person("Ha", 42, minSizeNameId),
 47                     personSvc.getPerson(minSizeNameId));
 48    }
 49
 50    @Test
 51    public void testMinAge() {
 52        Long minAgeId = personSvc.createPerson("Newborn", 0);
 53        assertEquals(new Person("Newborn", 0, minAgeId),
 54                     personSvc.getPerson(minAgeId));
 55    }
 56
 57    @Test
 58    public void testGetPerson() {
 59        Long bobId = personSvc.createPerson("Bob", 24);
 60        Person bob = personSvc.getPerson(bobId);
 61        assertEquals("Bob", bob.name);
 62        assertEquals(24, bob.age);
 63        assertNotNull(bob.id);
 64    }
 65
 66    @Test
 67    public void testGetAllPeople() {
 68        Long person1Id = personSvc.createPerson("Person1", 1);
 69        Long person2Id = personSvc.createPerson("Person2", 2);
 70
 71        Person expected1 = new Person("Person1", 1, person1Id);
 72        Person expected2 = new Person("Person2", 2, person2Id);
 73
 74        Collection<Person> allPeople = personSvc.getAllPeople();
 75        assertTrue(allPeople.size() >= 2,
 76            "Expected at least 2 people to be registered, but there were only: "
 77            + allPeople);
 78        assertTrue(allPeople.contains(expected1),
 79            "Did not find person " + expected1 + " in all people: " + allPeople);
 80        assertTrue(allPeople.contains(expected2),
 81            "Did not find person " + expected2 + " in all people: " + allPeople);
 82    }
 83
 84    @Test
 85    public void testUpdateAge() {
 86        Long personId = personSvc.createPerson("newAgePerson", 1);
 87
 88        Person originalPerson = personSvc.getPerson(personId);
 89        assertEquals("newAgePerson", originalPerson.name);
 90        assertEquals(1, originalPerson.age);
 91        assertEquals(personId, Long.valueOf(originalPerson.id));
 92
 93        personSvc.updatePerson(personId,
 94            new Person(originalPerson.name, 2, originalPerson.id));
 95        Person updatedPerson = personSvc.getPerson(personId);
 96        assertEquals("newAgePerson", updatedPerson.name);
 97        assertEquals(2, updatedPerson.age);
 98        assertEquals(personId, Long.valueOf(updatedPerson.id));
 99    }
100}

To try out the application, go to the finish directory and run the following Maven goal to build the application and run the integration tests on an Open Liberty server in a container:

cd finish
mvn verify

This command might take some time to run initially because the dependencies and the Docker image for Open Liberty must download. If you run the same command again, it will be faster.

The previous example shows how you can run integration tests from a cold start. With Open Liberty development mode, you can use MicroShed Testing to run tests on an active Open Liberty server. Run the following Maven goal to start Open Liberty in development mode:

mvn liberty:dev

After you see the following message, your application server in dev mode is ready:

**************************************************************
*    Liberty is running in dev mode.

After the Open Liberty server starts and you see the To run tests on demand, press Enter. message, you can press the enter/return key to run the integration tests. After the tests finish, you can press the enter/return key to run the tests again, or you can make code changes to the application or tests. Development mode automatically recompiles and updates any application or test code changes that you make.

After you’re finished running tests, exit development mode by pressing CTRL+C in the command-line session where you ran the server, or by typing q and then pressing the enter/return key.

Bootstrapping your application for testing

Navigate to the start directory to begin.

When you run Open Liberty in development mode, known as dev mode, the server listens for file changes and automatically recompiles and deploys your updates whenever you save a new change. Run the following goal to start Open Liberty in dev mode:

mvn liberty:dev

After you see the following message, your application server in dev mode is ready:

**************************************************************
*    Liberty is running in dev mode.

Dev mode holds your command-line session to listen for file changes. Open another command-line session to continue, or open the project in your editor.

Wait for the To run tests on demand, press Enter. message, and then press the enter/return key to run the tests. You see that one test runs:

 Running integration tests...

 -------------------------------------------------------
  T E S T S
 -------------------------------------------------------
 Running io.openliberty.guides.testing.PersonServiceIT
 Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.024 s - in io.openliberty.guides.testing.PersonServiceIT

 Results:

 Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

 Integration tests finished.

To begin bootstrapping, import the MicroShedTest annotation and annotate the PersonServiceIT class with @MicroShedTest. This annotation indicates that the test class uses MicroShed Testing.

The PersonServiceIT class outlines some basic information that informs how MicroShed Testing starts the application runtime and at which URL path the application is available:

Replace the PersonServiceIT class.
src/test/java/io/openliberty/guides/testing/PersonServiceIT.java

PersonServiceIT.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2019, 2021 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License v1.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-v10.html
 8 *
 9 * Contributors:
10 *     IBM Corporation - Initial implementation
11 *******************************************************************************/
12// end::copyright[]
13package io.openliberty.guides.testing;
14
15// tag::importAssertNotNull[]
16import static org.junit.jupiter.api.Assertions.assertNotNull;
17// end::importAssertNotNull[]
18
19import org.junit.jupiter.api.Test;
20// tag::importInject[]
21import org.microshed.testing.jaxrs.RESTClient;
22// end::importInject[]
23// tag::importMicroShedTest[]
24import org.microshed.testing.jupiter.MicroShedTest;
25// end::importMicroShedTest[]
26// tag::importSharedContainerConfig[]
27import org.microshed.testing.SharedContainerConfig;
28// end::importSharedContainerConfig[]
29// tag::importMPApp[]
30import org.microshed.testing.testcontainers.ApplicationContainer;
31// end::importMPApp[]
32// tag::importContainer[]
33import org.testcontainers.junit.jupiter.Container;
34// end::importContainer[]
35
36// tag::microShedTest[]
37@MicroShedTest
38// end::microShedTest[]
39// tag::sharedContainerConfig[]
40@SharedContainerConfig(AppDeploymentConfig.class)
41// end::sharedContainerConfig[]
42public class PersonServiceIT {
43
44    // tag::inject[]
45    @RESTClient
46    // end::inject[]
47    // tag::personSvc[]
48    public static PersonService personSvc;
49    // end::personSvc[]
50
51    // tag::container[]
52    @Container
53    // end::container[]
54    // tag::mpApp[]
55    public static ApplicationContainer app = new ApplicationContainer()
56                    // tag::withAppContextRoot[]
57                    .withAppContextRoot("/guide-microshed-testing")
58                    // end::withAppContextRoot[]
59                    // tag::withReadinessPath[]
60                    .withReadinessPath("/health/ready");
61                    // end::withReadinessPath[]
62    // end::mpApp[]
63
64    @Test
65    public void testCreatePerson() {
66        // tag::testCreatePerson[]
67        Long createId = personSvc.createPerson("Hank", 42);
68        assertNotNull(createId);
69        // end::testCreatePerson[]
70    }
71
72}

Import the ApplicationContainer class and the Container annotation, create the ApplicationContainer application, and annotate the application with @Container annotation.

The withAppContextRoot(String) method indicates the base path of the application. The app context root is the portion of the URL after the hostname and port. In this case, the application is deployed at the http://localhost:9080/guide-microshed-testing URL, so the app context root is /guide-microshed-testing.

server.xml

 1<server>
 2
 3    <featureManager>
 4        <feature>jaxrs-2.1</feature>
 5        <feature>jsonb-1.0</feature>
 6        <!-- tag::mpHealth[] -->
 7        <feature>mpHealth-3.1</feature>
 8        <!-- end::mpHealth[] -->
 9        <feature>mpConfig-2.0</feature>
10        <feature>mpRestClient-2.0</feature>
11        <feature>beanValidation-2.0</feature>
12        <feature>cdi-2.0</feature>
13    </featureManager>
14        
15</server>

The withReadinessPath(String) method indicates what path is polled by HTTP to determine application readiness. MicroShed Testing automatically starts the ApplicationContainer application and waits for it to be ready before the tests start running. In this case, you’re using the default application readiness check at the http://localhost:9080/health/ready URL, which is enabled by the MicroProfile Health feature in the server.xml configuration file. When the readiness URL returns the HTTP 200 message, the application is considered ready and the tests begin running.

Save your changes to the PersonServiceIT class and press the enter/return key in your console window to rerun the tests. You still see only one test running, but the output is different. Notice that MicroShed Testing is using a hollow configuration mode. This configuration mode means that MicroShed Testing is reusing an existing application runtime for the test, not starting up a new application instance each time you initiate a test run.

Talking to your application with a REST client

With MicroShed Testing, applications are exercised in a black-box fashion. Black-box means the tests can’t access the application internals. Instead, the application is exercised from the outside, usually with HTTP requests. To simplify the HTTP interactions, a REST client is injected into the tests. To do this, you imported the org.microshed.testing.jaxrs.RESTClient annotation, created a PersonService REST client, and annotated the REST client with @RESTClient.

In this example, the PersonService injected type is the same io.openliberty.guides.testing.PersonService class that is used in your application. However, the instance that gets injected is a REST client proxy. So, if you call personSvc.createPerson("Bob", 42), the REST client makes an HTTP POST request to the application that is running at http://localhost:9080/guide-microshed-testing/people URL, which triggers the corresponding Java method in the application.

PersonServiceIT.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2019, 2021 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License v1.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-v10.html
 8 *
 9 * Contributors:
10 *     IBM Corporation - Initial implementation
11 *******************************************************************************/
12// end::copyright[]
13package io.openliberty.guides.testing;
14
15// tag::importAssertNotNull[]
16import static org.junit.jupiter.api.Assertions.assertNotNull;
17// end::importAssertNotNull[]
18
19import org.junit.jupiter.api.Test;
20// tag::importInject[]
21import org.microshed.testing.jaxrs.RESTClient;
22// end::importInject[]
23// tag::importMicroShedTest[]
24import org.microshed.testing.jupiter.MicroShedTest;
25// end::importMicroShedTest[]
26// tag::importSharedContainerConfig[]
27import org.microshed.testing.SharedContainerConfig;
28// end::importSharedContainerConfig[]
29// tag::importMPApp[]
30import org.microshed.testing.testcontainers.ApplicationContainer;
31// end::importMPApp[]
32// tag::importContainer[]
33import org.testcontainers.junit.jupiter.Container;
34// end::importContainer[]
35
36// tag::microShedTest[]
37@MicroShedTest
38// end::microShedTest[]
39// tag::sharedContainerConfig[]
40@SharedContainerConfig(AppDeploymentConfig.class)
41// end::sharedContainerConfig[]
42public class PersonServiceIT {
43
44    // tag::inject[]
45    @RESTClient
46    // end::inject[]
47    // tag::personSvc[]
48    public static PersonService personSvc;
49    // end::personSvc[]
50
51    // tag::container[]
52    @Container
53    // end::container[]
54    // tag::mpApp[]
55    public static ApplicationContainer app = new ApplicationContainer()
56                    // tag::withAppContextRoot[]
57                    .withAppContextRoot("/guide-microshed-testing")
58                    // end::withAppContextRoot[]
59                    // tag::withReadinessPath[]
60                    .withReadinessPath("/health/ready");
61                    // end::withReadinessPath[]
62    // end::mpApp[]
63
64    @Test
65    public void testCreatePerson() {
66        // tag::testCreatePerson[]
67        Long createId = personSvc.createPerson("Hank", 42);
68        assertNotNull(createId);
69        // end::testCreatePerson[]
70    }
71
72}

PersonService.java

 1// tag::copyright[]
 2/*
 3 * Copyright (c) 2019 IBM Corporation and others
 4 *
 5 * See the NOTICE file(s) distributed with this work for additional
 6 * information regarding copyright ownership.
 7 *
 8 * Licensed under the Apache License, Version 2.0 (the "License");
 9 * You may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
11 *
12 *     http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 */
20// end::copyright[]
21package io.openliberty.guides.testing;
22
23import java.util.Collection;
24import java.util.HashMap;
25import java.util.Map;
26
27import javax.enterprise.context.ApplicationScoped;
28import javax.validation.Valid;
29import javax.validation.constraints.NotEmpty;
30import javax.validation.constraints.PositiveOrZero;
31import javax.validation.constraints.Size;
32import javax.ws.rs.Consumes;
33import javax.ws.rs.DELETE;
34import javax.ws.rs.GET;
35import javax.ws.rs.NotFoundException;
36import javax.ws.rs.POST;
37import javax.ws.rs.Path;
38import javax.ws.rs.PathParam;
39import javax.ws.rs.Produces;
40import javax.ws.rs.QueryParam;
41import javax.ws.rs.core.MediaType;
42
43@Path("/people")
44@ApplicationScoped
45@Produces(MediaType.APPLICATION_JSON)
46@Consumes(MediaType.APPLICATION_JSON)
47public class PersonService {
48
49    private final Map<Long, Person> personRepo = new HashMap<>();
50
51    @GET
52    public Collection<Person> getAllPeople() {
53        return personRepo.values();
54    }
55
56    @GET
57    @Path("/{personId}")
58    public Person getPerson(@PathParam("personId") long id) {
59        Person foundPerson = personRepo.get(id);
60        if (foundPerson == null)
61            personNotFound(id);
62        return foundPerson;
63    }
64
65    @POST
66    public Long createPerson(@QueryParam("name") @NotEmpty @Size(min=2, max=50) String name,
67                             @QueryParam("age") @PositiveOrZero int age) {
68        Person p = new Person(name, age);
69        personRepo.put(p.id, p);
70        return p.id;
71    }
72
73    @POST
74    @Path("/{personId}")
75    public void updatePerson(@PathParam("personId") long id, @Valid Person p) {
76        Person toUpdate = getPerson(id);
77        if (toUpdate == null)
78            personNotFound(id);
79        personRepo.put(id, p);
80    }
81
82    @DELETE
83    @Path("/{personId}")
84    public void removePerson(@PathParam("personId") long id) {
85        Person toDelete = personRepo.get(id);
86        if (toDelete == null)
87            personNotFound(id);
88        personRepo.remove(id);
89    }
90    
91    private void personNotFound(long id) {
92        throw new NotFoundException("Person with id " + id + " not found.");
93    }
94
95}

Writing your first test

Now that the setup is complete, you can write your first test case. Start by testing the basic "create person" use case for your REST-based application. To test this use case, use the REST client that’s injected by MicroShed Testing to make the HTTP POST request to the application and read the response.

Replace the PersonServiceIT class.
src/test/java/io/openliberty/guides/testing/PersonServiceIT.java

PersonServiceIT.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2019, 2021 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License v1.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-v10.html
 8 *
 9 * Contributors:
10 *     IBM Corporation - Initial implementation
11 *******************************************************************************/
12// end::copyright[]
13package io.openliberty.guides.testing;
14
15// tag::importAssertNotNull[]
16import static org.junit.jupiter.api.Assertions.assertNotNull;
17// end::importAssertNotNull[]
18
19import org.junit.jupiter.api.Test;
20// tag::importInject[]
21import org.microshed.testing.jaxrs.RESTClient;
22// end::importInject[]
23// tag::importMicroShedTest[]
24import org.microshed.testing.jupiter.MicroShedTest;
25// end::importMicroShedTest[]
26// tag::importSharedContainerConfig[]
27import org.microshed.testing.SharedContainerConfig;
28// end::importSharedContainerConfig[]
29// tag::importMPApp[]
30import org.microshed.testing.testcontainers.ApplicationContainer;
31// end::importMPApp[]
32// tag::importContainer[]
33import org.testcontainers.junit.jupiter.Container;
34// end::importContainer[]
35
36// tag::microShedTest[]
37@MicroShedTest
38// end::microShedTest[]
39// tag::sharedContainerConfig[]
40@SharedContainerConfig(AppDeploymentConfig.class)
41// end::sharedContainerConfig[]
42public class PersonServiceIT {
43
44    // tag::inject[]
45    @RESTClient
46    // end::inject[]
47    // tag::personSvc[]
48    public static PersonService personSvc;
49    // end::personSvc[]
50
51    // tag::container[]
52    @Container
53    // end::container[]
54    // tag::mpApp[]
55    public static ApplicationContainer app = new ApplicationContainer()
56                    // tag::withAppContextRoot[]
57                    .withAppContextRoot("/guide-microshed-testing")
58                    // end::withAppContextRoot[]
59                    // tag::withReadinessPath[]
60                    .withReadinessPath("/health/ready");
61                    // end::withReadinessPath[]
62    // end::mpApp[]
63
64    @Test
65    public void testCreatePerson() {
66        // tag::testCreatePerson[]
67        Long createId = personSvc.createPerson("Hank", 42);
68        assertNotNull(createId);
69        // end::testCreatePerson[]
70    }
71
72}

Replace the PersonServiceIT class to include the assertNotNull static method and write the test logic in the testCreatePerson() method.

Save the changes. Then, press the enter/return key in your console window to run the test. You see that the test ran again and exercised the REST endpoint of your application, including the response of your application’s endpoint:

[INFO] Building rest client for class io.openliberty.guides.testing.PersonService with base path: http://localhost:9080/guide-microshed-testing/ and providers: [class org.microshed.testing.jaxrs.JsonBProvider]
[INFO] Response from server: 1809686877352335426

Next, add more tests.

Replace the PersonServiceIT class.
src/test/java/io/openliberty/guides/testing/PersonServiceIT.java

PersonServiceIT.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2019, 2021 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License v1.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-v10.html
  8 *
  9 * Contributors:
 10 *     IBM Corporation - Initial implementation
 11 *******************************************************************************/
 12// end::copyright[]
 13package io.openliberty.guides.testing;
 14
 15import static org.junit.jupiter.api.Assertions.assertEquals;
 16// tag::importAssertNotNull[]
 17import static org.junit.jupiter.api.Assertions.assertNotNull;
 18// end::importAssertNotNull[]
 19import static org.junit.jupiter.api.Assertions.assertTrue;
 20
 21import java.util.Collection;
 22
 23import org.junit.jupiter.api.Test;
 24import org.microshed.testing.jaxrs.RESTClient;
 25import org.microshed.testing.jupiter.MicroShedTest;
 26// tag::importMPApp[]
 27import org.microshed.testing.testcontainers.ApplicationContainer;
 28// end::importMPApp[]
 29// tag::importContainer[]
 30import org.testcontainers.junit.jupiter.Container;
 31// end::importContainer[]
 32
 33@MicroShedTest
 34public class PersonServiceIT {
 35
 36    @RESTClient
 37    public static PersonService personSvc;
 38
 39    // tag::container[]
 40    @Container
 41    // end::container[]
 42    // tag::mpApp[]
 43    public static ApplicationContainer app = new ApplicationContainer()
 44                    .withAppContextRoot("/guide-microshed-testing")
 45                    .withReadinessPath("/health/ready");
 46    // end::mpApp[]
 47
 48    @Test
 49    public void testCreatePerson() {
 50        // tag::testCreatePerson[]
 51        Long createId = personSvc.createPerson("Hank", 42);
 52        assertNotNull(createId);
 53        // end::testCreatePerson[]
 54    }
 55
 56    // tag::tests[]
 57    // tag::testMinSizeName[]
 58    @Test
 59    public void testMinSizeName() {
 60        Long minSizeNameId = personSvc.createPerson("Ha", 42);
 61        assertEquals(new Person("Ha", 42, minSizeNameId),
 62                     personSvc.getPerson(minSizeNameId));
 63    }
 64    // end::testMinSizeName[]
 65
 66    // tag::testMinAge[]
 67    @Test
 68    public void testMinAge() {
 69        Long minAgeId = personSvc.createPerson("Newborn", 0);
 70        assertEquals(new Person("Newborn", 0, minAgeId),
 71                     personSvc.getPerson(minAgeId));
 72    }
 73    // end::testMinAge[]
 74
 75    // tag::testGetPerson[]
 76    @Test
 77    public void testGetPerson() {
 78        Long bobId = personSvc.createPerson("Bob", 24);
 79        Person bob = personSvc.getPerson(bobId);
 80        assertEquals("Bob", bob.name);
 81        assertEquals(24, bob.age);
 82        assertNotNull(bob.id);
 83    }
 84    // end::testGetPerson[]
 85
 86    // tag::testGetAllPeople[]
 87    @Test
 88    public void testGetAllPeople() {
 89        Long person1Id = personSvc.createPerson("Person1", 1);
 90        Long person2Id = personSvc.createPerson("Person2", 2);
 91
 92        Person expected1 = new Person("Person1", 1, person1Id);
 93        Person expected2 = new Person("Person2", 2, person2Id);
 94
 95        Collection<Person> allPeople = personSvc.getAllPeople();
 96        assertTrue(allPeople.size() >= 2,
 97            "Expected at least 2 people to be registered, but there were only: "
 98            + allPeople);
 99        assertTrue(allPeople.contains(expected1),
100            "Did not find person " + expected1 + " in all people: " + allPeople);
101        assertTrue(allPeople.contains(expected2),
102            "Did not find person " + expected2 + " in all people: " + allPeople);
103    }
104    // end::testGetAllPeople[]
105
106    // tag::testUpdateAge[]
107    @Test
108    public void testUpdateAge() {
109        Long personId = personSvc.createPerson("newAgePerson", 1);
110
111        Person originalPerson = personSvc.getPerson(personId);
112        assertEquals("newAgePerson", originalPerson.name);
113        assertEquals(1, originalPerson.age);
114        assertEquals(personId, Long.valueOf(originalPerson.id));
115
116        personSvc.updatePerson(personId,
117            new Person(originalPerson.name, 2, originalPerson.id));
118        Person updatedPerson = personSvc.getPerson(personId);
119        assertEquals("newAgePerson", updatedPerson.name);
120        assertEquals(2, updatedPerson.age);
121        assertEquals(personId, Long.valueOf(updatedPerson.id));
122    }
123    // end::testUpdateAge[]
124    // end::tests[]
125}

The following tests are added: testMinSizeName(), testMinAge(), testGetPerson(), testGetAllPeople(), and testUpdateAge().

Save the changes, and press the enter/return key in your console window to run the tests.

Testing outside of development mode

Running tests in development mode is convenient for local development, but it can be tedious to test against a running Open Liberty server in non-development scenarios such as CI/CD pipelines. For this reason, MicroShed Testing can start and stop the application runtime before and after the tests are run. This process is primarily accomplished by using Docker and Testcontainers.

To test outside of development mode, exit development mode by pressing CTRL+C in the command-line session where you ran the server, or by typing q and then pressing the enter/return key.

Next, use the following Maven goal to run the tests from a cold start:

mvn verify

Running tests from a cold start takes a little longer than running tests from development mode because the application runtime needs to start each time. However, tests that are run from a cold start use a clean instance on each run to ensure consistent results. These tests also automatically hook into existing build pipelines that are set up to run the integration-test phase.

Sharing configuration across multiple classes

Typically, projects have multiple test classes that all use the same type of application deployment. For these cases, it’s useful to reuse an existing configuration and application lifecycle across multiple test classes.

First, create another test class.

Create the ErrorPathIT class.
src/test/java/io/openliberty/guides/testing/ErrorPathIT.java

ErrorPathIT.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2019, 2021 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License v1.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-v10.html
 8 *
 9 * Contributors:
10 *     IBM Corporation - Initial implementation
11 *******************************************************************************/
12// end::copyright[]
13package io.openliberty.guides.testing;
14
15import static org.junit.jupiter.api.Assertions.assertThrows;
16
17import javax.ws.rs.BadRequestException;
18import javax.ws.rs.NotFoundException;
19
20import org.junit.jupiter.api.Test;
21import org.microshed.testing.jupiter.MicroShedTest;
22// tag::importSharedContainerConfig[]
23import org.microshed.testing.SharedContainerConfig;
24// end::importSharedContainerConfig[]
25// tag::importMPApp[]
26import org.microshed.testing.testcontainers.ApplicationContainer;
27// end::importMPApp[]
28// tag::importContainer[]
29import org.testcontainers.junit.jupiter.Container;
30// end::importContainer[]
31import org.microshed.testing.jaxrs.RESTClient;
32
33@MicroShedTest
34// tag::sharedContainerConfig[]
35@SharedContainerConfig(AppDeploymentConfig.class)
36// end::sharedContainerConfig[]
37public class ErrorPathIT {
38
39    // tag::container[]
40    @Container
41    public static ApplicationContainer app = new ApplicationContainer()
42                    .withAppContextRoot("/guide-microshed-testing")
43                    .withReadinessPath("/health/ready");
44    // end::container[]
45
46    // tag::personSvc[]
47    @RESTClient
48    public static PersonService personSvc;
49    // end::personSvc[]
50
51    @Test
52    public void testGetUnknownPerson() {
53        assertThrows(NotFoundException.class, () -> personSvc.getPerson(-1L));
54    }
55
56    @Test
57    public void testCreateBadPersonNullName() {
58        assertThrows(BadRequestException.class, () -> personSvc.createPerson(null, 5));
59    }
60
61    @Test
62    public void testCreateBadPersonNegativeAge() {
63        assertThrows(BadRequestException.class, () ->
64          personSvc.createPerson("NegativeAgePersoN", -1));
65    }
66
67    @Test
68    public void testCreateBadPersonNameTooLong() {
69        assertThrows(BadRequestException.class, () ->
70          personSvc.createPerson("NameTooLongPersonNameTooLongPersonNameTooLongPerson",
71          5));
72    }
73}

The ErrorPathIT test class has the same @Container configuration and PersonService REST client as the PersonServiceIT class.

Now, run the tests again outside of development mode:

mvn verify

Notice that tests for both the PersonServiceIT and ErrorPathIT classes run, but a new server starts for each test class, resulting in a longer test runtime.

Creating a common configuration

To solve this issue, common configuration can be placed in a class that implements SharedContainerConfiguration.

Create the AppDeploymentConfig class.
src/test/java/io/openliberty/guides/testing/AppDeploymentConfig.java

AppDeploymentConfig.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2019, 2021 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License v1.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-v10.html
 8 *
 9 * Contributors:
10 *     IBM Corporation - Initial implementation
11 *******************************************************************************/
12// end::copyright[]
13package io.openliberty.guides.testing;
14
15import org.microshed.testing.SharedContainerConfiguration;
16import org.microshed.testing.testcontainers.ApplicationContainer;
17import org.testcontainers.junit.jupiter.Container;
18
19public class AppDeploymentConfig implements SharedContainerConfiguration {
20
21    @Container
22    public static ApplicationContainer app = new ApplicationContainer()
23                    .withAppContextRoot("/guide-microshed-testing")
24                    .withReadinessPath("/health/ready");
25
26}

After the common configuration is created, the test classes can be updated to reference this shared configuration.

Updating the PersonServiceIT class

PersonServiceIT.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2019, 2021 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License v1.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-v10.html
  8 *
  9 * Contributors:
 10 *     IBM Corporation - Initial implementation
 11 *******************************************************************************/
 12// end::copyright[]
 13package io.openliberty.guides.testing;
 14
 15import static org.junit.jupiter.api.Assertions.assertEquals;
 16// tag::importAssertNotNull[]
 17import static org.junit.jupiter.api.Assertions.assertNotNull;
 18// end::importAssertNotNull[]
 19import static org.junit.jupiter.api.Assertions.assertTrue;
 20
 21import java.util.Collection;
 22
 23import org.junit.jupiter.api.Test;
 24import org.microshed.testing.jaxrs.RESTClient;
 25import org.microshed.testing.jupiter.MicroShedTest;
 26// tag::importMPApp[]
 27import org.microshed.testing.testcontainers.ApplicationContainer;
 28// end::importMPApp[]
 29// tag::importContainer[]
 30import org.testcontainers.junit.jupiter.Container;
 31// end::importContainer[]
 32
 33@MicroShedTest
 34public class PersonServiceIT {
 35
 36    @RESTClient
 37    public static PersonService personSvc;
 38
 39    // tag::container[]
 40    @Container
 41    // end::container[]
 42    // tag::mpApp[]
 43    public static ApplicationContainer app = new ApplicationContainer()
 44                    .withAppContextRoot("/guide-microshed-testing")
 45                    .withReadinessPath("/health/ready");
 46    // end::mpApp[]
 47
 48    @Test
 49    public void testCreatePerson() {
 50        // tag::testCreatePerson[]
 51        Long createId = personSvc.createPerson("Hank", 42);
 52        assertNotNull(createId);
 53        // end::testCreatePerson[]
 54    }
 55
 56    // tag::tests[]
 57    // tag::testMinSizeName[]
 58    @Test
 59    public void testMinSizeName() {
 60        Long minSizeNameId = personSvc.createPerson("Ha", 42);
 61        assertEquals(new Person("Ha", 42, minSizeNameId),
 62                     personSvc.getPerson(minSizeNameId));
 63    }
 64    // end::testMinSizeName[]
 65
 66    // tag::testMinAge[]
 67    @Test
 68    public void testMinAge() {
 69        Long minAgeId = personSvc.createPerson("Newborn", 0);
 70        assertEquals(new Person("Newborn", 0, minAgeId),
 71                     personSvc.getPerson(minAgeId));
 72    }
 73    // end::testMinAge[]
 74
 75    // tag::testGetPerson[]
 76    @Test
 77    public void testGetPerson() {
 78        Long bobId = personSvc.createPerson("Bob", 24);
 79        Person bob = personSvc.getPerson(bobId);
 80        assertEquals("Bob", bob.name);
 81        assertEquals(24, bob.age);
 82        assertNotNull(bob.id);
 83    }
 84    // end::testGetPerson[]
 85
 86    // tag::testGetAllPeople[]
 87    @Test
 88    public void testGetAllPeople() {
 89        Long person1Id = personSvc.createPerson("Person1", 1);
 90        Long person2Id = personSvc.createPerson("Person2", 2);
 91
 92        Person expected1 = new Person("Person1", 1, person1Id);
 93        Person expected2 = new Person("Person2", 2, person2Id);
 94
 95        Collection<Person> allPeople = personSvc.getAllPeople();
 96        assertTrue(allPeople.size() >= 2,
 97            "Expected at least 2 people to be registered, but there were only: "
 98            + allPeople);
 99        assertTrue(allPeople.contains(expected1),
100            "Did not find person " + expected1 + " in all people: " + allPeople);
101        assertTrue(allPeople.contains(expected2),
102            "Did not find person " + expected2 + " in all people: " + allPeople);
103    }
104    // end::testGetAllPeople[]
105
106    // tag::testUpdateAge[]
107    @Test
108    public void testUpdateAge() {
109        Long personId = personSvc.createPerson("newAgePerson", 1);
110
111        Person originalPerson = personSvc.getPerson(personId);
112        assertEquals("newAgePerson", originalPerson.name);
113        assertEquals(1, originalPerson.age);
114        assertEquals(personId, Long.valueOf(originalPerson.id));
115
116        personSvc.updatePerson(personId,
117            new Person(originalPerson.name, 2, originalPerson.id));
118        Person updatedPerson = personSvc.getPerson(personId);
119        assertEquals("newAgePerson", updatedPerson.name);
120        assertEquals(2, updatedPerson.age);
121        assertEquals(personId, Long.valueOf(updatedPerson.id));
122    }
123    // end::testUpdateAge[]
124    // end::tests[]
125}

Remove the container code from the PersonServiceIT class. Remove import statements for ApplicationContainer and Container and the ApplicationContainer app field.

Next, annotate the PersonServiceIT class with the @SharedContainerConfig annotation that references the AppDeploymentConfig shared configuration class.

Replace the PersonServiceIT class.
src/test/java/io/openliberty/guides/testing/PersonServiceIT.java

PersonServiceIT.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2019, 2021 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License v1.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-v10.html
  8 *
  9 * Contributors:
 10 *     IBM Corporation - Initial implementation
 11 *******************************************************************************/
 12// end::copyright[]
 13package io.openliberty.guides.testing;
 14
 15import static org.junit.jupiter.api.Assertions.assertEquals;
 16import static org.junit.jupiter.api.Assertions.assertNotNull;
 17import static org.junit.jupiter.api.Assertions.assertTrue;
 18
 19import java.util.Collection;
 20
 21import org.junit.jupiter.api.Test;
 22// tag::importSharedContainerConfig[]
 23import org.microshed.testing.SharedContainerConfig;
 24// end::importSharedContainerConfig[]
 25import org.microshed.testing.jaxrs.RESTClient;
 26import org.microshed.testing.jupiter.MicroShedTest;
 27
 28@MicroShedTest
 29// tag::sharedContainerConfig[]
 30@SharedContainerConfig(AppDeploymentConfig.class)
 31// end::sharedContainerConfig[]
 32public class PersonServiceIT {
 33
 34    @RESTClient
 35    public static PersonService personSvc;
 36
 37    @Test
 38    public void testCreatePerson() {
 39        Long createId = personSvc.createPerson("Hank", 42);
 40        assertNotNull(createId);
 41    }
 42
 43    @Test
 44    public void testMinSizeName() {
 45        Long minSizeNameId = personSvc.createPerson("Ha", 42);
 46        assertEquals(new Person("Ha", 42, minSizeNameId),
 47                     personSvc.getPerson(minSizeNameId));
 48    }
 49
 50    @Test
 51    public void testMinAge() {
 52        Long minAgeId = personSvc.createPerson("Newborn", 0);
 53        assertEquals(new Person("Newborn", 0, minAgeId),
 54                     personSvc.getPerson(minAgeId));
 55    }
 56
 57    @Test
 58    public void testGetPerson() {
 59        Long bobId = personSvc.createPerson("Bob", 24);
 60        Person bob = personSvc.getPerson(bobId);
 61        assertEquals("Bob", bob.name);
 62        assertEquals(24, bob.age);
 63        assertNotNull(bob.id);
 64    }
 65
 66    @Test
 67    public void testGetAllPeople() {
 68        Long person1Id = personSvc.createPerson("Person1", 1);
 69        Long person2Id = personSvc.createPerson("Person2", 2);
 70
 71        Person expected1 = new Person("Person1", 1, person1Id);
 72        Person expected2 = new Person("Person2", 2, person2Id);
 73
 74        Collection<Person> allPeople = personSvc.getAllPeople();
 75        assertTrue(allPeople.size() >= 2,
 76            "Expected at least 2 people to be registered, but there were only: "
 77            + allPeople);
 78        assertTrue(allPeople.contains(expected1),
 79            "Did not find person " + expected1 + " in all people: " + allPeople);
 80        assertTrue(allPeople.contains(expected2),
 81            "Did not find person " + expected2 + " in all people: " + allPeople);
 82    }
 83
 84    @Test
 85    public void testUpdateAge() {
 86        Long personId = personSvc.createPerson("newAgePerson", 1);
 87
 88        Person originalPerson = personSvc.getPerson(personId);
 89        assertEquals("newAgePerson", originalPerson.name);
 90        assertEquals(1, originalPerson.age);
 91        assertEquals(personId, Long.valueOf(originalPerson.id));
 92
 93        personSvc.updatePerson(personId,
 94            new Person(originalPerson.name, 2, originalPerson.id));
 95        Person updatedPerson = personSvc.getPerson(personId);
 96        assertEquals("newAgePerson", updatedPerson.name);
 97        assertEquals(2, updatedPerson.age);
 98        assertEquals(personId, Long.valueOf(updatedPerson.id));
 99    }
100}

Import the SharedContainerConfig annotation and annotate the PersonServiceIT class with @SharedContainerConfig.

Updating the ErrorPathIT class

ErrorPathIT.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2019, 2021 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License v1.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-v10.html
 8 *
 9 * Contributors:
10 *     IBM Corporation - Initial implementation
11 *******************************************************************************/
12// end::copyright[]
13package io.openliberty.guides.testing;
14
15import static org.junit.jupiter.api.Assertions.assertThrows;
16
17import javax.ws.rs.BadRequestException;
18import javax.ws.rs.NotFoundException;
19
20import org.junit.jupiter.api.Test;
21import org.microshed.testing.jupiter.MicroShedTest;
22// tag::importSharedContainerConfig[]
23import org.microshed.testing.SharedContainerConfig;
24// end::importSharedContainerConfig[]
25// tag::importMPApp[]
26import org.microshed.testing.testcontainers.ApplicationContainer;
27// end::importMPApp[]
28// tag::importContainer[]
29import org.testcontainers.junit.jupiter.Container;
30// end::importContainer[]
31import org.microshed.testing.jaxrs.RESTClient;
32
33@MicroShedTest
34// tag::sharedContainerConfig[]
35@SharedContainerConfig(AppDeploymentConfig.class)
36// end::sharedContainerConfig[]
37public class ErrorPathIT {
38
39    // tag::container[]
40    @Container
41    public static ApplicationContainer app = new ApplicationContainer()
42                    .withAppContextRoot("/guide-microshed-testing")
43                    .withReadinessPath("/health/ready");
44    // end::container[]
45
46    // tag::personSvc[]
47    @RESTClient
48    public static PersonService personSvc;
49    // end::personSvc[]
50
51    @Test
52    public void testGetUnknownPerson() {
53        assertThrows(NotFoundException.class, () -> personSvc.getPerson(-1L));
54    }
55
56    @Test
57    public void testCreateBadPersonNullName() {
58        assertThrows(BadRequestException.class, () -> personSvc.createPerson(null, 5));
59    }
60
61    @Test
62    public void testCreateBadPersonNegativeAge() {
63        assertThrows(BadRequestException.class, () ->
64          personSvc.createPerson("NegativeAgePersoN", -1));
65    }
66
67    @Test
68    public void testCreateBadPersonNameTooLong() {
69        assertThrows(BadRequestException.class, () ->
70          personSvc.createPerson("NameTooLongPersonNameTooLongPersonNameTooLongPerson",
71          5));
72    }
73}

Similarly, replace the ErrorPathIT class to remove the container code. Remove import statements for ApplicationContainer and Container and the ApplicationContainer app field.

Next, annotate the ErrorPathIT class with the @SharedContainerConfig annotation.

Replace the ErrorPathIT class.
src/test/java/io/openliberty/guides/testing/ErrorPathIT.java

ErrorPathIT.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2019, 2021 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License v1.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-v10.html
 8 *
 9 * Contributors:
10 *     IBM Corporation - Initial implementation
11 *******************************************************************************/
12// end::copyright[]
13package io.openliberty.guides.testing;
14
15import static org.junit.jupiter.api.Assertions.assertThrows;
16
17import javax.ws.rs.BadRequestException;
18import javax.ws.rs.NotFoundException;
19
20import org.junit.jupiter.api.Test;
21// tag::importSharedContainerConfig[]
22import org.microshed.testing.SharedContainerConfig;
23// end::importSharedContainerConfig[]
24import org.microshed.testing.jaxrs.RESTClient;
25import org.microshed.testing.jupiter.MicroShedTest;
26
27@MicroShedTest
28// tag::sharedContainerConfig[]
29@SharedContainerConfig(AppDeploymentConfig.class)
30// end::sharedContainerConfig[]
31public class ErrorPathIT {
32
33    @RESTClient
34    public static PersonService personSvc;
35
36    @Test
37    public void testGetUnknownPerson() {
38        assertThrows(NotFoundException.class, () -> personSvc.getPerson(-1L));
39    }
40
41    @Test
42    public void testCreateBadPersonNullName() {
43        assertThrows(BadRequestException.class, () -> personSvc.createPerson(null, 5));
44    }
45
46    @Test
47    public void testCreateBadPersonNegativeAge() {
48        assertThrows(BadRequestException.class, () ->
49          personSvc.createPerson("NegativeAgePersoN", -1));
50    }
51
52    @Test
53    public void testCreateBadPersonNameTooLong() {
54        assertThrows(BadRequestException.class, () ->
55           personSvc.createPerson("NameTooLongPersonNameTooLongPersonNameTooLongPerson",
56           5));
57    }
58}

Import the SharedContainerConfig annotation and annotate the ErrorPathIT class with @SharedContainerConfig.

If you rerun the tests now, they run in about half the time because the same server instance is being used for both test classes:

mvn verify

Great work! You’re done!

You developed automated tests for a REST service in Open Liberty by using MicroShed Testing and Open Liberty development mode.

Learn more about MicroShed Testing.

Guide Attribution

Testing a MicroProfile or Jakarta EE application by Open Liberty is licensed under CC BY-ND 4.0

Copied to clipboard
Copy code block
Copy file contents

Prerequisites:

Nice work! Where to next?

What did you think of this guide?

Extreme Dislike Dislike Like Extreme Like

What could make this guide better?

Raise an issue to share feedback

Create a pull request to contribute to this guide

Need help?

Ask a question on Stack Overflow

Like Open Liberty? Star our repo on GitHub.

Star