SlideShare a Scribd company logo
1 of 41
Download to read offline
JUnit5 & TestContainers
Catalog tribe demo

debop@coupang.com
Agenda
• JUnit 5

• TestContainers
JUnit 5
JUnit 5
• JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage

• Current version = 5.3.2

• No public modifier needed

• Require Java 8 or higher

• Support in IntelliJ IDEA and Eclipse IDE
Setup
testImplementation “org.junit.jupiter:junit-jupiter-api:$jupiter_version”
testRuntimeOnly “org.junit.jupiter:junit-jupiter-engine:$jupiter_version”
Example import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
@BeforeEach
fun setup() {
facts.clear()
}
@Test
fun `facts must have unique name`() {
facts.put("foo", 1)
facts.put("foo", 2)
facts.size shouldEqual 1
assertEquals(2, facts["foo"] !!)
}
Annotations
JUnit 4 JUnit 5
@BeforeClass /
@AfterClass
@BeforeAll / @AfterAll
@Before / @After @BeforeEach/@AfterEach
@Test @Test
@Test(expected=…) Assertions.assertThrows(…) { … }
@Ignore @Disabled
@Nested
@DisplayName
@DisplayName("FactMap operation test")
class FactMapTest {
@Nested
@DisplayName("When same key")
inner class MutableFactMap {
@Test
@DisplayName("When insert duplicated key, update old value")
fun `put same item`() {
val o1 = facts.put("foo", 1)
val o2 = facts.put("foo", 2)
assertNull(o1)
assertEquals(1, o2)
}
}
@Test
fun `facts must have unique name`() {
// …
}
}
@Nested
Assertions
• org.junit.jupiter.api.Assertions

• Use of lambdas for lazy evaluation of messages

• Grouping of assertions

• New way to handle exceptions
Assertions
@Test
fun `put same item`() {
val o1 = facts.put("foo", 1)
val o2 = facts.put("foo", 2)
assertNull(o1) { "o1 should be null" }
assertEquals(1, o2) { "o2 should be 1" }
}
Assertions
assertAll(
Executable { assertNull(o1) { "o1 should be null" } },
Executable { assertEquals(1, o2) { "o2 should be 1" } }
)
assertThrows(IllegalArgumentException::class.java) {
facts.put("", 1)
}
assertTimeout(Duration.ofMillis(200)) {
Thread.sleep(150)
}
assertTimeoutPreemptively(Duration.ofMillis(200)) {
Thread.sleep(150)
}
Assumptions
If assumption fails -> test is skipped
@Test
fun `already exists`() {
// facts is empty -> assumeFalse is failed -> skip assertEquals
assumeFalse { facts.isEmpty() }
// Skip tests
assertEquals(2, 1)
}
Dynamic Tests
@TestFactory
fun testRules(): Stream<DynamicTest> {
return IntStream.range(1, 3)
.mapToObj { it ->
dynamicTest("test for input=$it") {
assertEquals(it * 2, it + it)
}
}
}
https://www.baeldung.com/junit5-dynamic-tests
Conditional Test Execution
• ExecutionCondition as Extension API

• DisabledCondition is simplest example with
@Disabled annotation
Conditional Test Execution
• @EnabledOnOS(…)

• @EnabledOnJre(…)

• @EnabledIfSystemProperty(named=“”, matches=“”)

• @EnabledIfEnvironmentalVariable(named=“”,
matches=“”)

• @EnabledIf(“”) - Support for script, EXPERIMENTAL
Parameterized Tests
• Experimental feature

• Need “junit-jupiter-params”

• Resources

• JUnit 5 Parameterized Tests: Using Different Input 

• JUnit 5 ­ Parameterized Tests
Parameterized Tests
@ParameterizedTest
@ValueSource(strings = ["java8", "java9", "java10"])
fun `parameterized test`(param:String) {
param shouldContain "java"
}
Parameterized Tests
@ParameterizedTest(name = "[{index}]=> {arguments}")
@ValueSource(strings = ["java8", "java9", "java10"])
fun `parameterized test`(param: String) {
param shouldContain "java"
}
Parameterized Tests
• @ValueSource for String, Int, Long, Double)

• @EnumSource(…)

• @MethodSource(“methodName”)

method must return Stream, Iterator or Iterable

• @CsvSource({“foo, bar”, “foo2, bar2”})

• @CsvFileSource(resources=…)

• @ArgumentSource(MyArgProvider.class)
Parallel Test Execution
• Resources

• JUnit 5 Parallel Execution

• JUnit 5 Parallel Test Execution
Parallel Test Execution
junit.jupiter.testinstance.lifecycle.default = per_class
junit.jupiter.execution.parallel.enabled = true
junit.jupiter.execution.parallel.mode.default = concurrent
#junit.jupiter.execution.parallel.config.strategy = dynamic
#junit.jupiter.execution.parallel.config.dynamic.factor = 1
#junit.jupiter.execution.parallel.config.strategy = fixed
#junit.jupiter.execution.parallel.config.fixed.parallelism = 4
#junit.jupiter.execution.parallel.config.strategy = custom
#junit.jupiter.execution.parallel.config.custom.class = ...
Parallel Test Execution
• Synchronization for shared resources

• @Execution(CONCURRENT)

• @Execution(SAME_THREAD)

• ResourceLock(value=…, mode=…)

• Value

custom|SYSTEM_PROPERTIES|SYSTEM_OUT|SYSTEM_ERR

• Mode

READ | READ_WRITE

• JUnit 5 Synchronization
What else?
• @Tag and filtering in build script

• @RepeatedTest with dynamic placeholder for
@DisplayName

• @TestTemplate/
TestTemplateInvocationContextProvider

• Extension API, extensions registered via @ExtendWith
• Custom Extensions in kotlinx-junit-jupiter
TestContainers
Introduction
• Java library to launch Docker containers during Tests

• Integration tests against the data access layer

• Integration tests with external dependencies

e.g. message broker, database, cache …

• UI Tests with containerized, Selenium compatible,
Web browsers
Introduction
• Current version : 1.10.3

• Requires Docker installation

• Requires Java 8 or higher

• Compatible with JUnit 4 / 5
Usecases
• Data access layer integration tests: use a containerized instance of a
MySQL, PostgreSQL or Oracle database to test your data access layer code for
complete compatibility, but without requiring complex setup on developers'
machines and safe in the knowledge that your tests will always start with a
known DB state.Any other database type that can be containerized can also be
used.
• Application integration tests: for running your application in a short-lived
test mode with dependencies, such as databases, message queues or web servers.
• UI/Acceptance tests: use containerized web browsers, compatible with
Selenium, for conducting automated UI tests. Each test can get a fresh instance of
the browser, with no browser state, plugin variations or automated browser
upgrades to worry about.And you get a video recording of each test session, or
just each session where tests failed.
JUnit 4
@ClassRule
public static GenericContainer mysql =
new MySQLContainer().withExposedPorts(3306);
@Test
public void getExposedPorts() {
List<Integer> ports = mysql.getExposedPorts();
assertThat(ports).contains(3306);
}
JUnit 4 + Kotlin
static {
INSTANCE = createPostgreSQLContainer();
HOST = INSTANCE.getContainerIpAddress();
PORT = INSTANCE.getMappedPort(PostgreSQLContainer.POSTGRESQL_PORT);
JDBC_URL = INSTANCE.getJdbcUrl();
}
public static PostgreSQLContainer createPostgreSQLContainer() {
PostgreSQLContainer container = new PostgreSQLContainer();
container.withLogConsumer(new Slf4jLogConsumer(log));
container.withDatabaseName("test");
container.start();
return container;
}
JUnit 5 static GenericContainer mysql =
new MySQLContainer().withExposedPorts(3306);
@BeforeAll
static void setup() {
mysql.start();
}
@AfterAll
static void tearDown() {
mysql.stop();
}
@Test
void getExposedPorts() {
List<Integer> ports = mysql.getExposedPorts();
assertThat(ports).contains(3306);
}
Generic Container
• Offers flexible support for any container image as test
dependency

• Reference public docker images

• Internal dockerized services
Generic Container
• withExposedPorts(…)

• withEnv(…)

• withLabel(…)

• getContainerIpAddress()

• getMappedPort(…)
Generic Container - Kotlin
object RedisContainer : KLogging() {
// For Kotlin language spec
class KGenericContainer(imageName: String) : GenericContainer<KGenericContainer>(imageName)
val instance by lazy { startRedisContainer() }
private fun startRedisContainer() = KGenericContainer("redis:4.0.11").apply {
withExposedPorts(6379)
setWaitStrategy(HostPortWaitStrategy())
withLogConsumer(Slf4jLogConsumer(log))
start()
}
val host: String by lazy { instance.containerIpAddress }
val port: Int by lazy { instance.getMappedPort(6379) }
val url: String by lazy { "redis://$host:$port" }
}
Specialized Container
• Create images from Dockerfile

• withFileFromString(…)

• withFileFromClasspath(…)

• Use Dockerfile DSL to define Dockerfiles in code
Specialized Container
• Use database container to test database specific
features

• No local setup or VM

• 100% database compatibility instead of H2

• MySQL

• PostgreSQL

• Oracle XE
Future
• TestContainers 2.x

• API cleanup

• Decoupling from JUnit 4 to support other
framework directly
Alternatives
• TestNG

• Other JVM languages

• Groovy, Spock, Testcontainers-Spock

• Kotlin, Testcontainers (with workaround)
Resources
• JUnit 5

• JUnit 5 Basic

• JUnit 5 : Next step in automated testing

• How to perform a productivee testing using JUnit 5 on Kotlin 

• Test Containers

• Test containers Official site

• Docker Test Containers in Java Test

• TestContainers and Spring Boot

• Don’t use In-Memory Database (H2, Congo) for Tests
Q&A
Thank you!

More Related Content

What's hot

CICD Pipeline Using Github Actions
CICD Pipeline Using Github ActionsCICD Pipeline Using Github Actions
CICD Pipeline Using Github ActionsKumar Shìvam
 
Functional Tests Automation with Robot Framework
Functional Tests Automation with Robot FrameworkFunctional Tests Automation with Robot Framework
Functional Tests Automation with Robot Frameworklaurent bristiel
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsYura Nosenko
 
Introducing GitLab (June 2018)
Introducing GitLab (June 2018)Introducing GitLab (June 2018)
Introducing GitLab (June 2018)Noa Harel
 
CD using ArgoCD(KnolX).pdf
CD using ArgoCD(KnolX).pdfCD using ArgoCD(KnolX).pdf
CD using ArgoCD(KnolX).pdfKnoldus Inc.
 
Jenkins tutorial for beginners
Jenkins tutorial for beginnersJenkins tutorial for beginners
Jenkins tutorial for beginnersBugRaptors
 
Getting Started - Ansible Galaxy NG
Getting Started - Ansible Galaxy NGGetting Started - Ansible Galaxy NG
Getting Started - Ansible Galaxy NGHideki Saito
 
Karate - Web-Service API Testing Made Simple
Karate - Web-Service API Testing Made SimpleKarate - Web-Service API Testing Made Simple
Karate - Web-Service API Testing Made SimpleVodqaBLR
 
Introduction to Kotlin coroutines
Introduction to Kotlin coroutinesIntroduction to Kotlin coroutines
Introduction to Kotlin coroutinesRoman Elizarov
 
Introduction to kotlin coroutines
Introduction to kotlin coroutinesIntroduction to kotlin coroutines
Introduction to kotlin coroutinesNAVER Engineering
 
Testing with JUnit 5 and Spring - Spring I/O 2022
Testing with JUnit 5 and Spring - Spring I/O 2022Testing with JUnit 5 and Spring - Spring I/O 2022
Testing with JUnit 5 and Spring - Spring I/O 2022Sam Brannen
 
Graal in GraalVM - A New JIT Compiler
Graal in GraalVM - A New JIT CompilerGraal in GraalVM - A New JIT Compiler
Graal in GraalVM - A New JIT CompilerKoichi Sakata
 
Test in Rest. API testing with the help of Rest Assured.
Test in Rest. API testing with the help of  Rest Assured.Test in Rest. API testing with the help of  Rest Assured.
Test in Rest. API testing with the help of Rest Assured.Artem Korchevyi
 
Robot Framework Introduction
Robot Framework IntroductionRobot Framework Introduction
Robot Framework IntroductionPekka Klärck
 

What's hot (20)

JUnit 5
JUnit 5JUnit 5
JUnit 5
 
CICD Pipeline Using Github Actions
CICD Pipeline Using Github ActionsCICD Pipeline Using Github Actions
CICD Pipeline Using Github Actions
 
Functional Tests Automation with Robot Framework
Functional Tests Automation with Robot FrameworkFunctional Tests Automation with Robot Framework
Functional Tests Automation with Robot Framework
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applications
 
Introducing GitLab (June 2018)
Introducing GitLab (June 2018)Introducing GitLab (June 2018)
Introducing GitLab (June 2018)
 
React Hooks
React HooksReact Hooks
React Hooks
 
CD using ArgoCD(KnolX).pdf
CD using ArgoCD(KnolX).pdfCD using ArgoCD(KnolX).pdf
CD using ArgoCD(KnolX).pdf
 
Jenkins tutorial for beginners
Jenkins tutorial for beginnersJenkins tutorial for beginners
Jenkins tutorial for beginners
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 
Getting Started - Ansible Galaxy NG
Getting Started - Ansible Galaxy NGGetting Started - Ansible Galaxy NG
Getting Started - Ansible Galaxy NG
 
Karate - Web-Service API Testing Made Simple
Karate - Web-Service API Testing Made SimpleKarate - Web-Service API Testing Made Simple
Karate - Web-Service API Testing Made Simple
 
Introduction to Kotlin coroutines
Introduction to Kotlin coroutinesIntroduction to Kotlin coroutines
Introduction to Kotlin coroutines
 
Introduction to kotlin coroutines
Introduction to kotlin coroutinesIntroduction to kotlin coroutines
Introduction to kotlin coroutines
 
Testing with JUnit 5 and Spring - Spring I/O 2022
Testing with JUnit 5 and Spring - Spring I/O 2022Testing with JUnit 5 and Spring - Spring I/O 2022
Testing with JUnit 5 and Spring - Spring I/O 2022
 
Git and git flow
Git and git flowGit and git flow
Git and git flow
 
Graal in GraalVM - A New JIT Compiler
Graal in GraalVM - A New JIT CompilerGraal in GraalVM - A New JIT Compiler
Graal in GraalVM - A New JIT Compiler
 
Test in Rest. API testing with the help of Rest Assured.
Test in Rest. API testing with the help of  Rest Assured.Test in Rest. API testing with the help of  Rest Assured.
Test in Rest. API testing with the help of Rest Assured.
 
Git Branching Model
Git Branching ModelGit Branching Model
Git Branching Model
 
Git & GitHub for Beginners
Git & GitHub for BeginnersGit & GitHub for Beginners
Git & GitHub for Beginners
 
Robot Framework Introduction
Robot Framework IntroductionRobot Framework Introduction
Robot Framework Introduction
 

Similar to JUnit5 and TestContainers

Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developersAnton Udovychenko
 
Easy Java Integration Testing with Testcontainers​
Easy Java Integration Testing with Testcontainers​Easy Java Integration Testing with Testcontainers​
Easy Java Integration Testing with Testcontainers​Payara
 
What to expect from Java 9
What to expect from Java 9What to expect from Java 9
What to expect from Java 9Ivan Krylov
 
Testing the Enterprise Layers - the A, B, C's of Integration Testing - Aslak ...
Testing the Enterprise Layers - the A, B, C's of Integration Testing - Aslak ...Testing the Enterprise Layers - the A, B, C's of Integration Testing - Aslak ...
Testing the Enterprise Layers - the A, B, C's of Integration Testing - Aslak ...JAXLondon2014
 
Testing the Enterprise layers, with Arquillian
Testing the Enterprise layers, with ArquillianTesting the Enterprise layers, with Arquillian
Testing the Enterprise layers, with ArquillianVirtual JBoss User Group
 
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Paul King
 
Android Unit Test
Android Unit TestAndroid Unit Test
Android Unit TestPhuoc Bui
 
Guide to the jungle of testing frameworks
Guide to the jungle of testing frameworksGuide to the jungle of testing frameworks
Guide to the jungle of testing frameworksTomáš Kypta
 
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalksSelenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalksLohika_Odessa_TechTalks
 
Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Roberto Franchini
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevMattias Karlsson
 
S314168 - What's New in Enterprise Java Bean Technology @ JavaOne Brazil 2010
S314168 - What's New in Enterprise Java Bean Technology @ JavaOne Brazil 2010S314168 - What's New in Enterprise Java Bean Technology @ JavaOne Brazil 2010
S314168 - What's New in Enterprise Java Bean Technology @ JavaOne Brazil 2010Arun Gupta
 
Testcontainers - Geekout EE 2017 presentation
Testcontainers - Geekout EE 2017 presentationTestcontainers - Geekout EE 2017 presentation
Testcontainers - Geekout EE 2017 presentationRichard North
 
Web UI test automation instruments
Web UI test automation instrumentsWeb UI test automation instruments
Web UI test automation instrumentsArtem Nagornyi
 

Similar to JUnit5 and TestContainers (20)

Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developers
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 
Easy Java Integration Testing with Testcontainers​
Easy Java Integration Testing with Testcontainers​Easy Java Integration Testing with Testcontainers​
Easy Java Integration Testing with Testcontainers​
 
Advanced Java Testing
Advanced Java TestingAdvanced Java Testing
Advanced Java Testing
 
What to expect from Java 9
What to expect from Java 9What to expect from Java 9
What to expect from Java 9
 
Testing the Enterprise Layers - the A, B, C's of Integration Testing - Aslak ...
Testing the Enterprise Layers - the A, B, C's of Integration Testing - Aslak ...Testing the Enterprise Layers - the A, B, C's of Integration Testing - Aslak ...
Testing the Enterprise Layers - the A, B, C's of Integration Testing - Aslak ...
 
Testing the Enterprise layers, with Arquillian
Testing the Enterprise layers, with ArquillianTesting the Enterprise layers, with Arquillian
Testing the Enterprise layers, with Arquillian
 
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
 
Android Unit Test
Android Unit TestAndroid Unit Test
Android Unit Test
 
Junit 5 - Maior e melhor
Junit 5 - Maior e melhorJunit 5 - Maior e melhor
Junit 5 - Maior e melhor
 
Guide to the jungle of testing frameworks
Guide to the jungle of testing frameworksGuide to the jungle of testing frameworks
Guide to the jungle of testing frameworks
 
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalksSelenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
 
Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!
 
Good Practices On Test Automation
Good Practices On Test AutomationGood Practices On Test Automation
Good Practices On Test Automation
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from Oredev
 
S314168 - What's New in Enterprise Java Bean Technology @ JavaOne Brazil 2010
S314168 - What's New in Enterprise Java Bean Technology @ JavaOne Brazil 2010S314168 - What's New in Enterprise Java Bean Technology @ JavaOne Brazil 2010
S314168 - What's New in Enterprise Java Bean Technology @ JavaOne Brazil 2010
 
Spock
SpockSpock
Spock
 
PostgreSQL and PL/Java
PostgreSQL and PL/JavaPostgreSQL and PL/Java
PostgreSQL and PL/Java
 
Testcontainers - Geekout EE 2017 presentation
Testcontainers - Geekout EE 2017 presentationTestcontainers - Geekout EE 2017 presentation
Testcontainers - Geekout EE 2017 presentation
 
Web UI test automation instruments
Web UI test automation instrumentsWeb UI test automation instruments
Web UI test automation instruments
 

More from Sunghyouk Bae

Introduction of failsafe
Introduction of failsafeIntroduction of failsafe
Introduction of failsafeSunghyouk Bae
 
Kotlin @ Coupang Backed - JetBrains Day seoul 2018
Kotlin @ Coupang Backed - JetBrains Day seoul 2018Kotlin @ Coupang Backed - JetBrains Day seoul 2018
Kotlin @ Coupang Backed - JetBrains Day seoul 2018Sunghyouk Bae
 
Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Sunghyouk Bae
 
Alternatives of JPA/Hibernate
Alternatives of JPA/HibernateAlternatives of JPA/Hibernate
Alternatives of JPA/HibernateSunghyouk Bae
 
Kotlin coroutines and spring framework
Kotlin coroutines and spring frameworkKotlin coroutines and spring framework
Kotlin coroutines and spring frameworkSunghyouk Bae
 
Java naming strategy (자바 명명 전략)
Java naming strategy (자바 명명 전략)Java naming strategy (자바 명명 전략)
Java naming strategy (자바 명명 전략)Sunghyouk Bae
 
테스트자동화와 TDD
테스트자동화와 TDD테스트자동화와 TDD
테스트자동화와 TDDSunghyouk Bae
 
SpringBoot with MyBatis, Flyway, QueryDSL
SpringBoot with MyBatis, Flyway, QueryDSLSpringBoot with MyBatis, Flyway, QueryDSL
SpringBoot with MyBatis, Flyway, QueryDSLSunghyouk Bae
 
좋은 개발자 되기
좋은 개발자 되기좋은 개발자 되기
좋은 개발자 되기Sunghyouk Bae
 
Multithread pattern 소개
Multithread pattern 소개Multithread pattern 소개
Multithread pattern 소개Sunghyouk Bae
 

More from Sunghyouk Bae (16)

Introduction of failsafe
Introduction of failsafeIntroduction of failsafe
Introduction of failsafe
 
Kotlin @ Coupang Backed - JetBrains Day seoul 2018
Kotlin @ Coupang Backed - JetBrains Day seoul 2018Kotlin @ Coupang Backed - JetBrains Day seoul 2018
Kotlin @ Coupang Backed - JetBrains Day seoul 2018
 
Spring data requery
Spring data requerySpring data requery
Spring data requery
 
Requery overview
Requery overviewRequery overview
Requery overview
 
Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017
 
measure metrics
measure metricsmeasure metrics
measure metrics
 
Alternatives of JPA/Hibernate
Alternatives of JPA/HibernateAlternatives of JPA/Hibernate
Alternatives of JPA/Hibernate
 
Kotlin coroutines and spring framework
Kotlin coroutines and spring frameworkKotlin coroutines and spring framework
Kotlin coroutines and spring framework
 
Java naming strategy (자바 명명 전략)
Java naming strategy (자바 명명 전략)Java naming strategy (자바 명명 전략)
Java naming strategy (자바 명명 전략)
 
테스트자동화와 TDD
테스트자동화와 TDD테스트자동화와 TDD
테스트자동화와 TDD
 
SpringBoot with MyBatis, Flyway, QueryDSL
SpringBoot with MyBatis, Flyway, QueryDSLSpringBoot with MyBatis, Flyway, QueryDSL
SpringBoot with MyBatis, Flyway, QueryDSL
 
JUnit & AssertJ
JUnit & AssertJJUnit & AssertJ
JUnit & AssertJ
 
좋은 개발자 되기
좋은 개발자 되기좋은 개발자 되기
좋은 개발자 되기
 
Using AdoRepository
Using AdoRepositoryUsing AdoRepository
Using AdoRepository
 
Multithread pattern 소개
Multithread pattern 소개Multithread pattern 소개
Multithread pattern 소개
 
Strategy Maps
Strategy MapsStrategy Maps
Strategy Maps
 

Recently uploaded

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 

Recently uploaded (20)

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 

JUnit5 and TestContainers

  • 1. JUnit5 & TestContainers Catalog tribe demo debop@coupang.com
  • 2. Agenda • JUnit 5 • TestContainers
  • 4. JUnit 5 • JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage • Current version = 5.3.2 • No public modifier needed • Require Java 8 or higher • Support in IntelliJ IDEA and Eclipse IDE
  • 6. Example import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test @BeforeEach fun setup() { facts.clear() } @Test fun `facts must have unique name`() { facts.put("foo", 1) facts.put("foo", 2) facts.size shouldEqual 1 assertEquals(2, facts["foo"] !!) }
  • 7. Annotations JUnit 4 JUnit 5 @BeforeClass / @AfterClass @BeforeAll / @AfterAll @Before / @After @BeforeEach/@AfterEach @Test @Test @Test(expected=…) Assertions.assertThrows(…) { … } @Ignore @Disabled @Nested @DisplayName
  • 8. @DisplayName("FactMap operation test") class FactMapTest { @Nested @DisplayName("When same key") inner class MutableFactMap { @Test @DisplayName("When insert duplicated key, update old value") fun `put same item`() { val o1 = facts.put("foo", 1) val o2 = facts.put("foo", 2) assertNull(o1) assertEquals(1, o2) } } @Test fun `facts must have unique name`() { // … } }
  • 10. Assertions • org.junit.jupiter.api.Assertions • Use of lambdas for lazy evaluation of messages • Grouping of assertions • New way to handle exceptions
  • 11. Assertions @Test fun `put same item`() { val o1 = facts.put("foo", 1) val o2 = facts.put("foo", 2) assertNull(o1) { "o1 should be null" } assertEquals(1, o2) { "o2 should be 1" } }
  • 12. Assertions assertAll( Executable { assertNull(o1) { "o1 should be null" } }, Executable { assertEquals(1, o2) { "o2 should be 1" } } ) assertThrows(IllegalArgumentException::class.java) { facts.put("", 1) } assertTimeout(Duration.ofMillis(200)) { Thread.sleep(150) } assertTimeoutPreemptively(Duration.ofMillis(200)) { Thread.sleep(150) }
  • 13. Assumptions If assumption fails -> test is skipped @Test fun `already exists`() { // facts is empty -> assumeFalse is failed -> skip assertEquals assumeFalse { facts.isEmpty() } // Skip tests assertEquals(2, 1) }
  • 14. Dynamic Tests @TestFactory fun testRules(): Stream<DynamicTest> { return IntStream.range(1, 3) .mapToObj { it -> dynamicTest("test for input=$it") { assertEquals(it * 2, it + it) } } } https://www.baeldung.com/junit5-dynamic-tests
  • 15. Conditional Test Execution • ExecutionCondition as Extension API • DisabledCondition is simplest example with @Disabled annotation
  • 16. Conditional Test Execution • @EnabledOnOS(…) • @EnabledOnJre(…) • @EnabledIfSystemProperty(named=“”, matches=“”) • @EnabledIfEnvironmentalVariable(named=“”, matches=“”) • @EnabledIf(“”) - Support for script, EXPERIMENTAL
  • 17. Parameterized Tests • Experimental feature • Need “junit-jupiter-params” • Resources • JUnit 5 Parameterized Tests: Using Different Input • JUnit 5 ­ Parameterized Tests
  • 18. Parameterized Tests @ParameterizedTest @ValueSource(strings = ["java8", "java9", "java10"]) fun `parameterized test`(param:String) { param shouldContain "java" }
  • 19. Parameterized Tests @ParameterizedTest(name = "[{index}]=> {arguments}") @ValueSource(strings = ["java8", "java9", "java10"]) fun `parameterized test`(param: String) { param shouldContain "java" }
  • 20. Parameterized Tests • @ValueSource for String, Int, Long, Double) • @EnumSource(…) • @MethodSource(“methodName”)
 method must return Stream, Iterator or Iterable • @CsvSource({“foo, bar”, “foo2, bar2”}) • @CsvFileSource(resources=…) • @ArgumentSource(MyArgProvider.class)
  • 21. Parallel Test Execution • Resources • JUnit 5 Parallel Execution • JUnit 5 Parallel Test Execution
  • 22. Parallel Test Execution junit.jupiter.testinstance.lifecycle.default = per_class junit.jupiter.execution.parallel.enabled = true junit.jupiter.execution.parallel.mode.default = concurrent #junit.jupiter.execution.parallel.config.strategy = dynamic #junit.jupiter.execution.parallel.config.dynamic.factor = 1 #junit.jupiter.execution.parallel.config.strategy = fixed #junit.jupiter.execution.parallel.config.fixed.parallelism = 4 #junit.jupiter.execution.parallel.config.strategy = custom #junit.jupiter.execution.parallel.config.custom.class = ...
  • 23. Parallel Test Execution • Synchronization for shared resources • @Execution(CONCURRENT) • @Execution(SAME_THREAD) • ResourceLock(value=…, mode=…) • Value
 custom|SYSTEM_PROPERTIES|SYSTEM_OUT|SYSTEM_ERR • Mode
 READ | READ_WRITE • JUnit 5 Synchronization
  • 24. What else? • @Tag and filtering in build script • @RepeatedTest with dynamic placeholder for @DisplayName • @TestTemplate/ TestTemplateInvocationContextProvider • Extension API, extensions registered via @ExtendWith • Custom Extensions in kotlinx-junit-jupiter
  • 26. Introduction • Java library to launch Docker containers during Tests • Integration tests against the data access layer • Integration tests with external dependencies
 e.g. message broker, database, cache … • UI Tests with containerized, Selenium compatible, Web browsers
  • 27. Introduction • Current version : 1.10.3 • Requires Docker installation • Requires Java 8 or higher • Compatible with JUnit 4 / 5
  • 28. Usecases • Data access layer integration tests: use a containerized instance of a MySQL, PostgreSQL or Oracle database to test your data access layer code for complete compatibility, but without requiring complex setup on developers' machines and safe in the knowledge that your tests will always start with a known DB state.Any other database type that can be containerized can also be used. • Application integration tests: for running your application in a short-lived test mode with dependencies, such as databases, message queues or web servers. • UI/Acceptance tests: use containerized web browsers, compatible with Selenium, for conducting automated UI tests. Each test can get a fresh instance of the browser, with no browser state, plugin variations or automated browser upgrades to worry about.And you get a video recording of each test session, or just each session where tests failed.
  • 29. JUnit 4 @ClassRule public static GenericContainer mysql = new MySQLContainer().withExposedPorts(3306); @Test public void getExposedPorts() { List<Integer> ports = mysql.getExposedPorts(); assertThat(ports).contains(3306); }
  • 30. JUnit 4 + Kotlin static { INSTANCE = createPostgreSQLContainer(); HOST = INSTANCE.getContainerIpAddress(); PORT = INSTANCE.getMappedPort(PostgreSQLContainer.POSTGRESQL_PORT); JDBC_URL = INSTANCE.getJdbcUrl(); } public static PostgreSQLContainer createPostgreSQLContainer() { PostgreSQLContainer container = new PostgreSQLContainer(); container.withLogConsumer(new Slf4jLogConsumer(log)); container.withDatabaseName("test"); container.start(); return container; }
  • 31. JUnit 5 static GenericContainer mysql = new MySQLContainer().withExposedPorts(3306); @BeforeAll static void setup() { mysql.start(); } @AfterAll static void tearDown() { mysql.stop(); } @Test void getExposedPorts() { List<Integer> ports = mysql.getExposedPorts(); assertThat(ports).contains(3306); }
  • 32. Generic Container • Offers flexible support for any container image as test dependency • Reference public docker images • Internal dockerized services
  • 33. Generic Container • withExposedPorts(…) • withEnv(…) • withLabel(…) • getContainerIpAddress() • getMappedPort(…)
  • 34. Generic Container - Kotlin object RedisContainer : KLogging() { // For Kotlin language spec class KGenericContainer(imageName: String) : GenericContainer<KGenericContainer>(imageName) val instance by lazy { startRedisContainer() } private fun startRedisContainer() = KGenericContainer("redis:4.0.11").apply { withExposedPorts(6379) setWaitStrategy(HostPortWaitStrategy()) withLogConsumer(Slf4jLogConsumer(log)) start() } val host: String by lazy { instance.containerIpAddress } val port: Int by lazy { instance.getMappedPort(6379) } val url: String by lazy { "redis://$host:$port" } }
  • 35. Specialized Container • Create images from Dockerfile • withFileFromString(…) • withFileFromClasspath(…) • Use Dockerfile DSL to define Dockerfiles in code
  • 36. Specialized Container • Use database container to test database specific features • No local setup or VM • 100% database compatibility instead of H2 • MySQL • PostgreSQL • Oracle XE
  • 37. Future • TestContainers 2.x • API cleanup • Decoupling from JUnit 4 to support other framework directly
  • 38. Alternatives • TestNG • Other JVM languages • Groovy, Spock, Testcontainers-Spock • Kotlin, Testcontainers (with workaround)
  • 39. Resources • JUnit 5 • JUnit 5 Basic • JUnit 5 : Next step in automated testing • How to perform a productivee testing using JUnit 5 on Kotlin • Test Containers • Test containers Official site • Docker Test Containers in Java Test • TestContainers and Spring Boot • Don’t use In-Memory Database (H2, Congo) for Tests
  • 40. Q&A