SlideShare uma empresa Scribd logo
1 de 41
Baixar para ler 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!

Mais conteúdo relacionado

Mais procurados

Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...
Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...
Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...Edureka!
 
Linux Kernel Module - For NLKB
Linux Kernel Module - For NLKBLinux Kernel Module - For NLKB
Linux Kernel Module - For NLKBshimosawa
 
嵌入式測試驅動開發
嵌入式測試驅動開發嵌入式測試驅動開發
嵌入式測試驅動開發hugo lu
 
Multiple inheritance possible in Java
Multiple inheritance possible in JavaMultiple inheritance possible in Java
Multiple inheritance possible in JavaKurapati Vishwak
 
Tomcat and apache httpd training
Tomcat and apache httpd trainingTomcat and apache httpd training
Tomcat and apache httpd trainingFranck SIMON
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For SyntaxPravinYalameli
 
Tdd with python unittest for embedded c
Tdd with python unittest for embedded cTdd with python unittest for embedded c
Tdd with python unittest for embedded cBenux Wei
 
Presentation Spring, Spring MVC
Presentation Spring, Spring MVCPresentation Spring, Spring MVC
Presentation Spring, Spring MVCNathaniel Richand
 
Bean Validation - Cours v 1.1
Bean Validation - Cours v 1.1Bean Validation - Cours v 1.1
Bean Validation - Cours v 1.1Laurent Guérin
 
Java Development Kit (jdk)
Java Development Kit (jdk)Java Development Kit (jdk)
Java Development Kit (jdk)Jadavsejal
 
Overview of Android binder IPC implementation
Overview of Android binder IPC implementationOverview of Android binder IPC implementation
Overview of Android binder IPC implementationChethan Pchethan
 
From Spring Framework 5.3 to 6.0
From Spring Framework 5.3 to 6.0From Spring Framework 5.3 to 6.0
From Spring Framework 5.3 to 6.0VMware Tanzu
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsMahika Tutorials
 
Conférence sur les annotations Java par Olivier Croisier (Zenika) au Paris JUG
Conférence sur les annotations Java par Olivier Croisier (Zenika) au Paris JUGConférence sur les annotations Java par Olivier Croisier (Zenika) au Paris JUG
Conférence sur les annotations Java par Olivier Croisier (Zenika) au Paris JUGZenika
 
XPDDS17: Reworking the ARM GIC Emulation & Xen Challenges in the ARM ITS Emu...
XPDDS17:  Reworking the ARM GIC Emulation & Xen Challenges in the ARM ITS Emu...XPDDS17:  Reworking the ARM GIC Emulation & Xen Challenges in the ARM ITS Emu...
XPDDS17: Reworking the ARM GIC Emulation & Xen Challenges in the ARM ITS Emu...The Linux Foundation
 

Mais procurados (20)

Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...
Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...
Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...
 
Linux Kernel Module - For NLKB
Linux Kernel Module - For NLKBLinux Kernel Module - For NLKB
Linux Kernel Module - For NLKB
 
嵌入式測試驅動開發
嵌入式測試驅動開發嵌入式測試驅動開發
嵌入式測試驅動開發
 
Multiple inheritance possible in Java
Multiple inheritance possible in JavaMultiple inheritance possible in Java
Multiple inheritance possible in Java
 
Android Binder: Deep Dive
Android Binder: Deep DiveAndroid Binder: Deep Dive
Android Binder: Deep Dive
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Tomcat and apache httpd training
Tomcat and apache httpd trainingTomcat and apache httpd training
Tomcat and apache httpd training
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For Syntax
 
Completable future
Completable futureCompletable future
Completable future
 
Tdd with python unittest for embedded c
Tdd with python unittest for embedded cTdd with python unittest for embedded c
Tdd with python unittest for embedded c
 
Presentation Spring, Spring MVC
Presentation Spring, Spring MVCPresentation Spring, Spring MVC
Presentation Spring, Spring MVC
 
Hands-on ethernet driver
Hands-on ethernet driverHands-on ethernet driver
Hands-on ethernet driver
 
Maven ppt
Maven pptMaven ppt
Maven ppt
 
Bean Validation - Cours v 1.1
Bean Validation - Cours v 1.1Bean Validation - Cours v 1.1
Bean Validation - Cours v 1.1
 
Java Development Kit (jdk)
Java Development Kit (jdk)Java Development Kit (jdk)
Java Development Kit (jdk)
 
Overview of Android binder IPC implementation
Overview of Android binder IPC implementationOverview of Android binder IPC implementation
Overview of Android binder IPC implementation
 
From Spring Framework 5.3 to 6.0
From Spring Framework 5.3 to 6.0From Spring Framework 5.3 to 6.0
From Spring Framework 5.3 to 6.0
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika Tutorials
 
Conférence sur les annotations Java par Olivier Croisier (Zenika) au Paris JUG
Conférence sur les annotations Java par Olivier Croisier (Zenika) au Paris JUGConférence sur les annotations Java par Olivier Croisier (Zenika) au Paris JUG
Conférence sur les annotations Java par Olivier Croisier (Zenika) au Paris JUG
 
XPDDS17: Reworking the ARM GIC Emulation & Xen Challenges in the ARM ITS Emu...
XPDDS17:  Reworking the ARM GIC Emulation & Xen Challenges in the ARM ITS Emu...XPDDS17:  Reworking the ARM GIC Emulation & Xen Challenges in the ARM ITS Emu...
XPDDS17: Reworking the ARM GIC Emulation & Xen Challenges in the ARM ITS Emu...
 

Semelhante a 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
 

Semelhante a 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
 

Mais de 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
 

Mais de 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
 

Último

Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
SoftTeco - Software Development Company Profile
SoftTeco - Software Development Company ProfileSoftTeco - Software Development Company Profile
SoftTeco - Software Development Company Profileakrivarotava
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...OnePlan Solutions
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonApplitools
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencessuser9e7c64
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingShane Coughlan
 

Último (20)

Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
SoftTeco - Software Development Company Profile
SoftTeco - Software Development Company ProfileSoftTeco - Software Development Company Profile
SoftTeco - Software Development Company Profile
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conference
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
 

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