JUNIT 5 & TESTCONTAINERS. Testing with Java and Docker

Similar documents
Görge Albrecht State of the Union

Embracing. with. Noopur Gupta. Eclipse JDT co-lead. IBM

JUnit. New Opportunities for Testing on the

JUnit 5 User Guide. Stefan Bechtold, Sam Brannen, Johannes Link, Matthias Merdes, Marc Philipp, Christian Stein. Version 5.1.0

Junit 5 and Sling/AEM Mocks

JUNIT 5 EXTENSIONS 1. 1

Test-Driven Development JUnit

Java Programming Basics

JUnit 5 - Was bringt die neue Version?

Binghamton University. CS-140 Fall Unit Testing

Binghamton University. CS-140 Fall Unit Testing

A Guided Tour of Test Automation

Selenium Testing Course Content

Selenium. Duration: 50 hrs. Introduction to Automation. o Automating web application. o Automation challenges. o Automation life cycle

Test Execution and Automation. CSCE Lecture 15-03/20/2018

SELENIUM TRAINING COURSE CONTENT

Appium mobile test automation

SELENIUM. Courses Offered. Ph: / Course Coverage:- Date:..Timings.. Duration Fees. Testing Tools QTP Load Runner Hadoop

Mind Q Systems Private Limited

SELENIUM. SELENIUM COMPONENTS Selenium IDE Selenium RC Selenium Web Driver Selenium Grid

Mind Q Systems Private Limited

Programming Kotlin. Familiarize yourself with all of Kotlin s features with this in-depth guide. Stephen Samuel Stefan Bocutiu BIRMINGHAM - MUMBAI

Selenium Training. Training Topics

(Complete Package) We are ready to serve Latest Testing Trends, Are you ready to learn? New Batches Info

Learning Objectives of CP-SAT v 1.31

Unit Testing. CS 240 Advanced Programming Concepts

(Complete Package) We are ready to serve Latest Testing Trends, Are you ready to learn? New Batches Info

JAVA Unit testing Java, winter semester

Best Practices for Unit Testing in Kotlin

Selenium Course Content

CSCE 747 Unit Testing Laboratory Name(s):

SeleniumJava Training Solution

Learning Objectives of CP-SAT v 1.3

JUnit Programming Cookbook. JUnit Programming Cookbook

Introduction to Automation. What is automation testing Advantages of Automation Testing How to learn any automation tool Types of Automation tools

Unit Tes2ng Ac2vity. SWEN-261 Introduc2on to So3ware Engineering. Department of So3ware Engineering Rochester Ins2tute of Technology

Class 1 Introduction to Selenium, Software Test Life Cycle.

AUTOMATION TESTING FRAMEWORK FOR LUMINOUS LMS

[paf Wj] open source. Selenium 1.0 Testing Tools. Beginner's Guide. using the Selenium Framework to ensure the quality

International Journal of Advance Engineering and Research Development. Proof of concept (Poc) selenium web driver based Automation framework

Hoverfly Java Documentation

CS 215 Software Design Homework 3 Due: February 28, 11:30 PM

mvn package -Dmaven.test.skip=false //builds DSpace and runs tests

Unit Testing Activity

CS201 - Assignment 3, Part 1 Due: Friday February 28, at the beginning of class

Peers Techno log ies Pv t. L td. Core Java & Core Java &Adv Adv Java Java

EXPERT TRAINING PROGRAM [Selenium 2.0 / WebDriver]

Beyond JUnit: Introducing TestNG The Next Generation in Testing

JUnit Framework. Terminology: assertions, annotations, fixtures. Dr. Siobhán Drohan Mairead Meagher. Produced by:

P2: Advanced Java & Exam Preparation

SELENIUM - REMOTE CONTROL

REPAST MODEL TESTING GUIDE

SWE 434 Software Testing and Validation

Java SE 8 Programming

White-box testing. Software Reliability and Testing - Barbara Russo SERG - Laboratory of Empirical Software Engineering.

Topics covered. Introduction to JUnit JUnit: Hands-on session Introduction to Mockito Mockito: Hands-on session. JUnit & Mockito 2

The age of automation is going to be the age of 'do it yourself. - Marshall McLuhan

JAVA. 1. Introduction to JAVA

About 1. Chapter 1: Getting started with testng 2. Remarks 2. Versions 2. Examples 2. Installation or Setup 2. Quick program using TestNG 3

SeU Certified Selenium Engineer (CSE) Syllabus

What is the Selendroid?

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Java Review via Test Driven Development

Good Luck! CSC207, Fall 2012: Quiz 3 Duration 25 minutes Aids allowed: none. Student Number: Lecture Section: L0101. Instructor: Horton

CS410J: Advanced Java Programming

Accessibility. Adding features to support users with impaired vision, mobility, or hearing

Annotations in Java (JUnit)

Junit Overview. By Ana I. Duncan

Java SE 8 Programming

Getting Started with. Lite.

SeU Certified Selenium Engineer (CSE) Syllabus

ULC Test Framework Guide. Canoo RIA-Suite 2014 Update 4

Testing. Technion Institute of Technology Author: Assaf Israel. Author: Assaf Israel - Technion

Exceptions and Libraries

JUnit + JMock Tomáš Soukup

Testing on Android. Mobile Application Development. Jakob Mass MTAT Fall MTAT

Kotlin In Spreadshirt. JUG Saxony Day, Spreadshirt

Unit testing. JUnit. JUnit and Eclipse. A JUnit test class 3/6/17. A method is flagged as a JUnit test case.

C07: Testing and JUnit

LarvaLight User Manual

FOR BEGINNERS 3 MONTHS

Test Automation Integration with Test Management QAComplete

Chapter 11 Paper Practice

The course is supplemented by numerous hands-on labs that help attendees reinforce their theoretical knowledge of the learned material.

CORE JAVA TRAINING COURSE CONTENT

@AfterMethod

Learning Objectives of CP-SAT v 1.31 (C#)

Selenium Java Framework

Test-Driven Development JUnit

print statements, debugger expressions, test scripts. Writing expressions in a debugger only that t a program works now. An application typically

CS159. Nathan Sprague. September 30, 2015

Technology. Business Objectives & Challenges. Overview. Technical Solution

Test Automation Integration with Test Management QAComplete

Unit testing. unit testing: Looking for errors in a subsystem in isolation. The basic idea: JUnit provides "assert" commands to help us write tests.

STQA Mini Project No. 1

ActiveNET Enterprise Solution Company

Section 4: Graphs and Testing

Java SE 8 Programming

CS 3 Introduction to Software Engineering. 5: Iterators

All About Cranking Out High Quality XPages Applications. Martin Donnelly IBM Ireland

Transcription:

JUNIT 5 & TESTCONTAINERS Testing with Java and Docker

TIM RIEMER Solution Architect @ Vorwerk Digital tim.riemer@vorwerk.de Co-Lead Kotlin UG Dusseldorf @zordan_f github.com/timriemer

JUNIT 5

JUNIT 5 JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage Current version: 5.3.1 No public modifier needed Requires Java 8 or greater Support in IntelliJ IDEA and Eclipse IDE

EXAMPLE @Test public void simpletest() { assertequals(2, 1+1); }

EXAMPLE // JUnit 4 Imports import org.junit.test; import static org.junit.assert.assertequals;

EXAMPLE // JUnit 5 Imports import org.junit.jupiter.api.test; import static org.junit.jupiter.api.assertions.assertequals;

DEPENDENCIES <dependency> <groupid>org.junit.jupiter</groupid> <artifactid>junit-jupiter-engine</artifactid> <version>5.3.1</version> <scope>test</scope> </dependency>

ANNOTATIONS // JUnit 4 @BeforeClass @BeforeAll static void tearup() { System.out.println("tearUp!"); } // JUnit 4 @AfterClass @AfterAll static void teardown() { System.out.println("tearDown!"); }

ANNOTATIONS // JUnit 4 @Before @BeforeEach void before() { System.out.println("before!"); } // JUnit 4 @After @AfterEach void after() { System.out.println("after!"); }

ANNOTATIONS // JUnit 4 @Ignore @Disabled @Test void simpletest() { assertequals(2, 1+1); }

ANNOTATIONS Nested test classes with @Nested Must be non-static inner classes Can contain test methods, one @BeforeEach and @AfterEach method No limit for depth of class hierarchy

ANNOTATIONS @Nested class InnerClass { @Test void innerclasstest() { assertequals(4, 2+2); } }

ANNOTATIONS @Test @DisplayName("Should validate that the sum of 2 + 2 equals 4") void shouldchecksumofcalculation() { assertequals(4, 2+2); }

ASSERTIONS New class: org.junit.jupiter.api.assertions Use of lambdas for lazy evaluation of messages Grouping of assertions New way to handle exceptions

ASSERTIONS @Test void simpletest() { assertequals(5, 2+2, () -> "Result should be 5"); }

ASSERTIONS @Test void simpletestforassertall() { assertall( () -> assertequals(2, 1+1), () -> assertequals(4, 2+2) ); }

ASSERTIONS @Test void shouldthrowexception() { assertthrows(unsupportedoperationexception.class, () -> { throw new UnsupportedOperationException ("Operation not supported"); }); }

ASSERTIONS @Test void shouldcheckthrownexception() { var exception = assertthrows(unsupportedoperationexception.class, () -> { throw new UnsupportedOperationException ("Operation not supported"); }); assertequals("operation not supported, exception.getmessage()); }

ASSERTIONS @Test void testasserttimeout() { asserttimeout(ofseconds(10), () -> { Thread.sleep(15000); }); }

ASSERTIONS @Test void testasserttimeoutpreemptively() { asserttimeoutpreemptively(ofseconds(10), () -> { Thread.sleep(15000); }); }

ASSUMPTIONS TestAbortedException if assumption fails -> test is skipped @Test void assumptiontest() { assumetrue(true); assumefalse(false); assumingthat("abc".equals("abc"), () -> assertequals(2, 1+1)); }

DYNAMIC TESTS @TestFactory Stream<DynamicTest> dynamictestsfromstream() { return Stream.of(1, 2, 3).map(i -> dynamictest("test " + i, () -> { assertequals(i * 2, i + i); })); }

DYNAMIC TESTS

CONDITIONAL TEST EXECUTION ExecutionCondition as extension API DisabledCondition simplest example with @Disabled annotation

CONDITIONAL TEST EXECUTION @EnabledOnOS( ) @EnabledOnJre( ) @EnabledIfSystemProperty(named =, matches = ) @EnabledIfEnvironmentalVariable(named =, matches = ) @EnabledIf( ), support for scripting languages, EXPERIMENTAL

PARAMETERIZED TESTS Experimental feature junit-jupiter-params dependency needed

PARAMETERIZED TESTS @ParameterizedTest @ValueSource(strings = {"java8", "java9", "java10"}) void parameterizedtest(string param) { asserttrue(param.contains("java")); }

PARAMETERIZED TESTS @ParameterizedTest(name = "[{index}] => {arguments}") @ValueSource(strings = {"java8", "java9", "java10"}) void parameterizedtest(string param) { asserttrue(param.contains("java")); }

PARAMETERIZED TESTS @ValueSource for String, int, long and double @EnumSource( ) @MethodSource( methodname ) - method must return Stream, Iterator or Iterable @CsvSource({ foo, bar, foo2, bar2 }) @CsvFileSource(resources = ) @ArgumentSource(MyArgumentsProvider.class)

PARALLEL TEST EXCECUTION src/test/resources/junit-platform.properties: junit.jupiter.execution.parallel.enabled = true #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 EXCECUTION Synchronization for shared resources @Execution(CONCURRENT) @Execution(SAME_THREAD) @ResourceLock(value =, mode = ) value: user-defined String, SYSTEM_PROPERTIES,, SYSTEM_OUT, SYSTEM_ERR mode: READ, READ_WRITE

WHAT ELSE? @Tag and filtering in build script @RepeatedTest with dynamic placeholder for @DisplayName @TestTemplate / TestTemplateInvocationContextProvider Extension API, extensions registered via @ExtendWith

INTRODUCTION Java library to launch Docker containers during JUnit tests Integration tests against the data access layer Integration tests with external dependencies (e.g. message broker, database, ) UI tests with containerized, Selenium compatible, web browsers

INTRODUCTION Current version: 1.9.1 Requires Docker installation Requires Java 8 Compatible with JUnit

DEPENDENCIES <dependency> <groupid>org.testcontainers</groupid> <artifactid>testcontainers</artifactid> <version>1.9.1</version> <scope>test</scope> </dependency>

OWN MAVEN MODULES MySQL PostgreSQL Oracle XE Kafka Selenium

JUNIT 4 @ClassRule public static GenericContainer wildfly = new GenericContainer("jboss/wildfly").withExposedPorts(8080, 9990); @Test public void getexposedports() { var ports = wildfly.getexposedports(); var expectedports = Arrays.asList(8080, 9990); assertequals(expectedports, ports); }

JUNIT 5 static GenericContainer wildfly = new GenericContainer("jboss/wildfly").withExposedPorts(8080, 9990); @BeforeAll static void startup() { wildfly.start(); } @AfterAll static void teardown() { wildfly.stop(); } @Test void getexposedports() { var ports = wildfly.getexposedports(); var expectedports = Arrays.asList(8080, 9990); assertequals(expectedports, ports); }

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( )

SPECIALISED CONTAINER Create images from Dockerfile withfilefromstring( ) withfilefromclasspath( ) Use Dockerfile DSL to define Dockerfiles in code

SPECIALISED CONTAINER @Test void testdockerdslcontainer() { var container = new GenericContainer( new ImageFromDockerfile().withDockerfileFromBuilder(builder -> { builder.from( alpine:3.2").run("apk add --update git").cmd("git", version").build(); })).withexposedports(80); assertequals(arrays.aslist(80), container.getexposedports()); }

SPECIALISED CONTAINER Use database container to test database specific features No local setup or VM 100% database compatibility instead of in-memory H2 MySQL PostgreSQL Oracle XE

TESTCONTAINERS EXTENSION (NAIVE APPROACH) public class TestcontainersExtension implements BeforeAllCallback, AfterAllCallback { private List<Field> allcontainers; @Override public void beforeall(extensioncontext context) throws Exception { // find all containers via Reflection, add them to allcontainers and iterate over them ((GenericContainer) f.get(container)).start(); // } } @Override public void afterall(extensioncontext context) throws Exception { // iterate over allcontainers and stop each container ((GenericContainer) f.get(container)).stop(); // }

SPECIALISED CONTAINER // @ExtendWith(TestcontainersExtension.class) on class level private static PostgreSQLContainer postgres = new PostgreSQLContainer(); @Test void testsimplesql() throws SQLException { // HikariConfig, HikariDataSource and Statement omitted statement.execute("select 1"); ResultSet resultset = statement.getresultset(); resultset.next(); assertequals(1, resultset.getint(1)); } }

SELENIUM WEBDRIVER CONTAINER Compatible with Selenium 2 / Webdriver tests Use of all Selenium docker images from selenium-docker project Clean and fixed environment for each browser and test Selenium API and browser compatibility assured VNC recording (optionally just failed tests)

SELENIUM WEBDRIVER CONTAINER // @ExtendWith(TestcontainersExtension.class) on class level private BrowserWebDriverContainer chrome = new BrowserWebDriverContainer<>().withDesiredCapabilities(DesiredCapabilities.chrome()).withNetwork(Network.SHARED).withNetworkAliases("vnchost").withRecordingMode(BrowserWebDriverContainer.VncRecordingMode.SKIP, null); private VncRecordingContainer vnc = new VncRecordingContainer(chrome); @Test void searchfortestcontainersongoogle() { chrome.getwebdriver().get("http://www.google.com"); chrome.getwebdriver().findelement(by.name("q")).sendkeys("testcontainers"); chrome.getwebdriver().findelement(by.name("q")).submit(); assertequals("testcontainers", driver.findelement(by.name( q")).getattribute("value")); } vnc.saverecordingtofile(new File("build/", name + testcontainers.flv ));

FUTURE Testcontainers 2.0 API cleanup Decoupling from JUnit 4 to support other frameworks directly

ALTERNATIVES TestNG Other JVM languages Groovy, Spock, Testcontainers-Spock Kotlin, Testcontainers (with workaround)

QUESTIONS @zordan_f github.com/timriemer/jdk10_junit_testcontainers