SlideShare a Scribd company logo
1 of 34
Easy Java Integration
Testing with
Testcontainers
Simplifying Integration Tests for Enterprise Java
Fabio Turizo
Speaking Today
Fabio Turizo
Service Manager
@fabturizo
• Strategic Members of the Eclipse Foundation
• Project Management Committee member of Jakarta EE
Payara Services Helps Shape the
Future of the Industry
Integration Testing Basics
• A level above basic unit testing
• Multiple units come together to be tested
• Goal: Expose flaws in interface design
• Guarantee platform updates
• Test system dependencies
Integration Testing - Java
• Simple UT frameworks
• Junit, TestNG, Spock
• Highly dependable of the platform
• What about Mocking ?
• Good to simulate interactions
• Bad for real-time scenarios
Integration Testing - Java
• “Works in my machine” persists
• Lots of challenges for Enterprise Java
• Jakarta EE / MicroProfile lack proper tools
• Middleware size footprint has reduced a lot!
• … But complex environments have lots of dependencies 
• What about cloud-native applications?
Arquillian Framework
• Focus on testing Jakarta EE components
• Vendor-agnostic !
• Portable(*) Shrink-wrapped tests
• Container-specific adapters need to be written
• Added complexity in writing tests
Arquillian Sample (JUnit 4.x)
@RunWith(Arquillian.class)
public class PersonDaoTest {
@EJB
private PersonDao personDao;
@Inject TestData testData;
@Deployment
public static WebArchive createDeployment() {
return ShrinkWrap.create(WebArchive.class, "arquillian-example.war")
.addClass(Person.class)
.addClass(PersonDao.class)
.addAsResource("test-persistence.xml", "META-INF/persistence.xml");
}
Arquillian Sample (JUnit 4.x)
@Before
public void prepareTestData() {
testData.prepareForShouldReturnAllPerson();
}
@Test
public void shouldReturnAllPerson() throws Exception {
List<Person> personList = personDao.getAll();
assertNotNull(personList);
assertThat(personList.size(), is(1));
assertThat(personList.get(0).getName(), is("John"));
assertThat(personList.get(0).getLastName(), is("Malkovich"));
}
Arquillian Sample (JUnit 4.x)
@Dependent
public static class TestData {
@PersistenceContext
private EntityManager entityManager;
@Transactional
public void prepareForShouldReturnAllPerson() {
entityManager.persist(new Person("John", "Malkovich"));
}
}
}
Some Gaps to be Filled 
• Test issues:
• Assemble a *part of the application* to test it
• This includes code and resources
• The persistence layer is tested, but not the store
• No way to test different configurations
• Sadly, not a real-world test
Enter Testcontainers!
• Lightweight unit testing
• Based on Docker containers
• Ease up networking setup
• Data access layer tests support
• Fully* portable integration tests!
Testcontainers Benefits
• Effective black-box testing
• Tests are user-focused
• Run UA testing with little overhead
• Possible to audit security standards
• Identify flaws in specific technologies
Testcontainers Requirements
• Docker (only Linux containers, though)
• Test Frameworks
• Junit 4
• Junit 5
• Spock
• Maven/Gradle Dependencies
Getting Started – JUnit5
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.8.1</version>
<scope>test</scope>
</dependency>
Getting Started – TC + JUnit5
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers</artifactId>
<version>1.17.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<version>1.17.3</version>
<scope>test</scope>
</dependency>
Testcontainer Setup
@TestContainers
public class BasicApplicationTest{
@Container
GenericContainer myappContainer = new
GenericContainer(DockerImageName.parse(“fturizo/myapp"))
.withExposedPorts(8080, 9009, 28080)
.withCommand(“./deploy-application.sh”);
@Test
public void test_running(){
assert(isTrue(myappcontainer.isRunning()));
}
}
Container Access - Boundary
@Test
public void test_application(){
String url = String.format(“http://%s:%s/%s”,
myappContainer.getHost(),
myappContainer.getMappedPort(8080), “/myapp”);
int status = http.get(url).response().status();
//Careful!
assertEquals(status, 200);
}
Waiting for Readiness - HTTP
@TestContainers
public class BasicApplicationTest{
@Container
GenericContainer myappContainer = new
GenericContainer(DockerImageName.parse(“fturizo/myapp"))
.withExposedPorts(8080, 9009, 28080)
.waitingFor(Wait.forHttp(“/myapp/ready”)
.forStatusCode(200));
}
Waiting for Readiness – Log Message
@TestContainers
public class BasicApplicationTest{
@Container
GenericContainer myappContainer = new
GenericContainer(DockerImageName.parse(“fturizo/myapp"))
.withExposedPorts(8080, 9009, 28080)
.waitingFor(Wait.forLogMessage(“.*Application
is ready.*”);
}
Dependency Configuration (1)
Network network = Network.newNetwork();
@Container
GenericContainer dbContainer = new
GenericContainer(DockerImageName.parse(“mysql:8.0"))
.withEnv(“MYSQL_ROOT_PASSWORD”, “rootPass”)
.withEnv(“MYSQL_USER”, “test”)
.withEnv(“MYSQL_PASSWORD”, “test”)
.withEnv(“MYSQL_DATABASE”, “testDB”)
.withNetwork(network)
.withNetworkAlias(“mysql_db”);
Dependency Configuration (2)
@Container
GenericContainer appContainer = new
GenericContainer(DockerImageName.parse(“fturizo/myapp"))
.withEnv(“DB_SERVER”, “mysql_db”)
.withEnv(“DB_USER”, “test”)
.withEnv(“DB_PASSWORD”, “test”)
.withEnv(“DB_NAME”, “testDB”)
.withNetwork(network)
.dependsOn(dbContainer)
…
Database Support
• Special objects for wrapped containers
• Popular market choices for:
• Relational: MySQL, MariaDB, OracleXE, DB2, Postgres
• NoSQL: Couchbase, MongoDB, Neo4J, Cassandra, OrientDB
• Easy instantiation and integration
MySQL Database Configuration
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>mysql</artifactId>
<version>1.15.0-rc1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
<scope>test</scope>
</dependency>
MySQL Testcontainer (1)
@Container
MySQLContainer mysqlContainer = new
MySQLContainer<>(DockerImageName.parse(“mysql:8.0”))
.withNetwork(network)
.withNetworkAliases(“mysql_db”);
MySQL Testcontainer (2)
@Container
GenericContainer appContainer = new
GenericContainer(DockerImageName.parse(“fturizo/myapp"))
.withEnv(“DB_SERVER”, “mysql_db”)
.withEnv(“DB_USER”, mysqlContainer.getUser())
.withEnv(“DB_PASSWORD”,
mysqlContainer.getPassword())
.withEnv(“DB_NAME”,
mysqlContainer.getDatabaseName())
.withNetwork(network)
.dependsOn(mysqlContainer)
…
MySQL Testcontainer (3)
String query = "select * from …”;
try(Connection connection =
DriverManager.getConnection(mysqlContainer.getJdbcUrl(),
mysqlContainer.getUsername(),
mysqlContainer.getPassword());
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query))){
while(resultSet.next()) {
assertThat(resultSet.get(0), isEqual(“XYZ”));
}
} catch (SQLException e) {
assert false;
}
More Features!
• Docker Compose is supported, too:
DockerComposeContainer environment =
new DockerComposeContainer(new
File(“src/test/compose.yaml”))
.withExposedService(“mysql_1”, 3306)
.withExposedService(“myapp_1”, 8080);
More Features !
• Container support for popular solutions:
• ElasticSearch (Distributed Search)
• Apache Kafka (Distributed Messaging)
• RabbitMQ (JMS)
• Solr (Text Search)
• Nginx (Loadbalancing)
Testcontainers Caveats
• Docker adds an extra layer of processing
• More resources needed for full coverage
• Test time will increase overall!
• Middleware must be prepared for Docker*
• And so are its dependencies!
• Black-box testing is not suited for all software
Testcontainers Cloud
• Outsource your integration tests!
• https://www.testcontainers.cloud/
Demo Time
https://github.com/fturizo/ConferenceDemo
In Summary
• Testcontainers:
• Ease up writing tests
• Simplify dependency management
• Allow real-world testing
• Make true portability a priority
• Gives Enterprise Java a vendor-agnostic testing framework
Please visit us at:
payara.fish/join-us

More Related Content

What's hot

Clean architectures with fast api pycones
Clean architectures with fast api   pyconesClean architectures with fast api   pycones
Clean architectures with fast api pyconesAlvaro Del Castillo
 
[2019] PAYCO 쇼핑 마이크로서비스 아키텍처(MSA) 전환기
[2019] PAYCO 쇼핑 마이크로서비스 아키텍처(MSA) 전환기[2019] PAYCO 쇼핑 마이크로서비스 아키텍처(MSA) 전환기
[2019] PAYCO 쇼핑 마이크로서비스 아키텍처(MSA) 전환기NHN FORWARD
 
NuxtでAPIサーバー立ててみた
NuxtでAPIサーバー立ててみたNuxtでAPIサーバー立ててみた
NuxtでAPIサーバー立ててみたssuserbf0fbd
 
Spring IO 2023 - Dynamic OpenAPIs with Spring Cloud Gateway
Spring IO 2023 - Dynamic OpenAPIs with Spring Cloud GatewaySpring IO 2023 - Dynamic OpenAPIs with Spring Cloud Gateway
Spring IO 2023 - Dynamic OpenAPIs with Spring Cloud GatewayIván López Martín
 
CI-CD Jenkins, GitHub Actions, Tekton
CI-CD Jenkins, GitHub Actions, Tekton CI-CD Jenkins, GitHub Actions, Tekton
CI-CD Jenkins, GitHub Actions, Tekton Araf Karsh Hamid
 
AWS 기반의 마이크로 서비스 아키텍쳐 구현 방안 :: 김필중 :: AWS Summit Seoul 20
AWS 기반의 마이크로 서비스 아키텍쳐 구현 방안 :: 김필중 :: AWS Summit Seoul 20AWS 기반의 마이크로 서비스 아키텍쳐 구현 방안 :: 김필중 :: AWS Summit Seoul 20
AWS 기반의 마이크로 서비스 아키텍쳐 구현 방안 :: 김필중 :: AWS Summit Seoul 20Amazon Web Services Korea
 
Deep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UKDeep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UKJosé Paumard
 
Azure Logic Apps
Azure Logic AppsAzure Logic Apps
Azure Logic AppsBizTalk360
 
Mule : Building Blocks for Microservices
Mule : Building Blocks for MicroservicesMule : Building Blocks for Microservices
Mule : Building Blocks for MicroservicesAnirudh Pandit
 
[오픈소스컨설팅]Scouter 설치 및 사용가이드(JBoss)
[오픈소스컨설팅]Scouter 설치 및 사용가이드(JBoss)[오픈소스컨설팅]Scouter 설치 및 사용가이드(JBoss)
[오픈소스컨설팅]Scouter 설치 및 사용가이드(JBoss)Ji-Woong Choi
 
Microservices Platform with Spring Boot, Spring Cloud Config, Spring Cloud Ne...
Microservices Platform with Spring Boot, Spring Cloud Config, Spring Cloud Ne...Microservices Platform with Spring Boot, Spring Cloud Config, Spring Cloud Ne...
Microservices Platform with Spring Boot, Spring Cloud Config, Spring Cloud Ne...Tin Linn Soe
 
카카오톡의 서버사이드 코틀린
카카오톡의 서버사이드 코틀린카카오톡의 서버사이드 코틀린
카카오톡의 서버사이드 코틀린if kakao
 
Azure API Management 俺的マニュアル
Azure API Management 俺的マニュアルAzure API Management 俺的マニュアル
Azure API Management 俺的マニュアル貴志 上坂
 
Uncover the mysteries of infrastructure as code (iac)!
Uncover the mysteries of infrastructure as code (iac)!Uncover the mysteries of infrastructure as code (iac)!
Uncover the mysteries of infrastructure as code (iac)!Prashant Kalkar
 
마이크로 서비스 아키텍쳐 소개 및 구현 방법
마이크로 서비스 아키텍쳐 소개 및 구현 방법마이크로 서비스 아키텍쳐 소개 및 구현 방법
마이크로 서비스 아키텍쳐 소개 및 구현 방법Young Soo Lee
 
Spring Framework Petclinic sample application
Spring Framework Petclinic sample applicationSpring Framework Petclinic sample application
Spring Framework Petclinic sample applicationAntoine Rey
 
쿠키런: 킹덤 대규모 인프라 및 서버 운영 사례 공유 [데브시스터즈 - 레벨 200] - 발표자: 용찬호, R&D 엔지니어, 데브시스터즈 ...
쿠키런: 킹덤 대규모 인프라 및 서버 운영 사례 공유 [데브시스터즈 - 레벨 200] - 발표자: 용찬호, R&D 엔지니어, 데브시스터즈 ...쿠키런: 킹덤 대규모 인프라 및 서버 운영 사례 공유 [데브시스터즈 - 레벨 200] - 발표자: 용찬호, R&D 엔지니어, 데브시스터즈 ...
쿠키런: 킹덤 대규모 인프라 및 서버 운영 사례 공유 [데브시스터즈 - 레벨 200] - 발표자: 용찬호, R&D 엔지니어, 데브시스터즈 ...Amazon Web Services Korea
 
How to Webpack your Django!
How to Webpack your Django!How to Webpack your Django!
How to Webpack your Django!David Gibbons
 
Deployment Best Practices on WebLogic Server (DOAG IMC Summit 2013)
Deployment Best Practices on WebLogic Server (DOAG IMC Summit 2013)Deployment Best Practices on WebLogic Server (DOAG IMC Summit 2013)
Deployment Best Practices on WebLogic Server (DOAG IMC Summit 2013)enpit GmbH & Co. KG
 

What's hot (20)

Clean architectures with fast api pycones
Clean architectures with fast api   pyconesClean architectures with fast api   pycones
Clean architectures with fast api pycones
 
[2019] PAYCO 쇼핑 마이크로서비스 아키텍처(MSA) 전환기
[2019] PAYCO 쇼핑 마이크로서비스 아키텍처(MSA) 전환기[2019] PAYCO 쇼핑 마이크로서비스 아키텍처(MSA) 전환기
[2019] PAYCO 쇼핑 마이크로서비스 아키텍처(MSA) 전환기
 
NuxtでAPIサーバー立ててみた
NuxtでAPIサーバー立ててみたNuxtでAPIサーバー立ててみた
NuxtでAPIサーバー立ててみた
 
Spring IO 2023 - Dynamic OpenAPIs with Spring Cloud Gateway
Spring IO 2023 - Dynamic OpenAPIs with Spring Cloud GatewaySpring IO 2023 - Dynamic OpenAPIs with Spring Cloud Gateway
Spring IO 2023 - Dynamic OpenAPIs with Spring Cloud Gateway
 
Introduction to Microservices
Introduction to MicroservicesIntroduction to Microservices
Introduction to Microservices
 
CI-CD Jenkins, GitHub Actions, Tekton
CI-CD Jenkins, GitHub Actions, Tekton CI-CD Jenkins, GitHub Actions, Tekton
CI-CD Jenkins, GitHub Actions, Tekton
 
AWS 기반의 마이크로 서비스 아키텍쳐 구현 방안 :: 김필중 :: AWS Summit Seoul 20
AWS 기반의 마이크로 서비스 아키텍쳐 구현 방안 :: 김필중 :: AWS Summit Seoul 20AWS 기반의 마이크로 서비스 아키텍쳐 구현 방안 :: 김필중 :: AWS Summit Seoul 20
AWS 기반의 마이크로 서비스 아키텍쳐 구현 방안 :: 김필중 :: AWS Summit Seoul 20
 
Deep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UKDeep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UK
 
Azure Logic Apps
Azure Logic AppsAzure Logic Apps
Azure Logic Apps
 
Mule : Building Blocks for Microservices
Mule : Building Blocks for MicroservicesMule : Building Blocks for Microservices
Mule : Building Blocks for Microservices
 
[오픈소스컨설팅]Scouter 설치 및 사용가이드(JBoss)
[오픈소스컨설팅]Scouter 설치 및 사용가이드(JBoss)[오픈소스컨설팅]Scouter 설치 및 사용가이드(JBoss)
[오픈소스컨설팅]Scouter 설치 및 사용가이드(JBoss)
 
Microservices Platform with Spring Boot, Spring Cloud Config, Spring Cloud Ne...
Microservices Platform with Spring Boot, Spring Cloud Config, Spring Cloud Ne...Microservices Platform with Spring Boot, Spring Cloud Config, Spring Cloud Ne...
Microservices Platform with Spring Boot, Spring Cloud Config, Spring Cloud Ne...
 
카카오톡의 서버사이드 코틀린
카카오톡의 서버사이드 코틀린카카오톡의 서버사이드 코틀린
카카오톡의 서버사이드 코틀린
 
Azure API Management 俺的マニュアル
Azure API Management 俺的マニュアルAzure API Management 俺的マニュアル
Azure API Management 俺的マニュアル
 
Uncover the mysteries of infrastructure as code (iac)!
Uncover the mysteries of infrastructure as code (iac)!Uncover the mysteries of infrastructure as code (iac)!
Uncover the mysteries of infrastructure as code (iac)!
 
마이크로 서비스 아키텍쳐 소개 및 구현 방법
마이크로 서비스 아키텍쳐 소개 및 구현 방법마이크로 서비스 아키텍쳐 소개 및 구현 방법
마이크로 서비스 아키텍쳐 소개 및 구현 방법
 
Spring Framework Petclinic sample application
Spring Framework Petclinic sample applicationSpring Framework Petclinic sample application
Spring Framework Petclinic sample application
 
쿠키런: 킹덤 대규모 인프라 및 서버 운영 사례 공유 [데브시스터즈 - 레벨 200] - 발표자: 용찬호, R&D 엔지니어, 데브시스터즈 ...
쿠키런: 킹덤 대규모 인프라 및 서버 운영 사례 공유 [데브시스터즈 - 레벨 200] - 발표자: 용찬호, R&D 엔지니어, 데브시스터즈 ...쿠키런: 킹덤 대규모 인프라 및 서버 운영 사례 공유 [데브시스터즈 - 레벨 200] - 발표자: 용찬호, R&D 엔지니어, 데브시스터즈 ...
쿠키런: 킹덤 대규모 인프라 및 서버 운영 사례 공유 [데브시스터즈 - 레벨 200] - 발표자: 용찬호, R&D 엔지니어, 데브시스터즈 ...
 
How to Webpack your Django!
How to Webpack your Django!How to Webpack your Django!
How to Webpack your Django!
 
Deployment Best Practices on WebLogic Server (DOAG IMC Summit 2013)
Deployment Best Practices on WebLogic Server (DOAG IMC Summit 2013)Deployment Best Practices on WebLogic Server (DOAG IMC Summit 2013)
Deployment Best Practices on WebLogic Server (DOAG IMC Summit 2013)
 

Similar to Easy Java Integration Testing with Testcontainers​

Level Up Your Integration Testing With Testcontainers
Level Up Your Integration Testing With TestcontainersLevel Up Your Integration Testing With Testcontainers
Level Up Your Integration Testing With TestcontainersVMware Tanzu
 
JLove - Replicating production on your laptop using the magic of containers
JLove - Replicating production on your laptop using the magic of containersJLove - Replicating production on your laptop using the magic of containers
JLove - Replicating production on your laptop using the magic of containersGrace Jansen
 
JBCN_Testing_With_Containers
JBCN_Testing_With_ContainersJBCN_Testing_With_Containers
JBCN_Testing_With_ContainersGrace Jansen
 
Devoxx UK 2013 Test-Driven Development with JavaEE 7, Arquillian and Embedded...
Devoxx UK 2013 Test-Driven Development with JavaEE 7, Arquillian and Embedded...Devoxx UK 2013 Test-Driven Development with JavaEE 7, Arquillian and Embedded...
Devoxx UK 2013 Test-Driven Development with JavaEE 7, Arquillian and Embedded...Peter Pilgrim
 
Jakarta EE Test Strategies (2022)
Jakarta EE Test Strategies (2022)Jakarta EE Test Strategies (2022)
Jakarta EE Test Strategies (2022)Ryan Cuprak
 
Performance Test Driven Development with Oracle Coherence
Performance Test Driven Development with Oracle CoherencePerformance Test Driven Development with Oracle Coherence
Performance Test Driven Development with Oracle Coherencearagozin
 
JUnit5 and TestContainers
JUnit5 and TestContainersJUnit5 and TestContainers
JUnit5 and TestContainersSunghyouk Bae
 
How to Build Your Own Test Automation Framework?
How to Build Your Own Test Automation Framework?How to Build Your Own Test Automation Framework?
How to Build Your Own Test Automation Framework?Dmitry Buzdin
 
JUDCON India 2014 Java EE 7 talk
JUDCON India 2014 Java EE 7 talkJUDCON India 2014 Java EE 7 talk
JUDCON India 2014 Java EE 7 talkVijay Nair
 
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014FalafelSoftware
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingSteven Smith
 
Testcontainers - Geekout EE 2017 presentation
Testcontainers - Geekout EE 2017 presentationTestcontainers - Geekout EE 2017 presentation
Testcontainers - Geekout EE 2017 presentationRichard North
 
Why jakarta ee matters (ConFoo 2021)
Why jakarta ee matters (ConFoo 2021)Why jakarta ee matters (ConFoo 2021)
Why jakarta ee matters (ConFoo 2021)Ryan Cuprak
 
Test it! Unit, mocking and in-container Meet Arquillian!
Test it! Unit, mocking and in-container Meet Arquillian!Test it! Unit, mocking and in-container Meet Arquillian!
Test it! Unit, mocking and in-container Meet Arquillian!Ivan Ivanov
 
Enterprise Persistence in OSGi - Mike Keith, Oracle
Enterprise Persistence in OSGi - Mike Keith, OracleEnterprise Persistence in OSGi - Mike Keith, Oracle
Enterprise Persistence in OSGi - Mike Keith, Oraclemfrancis
 
Strudel: Framework for Transaction Performance Analyses on SQL/NoSQL Systems
Strudel: Framework for Transaction Performance Analyses on SQL/NoSQL SystemsStrudel: Framework for Transaction Performance Analyses on SQL/NoSQL Systems
Strudel: Framework for Transaction Performance Analyses on SQL/NoSQL Systemstatemura
 
Haj 4328-java ee 7 overview
Haj 4328-java ee 7 overviewHaj 4328-java ee 7 overview
Haj 4328-java ee 7 overviewKevin Sutter
 
190711_Testbirds_Selenium_eclipsecon_FINAL_0.ppt
190711_Testbirds_Selenium_eclipsecon_FINAL_0.ppt190711_Testbirds_Selenium_eclipsecon_FINAL_0.ppt
190711_Testbirds_Selenium_eclipsecon_FINAL_0.pptNaviAningi
 

Similar to Easy Java Integration Testing with Testcontainers​ (20)

Level Up Your Integration Testing With Testcontainers
Level Up Your Integration Testing With TestcontainersLevel Up Your Integration Testing With Testcontainers
Level Up Your Integration Testing With Testcontainers
 
JLove - Replicating production on your laptop using the magic of containers
JLove - Replicating production on your laptop using the magic of containersJLove - Replicating production on your laptop using the magic of containers
JLove - Replicating production on your laptop using the magic of containers
 
JBCN_Testing_With_Containers
JBCN_Testing_With_ContainersJBCN_Testing_With_Containers
JBCN_Testing_With_Containers
 
Devoxx UK 2013 Test-Driven Development with JavaEE 7, Arquillian and Embedded...
Devoxx UK 2013 Test-Driven Development with JavaEE 7, Arquillian and Embedded...Devoxx UK 2013 Test-Driven Development with JavaEE 7, Arquillian and Embedded...
Devoxx UK 2013 Test-Driven Development with JavaEE 7, Arquillian and Embedded...
 
Jakarta EE Test Strategies (2022)
Jakarta EE Test Strategies (2022)Jakarta EE Test Strategies (2022)
Jakarta EE Test Strategies (2022)
 
Performance Test Driven Development with Oracle Coherence
Performance Test Driven Development with Oracle CoherencePerformance Test Driven Development with Oracle Coherence
Performance Test Driven Development with Oracle Coherence
 
JUnit5 and TestContainers
JUnit5 and TestContainersJUnit5 and TestContainers
JUnit5 and TestContainers
 
How to Build Your Own Test Automation Framework?
How to Build Your Own Test Automation Framework?How to Build Your Own Test Automation Framework?
How to Build Your Own Test Automation Framework?
 
JUDCON India 2014 Java EE 7 talk
JUDCON India 2014 Java EE 7 talkJUDCON India 2014 Java EE 7 talk
JUDCON India 2014 Java EE 7 talk
 
Building XWiki
Building XWikiBuilding XWiki
Building XWiki
 
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
 
Testcontainers - Geekout EE 2017 presentation
Testcontainers - Geekout EE 2017 presentationTestcontainers - Geekout EE 2017 presentation
Testcontainers - Geekout EE 2017 presentation
 
Why jakarta ee matters (ConFoo 2021)
Why jakarta ee matters (ConFoo 2021)Why jakarta ee matters (ConFoo 2021)
Why jakarta ee matters (ConFoo 2021)
 
Test it! Unit, mocking and in-container Meet Arquillian!
Test it! Unit, mocking and in-container Meet Arquillian!Test it! Unit, mocking and in-container Meet Arquillian!
Test it! Unit, mocking and in-container Meet Arquillian!
 
Advanced Java Testing
Advanced Java TestingAdvanced Java Testing
Advanced Java Testing
 
Enterprise Persistence in OSGi - Mike Keith, Oracle
Enterprise Persistence in OSGi - Mike Keith, OracleEnterprise Persistence in OSGi - Mike Keith, Oracle
Enterprise Persistence in OSGi - Mike Keith, Oracle
 
Strudel: Framework for Transaction Performance Analyses on SQL/NoSQL Systems
Strudel: Framework for Transaction Performance Analyses on SQL/NoSQL SystemsStrudel: Framework for Transaction Performance Analyses on SQL/NoSQL Systems
Strudel: Framework for Transaction Performance Analyses on SQL/NoSQL Systems
 
Haj 4328-java ee 7 overview
Haj 4328-java ee 7 overviewHaj 4328-java ee 7 overview
Haj 4328-java ee 7 overview
 
190711_Testbirds_Selenium_eclipsecon_FINAL_0.ppt
190711_Testbirds_Selenium_eclipsecon_FINAL_0.ppt190711_Testbirds_Selenium_eclipsecon_FINAL_0.ppt
190711_Testbirds_Selenium_eclipsecon_FINAL_0.ppt
 

More from Payara

Payara Cloud - Cloud Native Jakarta EE.pptx
Payara Cloud - Cloud Native Jakarta EE.pptxPayara Cloud - Cloud Native Jakarta EE.pptx
Payara Cloud - Cloud Native Jakarta EE.pptxPayara
 
Jakarta Concurrency: Present and Future
Jakarta Concurrency: Present and FutureJakarta Concurrency: Present and Future
Jakarta Concurrency: Present and FuturePayara
 
GlassFish Migration Webinar 2022 Current version.pptx
GlassFish Migration Webinar 2022 Current version.pptxGlassFish Migration Webinar 2022 Current version.pptx
GlassFish Migration Webinar 2022 Current version.pptxPayara
 
10 Strategies for Developing Reliable Jakarta EE & MicroProfile Applications ...
10 Strategies for Developing Reliable Jakarta EE & MicroProfile Applications ...10 Strategies for Developing Reliable Jakarta EE & MicroProfile Applications ...
10 Strategies for Developing Reliable Jakarta EE & MicroProfile Applications ...Payara
 
Securing Microservices with MicroProfile and Auth0v2
Securing Microservices with MicroProfile and Auth0v2Securing Microservices with MicroProfile and Auth0v2
Securing Microservices with MicroProfile and Auth0v2Payara
 
Reactive features of MicroProfile you need to learn
Reactive features of MicroProfile you need to learnReactive features of MicroProfile you need to learn
Reactive features of MicroProfile you need to learnPayara
 
Effective cloud-ready apps with MicroProfile
Effective cloud-ready apps with MicroProfileEffective cloud-ready apps with MicroProfile
Effective cloud-ready apps with MicroProfilePayara
 
A step-by-step guide from traditional Java EE to reactive microservice design
A step-by-step guide from traditional Java EE to reactive microservice designA step-by-step guide from traditional Java EE to reactive microservice design
A step-by-step guide from traditional Java EE to reactive microservice designPayara
 
Transactions in Microservices
Transactions in MicroservicesTransactions in Microservices
Transactions in MicroservicesPayara
 
Fun with Kubernetes and Payara Micro 5
Fun with Kubernetes and Payara Micro 5Fun with Kubernetes and Payara Micro 5
Fun with Kubernetes and Payara Micro 5Payara
 
What's new in Jakarta EE and Eclipse GlassFish (May 2019)
What's new in Jakarta EE and Eclipse GlassFish (May 2019)What's new in Jakarta EE and Eclipse GlassFish (May 2019)
What's new in Jakarta EE and Eclipse GlassFish (May 2019)Payara
 
Previewing Payara Platform 5.192
Previewing Payara Platform 5.192Previewing Payara Platform 5.192
Previewing Payara Platform 5.192Payara
 
Secure JAX-RS
Secure JAX-RSSecure JAX-RS
Secure JAX-RSPayara
 
Gradual Migration to MicroProfile
Gradual Migration to MicroProfileGradual Migration to MicroProfile
Gradual Migration to MicroProfilePayara
 
Monitor Microservices with MicroProfile Metrics
Monitor Microservices with MicroProfile MetricsMonitor Microservices with MicroProfile Metrics
Monitor Microservices with MicroProfile MetricsPayara
 
Java2 days -_be_reactive_and_micro_with_a_microprofile_stack
Java2 days -_be_reactive_and_micro_with_a_microprofile_stackJava2 days -_be_reactive_and_micro_with_a_microprofile_stack
Java2 days -_be_reactive_and_micro_with_a_microprofile_stackPayara
 
Java2 days 5_agile_steps_to_cloud-ready_apps
Java2 days 5_agile_steps_to_cloud-ready_appsJava2 days 5_agile_steps_to_cloud-ready_apps
Java2 days 5_agile_steps_to_cloud-ready_appsPayara
 
Rapid development tools for java ee 8 and micro profile [GIDS]
Rapid development tools for java ee 8 and micro profile [GIDS] Rapid development tools for java ee 8 and micro profile [GIDS]
Rapid development tools for java ee 8 and micro profile [GIDS] Payara
 
Ondrej mihalyi be reactive and micro with a micro profile stack
Ondrej mihalyi   be reactive and micro with a micro profile stackOndrej mihalyi   be reactive and micro with a micro profile stack
Ondrej mihalyi be reactive and micro with a micro profile stackPayara
 
Bed con Quest for JavaEE
Bed con Quest for JavaEEBed con Quest for JavaEE
Bed con Quest for JavaEEPayara
 

More from Payara (20)

Payara Cloud - Cloud Native Jakarta EE.pptx
Payara Cloud - Cloud Native Jakarta EE.pptxPayara Cloud - Cloud Native Jakarta EE.pptx
Payara Cloud - Cloud Native Jakarta EE.pptx
 
Jakarta Concurrency: Present and Future
Jakarta Concurrency: Present and FutureJakarta Concurrency: Present and Future
Jakarta Concurrency: Present and Future
 
GlassFish Migration Webinar 2022 Current version.pptx
GlassFish Migration Webinar 2022 Current version.pptxGlassFish Migration Webinar 2022 Current version.pptx
GlassFish Migration Webinar 2022 Current version.pptx
 
10 Strategies for Developing Reliable Jakarta EE & MicroProfile Applications ...
10 Strategies for Developing Reliable Jakarta EE & MicroProfile Applications ...10 Strategies for Developing Reliable Jakarta EE & MicroProfile Applications ...
10 Strategies for Developing Reliable Jakarta EE & MicroProfile Applications ...
 
Securing Microservices with MicroProfile and Auth0v2
Securing Microservices with MicroProfile and Auth0v2Securing Microservices with MicroProfile and Auth0v2
Securing Microservices with MicroProfile and Auth0v2
 
Reactive features of MicroProfile you need to learn
Reactive features of MicroProfile you need to learnReactive features of MicroProfile you need to learn
Reactive features of MicroProfile you need to learn
 
Effective cloud-ready apps with MicroProfile
Effective cloud-ready apps with MicroProfileEffective cloud-ready apps with MicroProfile
Effective cloud-ready apps with MicroProfile
 
A step-by-step guide from traditional Java EE to reactive microservice design
A step-by-step guide from traditional Java EE to reactive microservice designA step-by-step guide from traditional Java EE to reactive microservice design
A step-by-step guide from traditional Java EE to reactive microservice design
 
Transactions in Microservices
Transactions in MicroservicesTransactions in Microservices
Transactions in Microservices
 
Fun with Kubernetes and Payara Micro 5
Fun with Kubernetes and Payara Micro 5Fun with Kubernetes and Payara Micro 5
Fun with Kubernetes and Payara Micro 5
 
What's new in Jakarta EE and Eclipse GlassFish (May 2019)
What's new in Jakarta EE and Eclipse GlassFish (May 2019)What's new in Jakarta EE and Eclipse GlassFish (May 2019)
What's new in Jakarta EE and Eclipse GlassFish (May 2019)
 
Previewing Payara Platform 5.192
Previewing Payara Platform 5.192Previewing Payara Platform 5.192
Previewing Payara Platform 5.192
 
Secure JAX-RS
Secure JAX-RSSecure JAX-RS
Secure JAX-RS
 
Gradual Migration to MicroProfile
Gradual Migration to MicroProfileGradual Migration to MicroProfile
Gradual Migration to MicroProfile
 
Monitor Microservices with MicroProfile Metrics
Monitor Microservices with MicroProfile MetricsMonitor Microservices with MicroProfile Metrics
Monitor Microservices with MicroProfile Metrics
 
Java2 days -_be_reactive_and_micro_with_a_microprofile_stack
Java2 days -_be_reactive_and_micro_with_a_microprofile_stackJava2 days -_be_reactive_and_micro_with_a_microprofile_stack
Java2 days -_be_reactive_and_micro_with_a_microprofile_stack
 
Java2 days 5_agile_steps_to_cloud-ready_apps
Java2 days 5_agile_steps_to_cloud-ready_appsJava2 days 5_agile_steps_to_cloud-ready_apps
Java2 days 5_agile_steps_to_cloud-ready_apps
 
Rapid development tools for java ee 8 and micro profile [GIDS]
Rapid development tools for java ee 8 and micro profile [GIDS] Rapid development tools for java ee 8 and micro profile [GIDS]
Rapid development tools for java ee 8 and micro profile [GIDS]
 
Ondrej mihalyi be reactive and micro with a micro profile stack
Ondrej mihalyi   be reactive and micro with a micro profile stackOndrej mihalyi   be reactive and micro with a micro profile stack
Ondrej mihalyi be reactive and micro with a micro profile stack
 
Bed con Quest for JavaEE
Bed con Quest for JavaEEBed con Quest for JavaEE
Bed con Quest for JavaEE
 

Recently uploaded

Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 

Recently uploaded (20)

Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 

Easy Java Integration Testing with Testcontainers​

  • 1. Easy Java Integration Testing with Testcontainers Simplifying Integration Tests for Enterprise Java Fabio Turizo
  • 3. • Strategic Members of the Eclipse Foundation • Project Management Committee member of Jakarta EE Payara Services Helps Shape the Future of the Industry
  • 4. Integration Testing Basics • A level above basic unit testing • Multiple units come together to be tested • Goal: Expose flaws in interface design • Guarantee platform updates • Test system dependencies
  • 5. Integration Testing - Java • Simple UT frameworks • Junit, TestNG, Spock • Highly dependable of the platform • What about Mocking ? • Good to simulate interactions • Bad for real-time scenarios
  • 6. Integration Testing - Java • “Works in my machine” persists • Lots of challenges for Enterprise Java • Jakarta EE / MicroProfile lack proper tools • Middleware size footprint has reduced a lot! • … But complex environments have lots of dependencies  • What about cloud-native applications?
  • 7. Arquillian Framework • Focus on testing Jakarta EE components • Vendor-agnostic ! • Portable(*) Shrink-wrapped tests • Container-specific adapters need to be written • Added complexity in writing tests
  • 8. Arquillian Sample (JUnit 4.x) @RunWith(Arquillian.class) public class PersonDaoTest { @EJB private PersonDao personDao; @Inject TestData testData; @Deployment public static WebArchive createDeployment() { return ShrinkWrap.create(WebArchive.class, "arquillian-example.war") .addClass(Person.class) .addClass(PersonDao.class) .addAsResource("test-persistence.xml", "META-INF/persistence.xml"); }
  • 9. Arquillian Sample (JUnit 4.x) @Before public void prepareTestData() { testData.prepareForShouldReturnAllPerson(); } @Test public void shouldReturnAllPerson() throws Exception { List<Person> personList = personDao.getAll(); assertNotNull(personList); assertThat(personList.size(), is(1)); assertThat(personList.get(0).getName(), is("John")); assertThat(personList.get(0).getLastName(), is("Malkovich")); }
  • 10. Arquillian Sample (JUnit 4.x) @Dependent public static class TestData { @PersistenceContext private EntityManager entityManager; @Transactional public void prepareForShouldReturnAllPerson() { entityManager.persist(new Person("John", "Malkovich")); } } }
  • 11. Some Gaps to be Filled  • Test issues: • Assemble a *part of the application* to test it • This includes code and resources • The persistence layer is tested, but not the store • No way to test different configurations • Sadly, not a real-world test
  • 12. Enter Testcontainers! • Lightweight unit testing • Based on Docker containers • Ease up networking setup • Data access layer tests support • Fully* portable integration tests!
  • 13. Testcontainers Benefits • Effective black-box testing • Tests are user-focused • Run UA testing with little overhead • Possible to audit security standards • Identify flaws in specific technologies
  • 14. Testcontainers Requirements • Docker (only Linux containers, though) • Test Frameworks • Junit 4 • Junit 5 • Spock • Maven/Gradle Dependencies
  • 15. Getting Started – JUnit5 <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>5.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.8.1</version> <scope>test</scope> </dependency>
  • 16. Getting Started – TC + JUnit5 <dependency> <groupId>org.testcontainers</groupId> <artifactId>testcontainers</artifactId> <version>1.17.3</version> <scope>test</scope> </dependency> <dependency> <groupId>org.testcontainers</groupId> <artifactId>junit-jupiter</artifactId> <version>1.17.3</version> <scope>test</scope> </dependency>
  • 17. Testcontainer Setup @TestContainers public class BasicApplicationTest{ @Container GenericContainer myappContainer = new GenericContainer(DockerImageName.parse(“fturizo/myapp")) .withExposedPorts(8080, 9009, 28080) .withCommand(“./deploy-application.sh”); @Test public void test_running(){ assert(isTrue(myappcontainer.isRunning())); } }
  • 18. Container Access - Boundary @Test public void test_application(){ String url = String.format(“http://%s:%s/%s”, myappContainer.getHost(), myappContainer.getMappedPort(8080), “/myapp”); int status = http.get(url).response().status(); //Careful! assertEquals(status, 200); }
  • 19. Waiting for Readiness - HTTP @TestContainers public class BasicApplicationTest{ @Container GenericContainer myappContainer = new GenericContainer(DockerImageName.parse(“fturizo/myapp")) .withExposedPorts(8080, 9009, 28080) .waitingFor(Wait.forHttp(“/myapp/ready”) .forStatusCode(200)); }
  • 20. Waiting for Readiness – Log Message @TestContainers public class BasicApplicationTest{ @Container GenericContainer myappContainer = new GenericContainer(DockerImageName.parse(“fturizo/myapp")) .withExposedPorts(8080, 9009, 28080) .waitingFor(Wait.forLogMessage(“.*Application is ready.*”); }
  • 21. Dependency Configuration (1) Network network = Network.newNetwork(); @Container GenericContainer dbContainer = new GenericContainer(DockerImageName.parse(“mysql:8.0")) .withEnv(“MYSQL_ROOT_PASSWORD”, “rootPass”) .withEnv(“MYSQL_USER”, “test”) .withEnv(“MYSQL_PASSWORD”, “test”) .withEnv(“MYSQL_DATABASE”, “testDB”) .withNetwork(network) .withNetworkAlias(“mysql_db”);
  • 22. Dependency Configuration (2) @Container GenericContainer appContainer = new GenericContainer(DockerImageName.parse(“fturizo/myapp")) .withEnv(“DB_SERVER”, “mysql_db”) .withEnv(“DB_USER”, “test”) .withEnv(“DB_PASSWORD”, “test”) .withEnv(“DB_NAME”, “testDB”) .withNetwork(network) .dependsOn(dbContainer) …
  • 23. Database Support • Special objects for wrapped containers • Popular market choices for: • Relational: MySQL, MariaDB, OracleXE, DB2, Postgres • NoSQL: Couchbase, MongoDB, Neo4J, Cassandra, OrientDB • Easy instantiation and integration
  • 25. MySQL Testcontainer (1) @Container MySQLContainer mysqlContainer = new MySQLContainer<>(DockerImageName.parse(“mysql:8.0”)) .withNetwork(network) .withNetworkAliases(“mysql_db”);
  • 26. MySQL Testcontainer (2) @Container GenericContainer appContainer = new GenericContainer(DockerImageName.parse(“fturizo/myapp")) .withEnv(“DB_SERVER”, “mysql_db”) .withEnv(“DB_USER”, mysqlContainer.getUser()) .withEnv(“DB_PASSWORD”, mysqlContainer.getPassword()) .withEnv(“DB_NAME”, mysqlContainer.getDatabaseName()) .withNetwork(network) .dependsOn(mysqlContainer) …
  • 27. MySQL Testcontainer (3) String query = "select * from …”; try(Connection connection = DriverManager.getConnection(mysqlContainer.getJdbcUrl(), mysqlContainer.getUsername(), mysqlContainer.getPassword()); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(query))){ while(resultSet.next()) { assertThat(resultSet.get(0), isEqual(“XYZ”)); } } catch (SQLException e) { assert false; }
  • 28. More Features! • Docker Compose is supported, too: DockerComposeContainer environment = new DockerComposeContainer(new File(“src/test/compose.yaml”)) .withExposedService(“mysql_1”, 3306) .withExposedService(“myapp_1”, 8080);
  • 29. More Features ! • Container support for popular solutions: • ElasticSearch (Distributed Search) • Apache Kafka (Distributed Messaging) • RabbitMQ (JMS) • Solr (Text Search) • Nginx (Loadbalancing)
  • 30. Testcontainers Caveats • Docker adds an extra layer of processing • More resources needed for full coverage • Test time will increase overall! • Middleware must be prepared for Docker* • And so are its dependencies! • Black-box testing is not suited for all software
  • 31. Testcontainers Cloud • Outsource your integration tests! • https://www.testcontainers.cloud/
  • 33. In Summary • Testcontainers: • Ease up writing tests • Simplify dependency management • Allow real-world testing • Make true portability a priority • Gives Enterprise Java a vendor-agnostic testing framework
  • 34. Please visit us at: payara.fish/join-us