SlideShare a Scribd company logo
JUnit 5
Sam Brannen
@sam_brannen
October 7–10, 2019
Austin Convention Center
Evolution and Innovation
2@s1p @sam_brannen #JUnit5 #springone
Sam Brannen
Principal Software Engineer
Java Developer for over 20 years
Spring Framework Core Committer since 2007
JUnit 5 Core Committer since October 2015
3@s1p @sam_brannen #JUnit5 #springone
Agenda
JUnit 5
JUnit Jupiter
What’s New
What’s Coming
Spring and JUnit Jupiter
Q & A
Show of hands…
JUnit 5
P L A T F O R M
J U P I T E RV I N T A G E
P A R T Y
T H I R D
7@s1p @sam_brannen #JUnit5 #springone
JUnit 5 = Platform + Jupiter + Vintage
JUnit Platform
• Foundation for launching testing frameworks on the JVM
• Launcher and TestEngine APIs
• ConsoleLauncher
JUnit Jupiter
• New programming model & extension model for JUnit 5
JUnit Vintage
• TestEngine for running JUnit 3 & JUnit 4 based tests
revolutionary
evolutionary
necessary
8@s1p @sam_brannen #JUnit5 #springone
Third-party TestEngines
Specsy
Spek
Cucumber
Drools Scenario
jqwik
source: https://github.com/junit-team/junit5/wiki/Third-party-Extensions
9@s1p @sam_brannen #JUnit5 #springone
Java Versions
Baseline
• AUTOMATIC-MODULE-NAME
• Module descriptors (since 5.5)
• module-path scanning
Building and testing
against 11, 12, 13, 14-ea
10@s1p @sam_brannen #JUnit5 #springone
IDEs and Build Tools
IntelliJ: since IDEA 2016.2+
Eclipse: since Eclipse Oxygen 4.7.1a+
VS Code: since March 2018
NetBeans: since Apache NetBeans 10.0
Gradle: official test task support since Gradle 4.6
Maven: official support since Maven Surefire 2.22.0
Ant: junitlauncher task since Ant 1.10.3
See user guide and
sample apps for
examples
Or just go to
start.spring.io
11@s1p @sam_brannen #JUnit5 #springone
Releases
Version Date
5.0.0 September 10th, 2017
… …
5.3.0 September 3rd, 2018
5.4.0 February 7th, 2019
5.5.0 June 30th, 2019
5.5.2 September 8th, 2019
JUnit Jupiter
13@s1p @sam_brannen #JUnit5 #springone
In a Nutshell, JUnit Jupiter is …
“The new programming model and extension model in JUnit 5”
Programming Model
• How you write tests
• Annotations
• Assertions
• Assumptions
• Types of tests
Extension Model
• How you and third parties extend the framework
• Spring, Mockito, AssertJ, Selenium, …
14@s1p @sam_brannen #JUnit5 #springone
More Powerful Programming Model
What you can do with JUnit Jupiter that you can’t do with JUnit 4.
Visibility
• Everything does not have to be public
Custom display names
• @DisplayName: spaces, special characters, emoji 😱
• DisplayNameGenerator
Tagging
• @Tag replaces experimental @Category
• Tag Expression Language
The Basics
16@s1p @sam_brannen #JUnit5 #springone
Example: CalculatorTests
@DisplayName("Calculator Unit Tests")
class CalculatorTests {
private final Calculator calculator = new Calculator();
@Test
@DisplayName("addition")
void add() {
assertEquals(5, calculator.add(2, 3),
() -> "2 + 3 = " + (2 + 3));
}
// ...
}
17@s1p @sam_brannen #JUnit5 #springone
Expected Exceptions
@Test
@DisplayName("n / 0 --> ArithmeticException")
void divideByZero() {
Exception exception = assertThrows(ArithmeticException.class,
() -> calculator.divide(1, 0));
assertEquals("/ by zero", exception.getMessage());
}
18@s1p @sam_brannen #JUnit5 #springone
Programmatic Timeouts
@Test
@DisplayName("Ensure Fibonacci computation is 'fast enough'")
void fibonacci() {
// assertTimeout(ofMillis(1000),
// () -> calculator.fibonacci(30));
assertTimeoutPreemptively(ofMillis(1000),
() -> calculator.fibonacci(30));
}
19@s1p @sam_brannen #JUnit5 #springone
Even More Power and Expressiveness
Meta-annotation support
• Create your own custom composed annotations
• Combine annotations from Spring and JUnit
Conditional test execution
Dependency injection for constructors and methods
Lambda expressions and method references
Interface default methods and testing traits
@Nested test classes
@RepeatedTest, @ParameterizedTest, @TestFactory
@TestInstance lifecycle management
Focus on Extensibility
21@s1p @sam_brannen #JUnit5 #springone
New Extension Model
Extension
• marker interface
org.junit.jupiter.api.extension
• package containing all extension APIs
• implement as many as you like
@ExtendWith(...)
• used to register one or more extensions
• interface, class, or method level
o or as a meta-annotation
@RegisterExtension
• programmatic registration via fields
22@s1p @sam_brannen #JUnit5 #springone
Extension APIs – Lifecycle Callbacks
• BeforeAllCallback
• BeforeEachCallback
• BeforeTestExecutionCallback
• AfterTestExecutionCallback
• AfterEachCallback
• AfterAllCallback
Extensions wrap
user-supplied
lifecycle methods
and test methods
23@s1p @sam_brannen #JUnit5 #springone
Extension APIs – Exception Handling
• TestExecutionExceptionHandler
• @Test and @TestFactory methods
• @RepeatedTest and @ParameterizedTest invocations
• LifecycleMethodExecutionExceptionHandler (since 5.5)
• @BeforeAll, @AfterAll, @BeforeEach, and @AfterEach methods
24@s1p @sam_brannen #JUnit5 #springone
Extension APIs – Dependency Injection
• TestInstanceFactory
• TestInstancePostProcessor
• ParameterResolver
25@s1p @sam_brannen #JUnit5 #springone
Extension APIs – Miscellaneous
• ExecutionCondition
• @Disabled, @EnabledOnOs, @DisabledOnJre, …
• InvocationInterceptor (since 5.5)
• TestWatcher (since 5.4)
• TestTemplateInvocationContextProvider
• @TestTemplate, @RepeatedTest, @ParameterizedTest, …
26@s1p @sam_brannen #JUnit5 #springone
Extension APIs – Discovery Phase
• DisplayNameGenerator (since 5.4)
• MethodOrderer (since 5.4)
27@s1p @sam_brannen #JUnit5 #springone
InvocationInterceptor
• API for intercepting constructor and method invocations
• Test class constructor
• @BeforeAll, @AfterAll, @BeforeEach, @AfterEach methods
• @Test, @TestFactory, @TestTemplate methods
• DynamicTest invocations
• Can be used to execute user code in a separate thread
• For example, to execute Swing code in the event dispatch thread (EDT)
28@s1p @sam_brannen #JUnit5 #springone
TestWatcher
• API for processing the results of test execution
• Supported for @Test and @TestTemplate methods
• Events fired:
• disabled
• aborted
• succeeded
• failed
• Can be used for custom logging, reporting, conditional execution of
subsequent tests, …
29@s1p @sam_brannen #JUnit5 #springone
DisplayNameGenerator
• SPI for generating custom display names for classes and methods
• Configured via @DisplayNameGeneration
• Implement your own
• Or use a built-in implementation:
• Standard: default behavior
• ReplaceUnderscores: replaces underscores with spaces
30@s1p @sam_brannen #JUnit5 #springone
MethodOrderer
• API for controlling test method execution order
• Configured via @TestMethodOrder
• Implement your own
• Or use a built-in implementation:
• Alphanumeric: sorted alphanumerically
• OrderAnnotation: sorted based on @Order
• Random: pseudo-random ordering
What’s New
32@s1p @sam_brannen #JUnit5 #springone
New in JUnit 5.4 (1/2)
• Discontinuation of the junit-platform-surefire-provider
• New junit-jupiter dependency-aggregating artifact
• LegacyXmlReportGeneratingListener
• Test Kit for testing engines and extensions
• null and empty argument sources for @ParameterizedTest methods
• @TempDir support for temporary directories
33@s1p @sam_brannen #JUnit5 #springone
New in JUnit 5.4 (2/2)
• Custom display name generator API: DisplayNameGenerator
• Ordering: @Test methods and @RegisterExtension fields
• TestWatcher extension API
• API for accessing outer test instances in ExtensionContext
• Improved JUnit 4 migration support: Assumptions and @Ignore
• Improved diagnostics and error reporting
34@s1p @sam_brannen #JUnit5 #springone
Example: @TempDir
@Test
void writeItems(@TempDir Path tempDir) throws IOException {
Path file = tempDir.resolve("test.txt");
new ListWriter(file).write("a", "b", "c");
assertEquals(singletonList("a,b,c"),
Files.readAllLines(file));
}
Demo
DisplayNameGenerator
Demo
Ordering Test Methods
Demo
TestWatcher
@SkipOnFailuresInEnclosingClass
38@s1p @sam_brannen #JUnit5 #springone
Example: Test Kit
@Test
void verifyStats() {
EngineTestKit.engine("junit-jupiter")
.selectors(selectClass(ExampleTestCase.class))
.execute()
.testEvents()
.assertStatistics(stats -> stats
.skipped(1)
.started(3)
.succeeded(1)
.aborted(1)
.failed(1));
}
39@s1p @sam_brannen #JUnit5 #springone
New in JUnit 5.5 (1/2)
• Global timeouts and @Timeout
• @EnabledIf and @DisabledIf deprecated
• @ValueSource supports boolean literal values
• New emptyValue attribute in @CsvSource and @CsvFileSource
• New junit.jupiter.displayname.generator.default config param
to set default DisplayNameGenerator
40@s1p @sam_brannen #JUnit5 #springone
New in JUnit 5.5 (2/2)
• New InvocationInterceptor extension API
• New LifecycleMethodExecutionExceptionHandler extension API
• Configurable test discovery implementation for TestEngine authors
• Explicit Java module descriptors
Demo
@Timeout
Demo
InvocationInterceptor
SwingEdtInterceptor
Demo
LifecycleMethodExecutionExceptionHandler
BindExceptionHandler
What’s Coming
45@s1p @sam_brannen #JUnit5 #springone
Coming in JUnit 5.6 (1/2)
• @EnabledIf and @DisabledIf will be removed
• Multi-character delimiters in @CsvSource and @CsvFileSource
• Custom null values in @CsvSource and @CsvFileSource
• Documented support for comments in CSV files loaded via @CsvFileSource
• Auto-detection of enum type from method signature for @EnumSource
• @EnabledForJreRange and @DisabledForJreRange
• @Timeout disabled while in debug mode
46@s1p @sam_brannen #JUnit5 #springone
Coming in JUnit 5.6 (2/2)
• API to select and execute individual tests in inherited nested classes
• New TestInstancePreDestroyCallback extension API
• counterpart to TestInstancePostProcessor
• New TypeBasedParameterResolver<T> abstract base class
• generic adapter for the ParameterResolver API
• simplifies parameter resolution of a specific type
• Support for first/last order for extensions registered via @RegisterExtension
• Significant performance improvements for the Vintage test engine
47@s1p @sam_brannen #JUnit5 #springone
On the Horizon
• Parameterized test classes
• Custom ClassLoader
• Declarative and programmatic test suites for the JUnit Platform
• Scenario tests
• Programmatic extension management
• New XML / JSON reporting format
• ...
Spring and JUnit Jupiter
49@s1p @sam_brannen #JUnit5 #springone
Spring Support for JUnit Jupiter
• Fully integrated in Spring Framework 5.0!
• Supports all Core Spring TestContext Framework features
• Constructor and method injection via @Autowired, @Qualifier, @Value
• Conditional test execution via SpEL expressions
• ApplicationContext configuration annotations
• Also works with Spring Framework 4.3
https://github.com/sbrannen/spring-test-junit5
50@s1p @sam_brannen #JUnit5 #springone
Configuring JUnit Jupiter with Spring
SpringExtension
• @ExtendWith(SpringExtension.class)
@SpringJUnitConfig
• @ContextConfiguration + SpringExtension
@SpringJUnitWebConfig
• @SpringJUnitConfig + @WebAppConfiguration
@EnabledIf / @DisabledIf
• SpEL expression evaluation for conditional execution
51@s1p @sam_brannen #JUnit5 #springone
Automatic Test Constructor Autowiring (5.2)
By default, a test class constructor must be annotated with @Autowired
The “default” can be changed
• set spring.test.constructor.autowire.mode=all
• JVM system property or SpringProperties mechanism
@TestConstructor(autowireMode = ALL / ANNOTATED)
• Overrides default on a per-class basis
52@s1p @sam_brannen #JUnit5 #springone
What’s New in spring-test 5.2
https://github.com/spring-projects/spring-framework/wiki/What's-New-in-Spring-Framework-5.x#testing
53@s1p @sam_brannen #JUnit5 #springone
Spring Boot 2.2 & JUnit Jupiter – Custom Config
@Target(TYPE)
@Retention(RUNTIME)
// @ExtendWith(SpringExtension.class)
@SpringBootTest
@AutoConfigureMockMvc
@Transactional
public @interface SpringEventsWebTest {
}
@SpringBootTest + @AutoConfigureMockMvc + @ExtendWith(SpringExtension.class)
54@s1p @sam_brannen #JUnit5 #springone
Spring Boot 2.2 & JUnit Jupiter – MockMvc Test
@SpringEventsWebTest
class EventsControllerTests {
@Test
@DisplayName("Home page should display more than 10 events")
void listEvents(@Autowired MockMvc mockMvc) throws Exception {
mockMvc.perform(get("/"))
.andExpect(view().name("event/list"))
.andExpect(model().attribute("events",
hasSize(greaterThan(10))));
}
}
@SpringEventsWebTest + method-level DI + MockMvc
55@s1p @sam_brannen #JUnit5 #springone
Tip: Upgrading JUnit 5 Version in Spring Boot
Popular question…
• https://stackoverflow.com/a/54605523/388980
Gradle:
ext['junit-jupiter.version'] = '5.5.2'
Maven:
<properties>
<junit-jupiter.version>5.5.2</junit-jupiter.version>
</properties>
Getting Involved
57@s1p @sam_brannen #JUnit5 #springone
How can I help out?
Participate on GitHub
• Report issues
• Suggest new features
• Participate in discussions
Answer questions on Stack Overflow and Gitter
Support the JUnit Team with donations via Steady HQ
https://steadyhq.com/en/junit
In closing…
59@s1p @sam_brannen #JUnit5 #springone
JUnit 5 Resources
Project Homepage à http://junit.org/junit5
User Guide à http://junit.org/junit5/docs/current/user-guide
Javadoc à http://junit.org/junit5/docs/current/api
GitHub à https://github.com/junit-team
Gitter à https://gitter.im/junit-team/junit5
Stack Overflow à http://stackoverflow.com/tags/junit5
60@s1p @sam_brannen #JUnit5 #springone
Demos Used in this Presentation
https://github.com/sbrannen/junit5-demo
https://github.com/junit-team/junit5/tree/master/documentation/src/test
Unless otherwise indicated, these slides are © 2013-2019 Pivotal Software, Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/
Thank You!
Sam Brannen
@sam_brannen
JUnit
#springone@s1p

More Related Content

PPTX
JUnit 5: What's New and What's Coming - Spring I/O 2019
PDF
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
PDF
JUnit 5 - New Opportunities for Testing on the JVM
PDF
JUnit 5 - The Next Generation
PPTX
JUnit 5 - from Lambda to Alpha and beyond
PDF
JUnit 5 — New Opportunities for Testing on the JVM
PPTX
Renaissance of JUnit - Introduction to JUnit 5
PDF
Testing with Spring 4.x
JUnit 5: What's New and What's Coming - Spring I/O 2019
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
JUnit 5 - New Opportunities for Testing on the JVM
JUnit 5 - The Next Generation
JUnit 5 - from Lambda to Alpha and beyond
JUnit 5 — New Opportunities for Testing on the JVM
Renaissance of JUnit - Introduction to JUnit 5
Testing with Spring 4.x

What's hot (20)

PPTX
Get the Most out of Testing with Spring 4.2
DOCX
Realtime selenium interview questions
PDF
DOCX
Selenium notes
PDF
Testing Spring Boot Applications
PDF
Advanced Selenium Workshop
DOCX
Selenium interview-questions-freshers
PPTX
TDD - Unit Testing
PPTX
Spring Test Framework
PDF
What is new in JUnit5
DOCX
Selenium interview questions
PPT
RPG Program for Unit Testing RPG
PPTX
Codeception
DOCX
Test driven development and unit testing with examples in C++
PPTX
Python in Test automation
PDF
Cucumber questions
PDF
Test Automation
PPTX
Introduction to JUnit testing in OpenDaylight
PPTX
Integration Group - Robot Framework
PDF
PHP Unit Testing in Yii
Get the Most out of Testing with Spring 4.2
Realtime selenium interview questions
Selenium notes
Testing Spring Boot Applications
Advanced Selenium Workshop
Selenium interview-questions-freshers
TDD - Unit Testing
Spring Test Framework
What is new in JUnit5
Selenium interview questions
RPG Program for Unit Testing RPG
Codeception
Test driven development and unit testing with examples in C++
Python in Test automation
Cucumber questions
Test Automation
Introduction to JUnit testing in OpenDaylight
Integration Group - Robot Framework
PHP Unit Testing in Yii
Ad

Similar to JUnit 5 - Evolution and Innovation - SpringOne Platform 2019 (20)

PPT
PPTX
Expanding Your .NET Testing Toolbox - GLUG NET
PDF
Test Driven Development with JavaFX
PPTX
Testes? Mas isso não aumenta o tempo de projecto? Não quero...
PPTX
Getting Started with Test-Driven Development at Longhorn PHP 2023
PPTX
Episode 5 - Writing unit tests in Salesforce
PPT
Unit testing with Spock Framework
PPTX
How do you tame a big ball of mud? One test at a time.
PPTX
Whitebox testing of Spring Boot applications
PPTX
Junit_.pptx
PDF
Kristian Karl - Experiences of Test Automation at Spotify - EuroSTAR 2013
PDF
Kristian Karl - Experiences of Test Automation at Spotify - EuroSTAR 2013
PDF
Test driven development
PDF
Automated Developer Testing: Achievements and Challenges
PPTX
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
 
PDF
Java Unit Testing Tool Competition — Fifth Round
PPTX
Unit tests & TDD
PPT
API Performance Testing
PDF
Testing with JUnit 5 and Spring
PDF
May: Automated Developer Testing: Achievements and Challenges
Expanding Your .NET Testing Toolbox - GLUG NET
Test Driven Development with JavaFX
Testes? Mas isso não aumenta o tempo de projecto? Não quero...
Getting Started with Test-Driven Development at Longhorn PHP 2023
Episode 5 - Writing unit tests in Salesforce
Unit testing with Spock Framework
How do you tame a big ball of mud? One test at a time.
Whitebox testing of Spring Boot applications
Junit_.pptx
Kristian Karl - Experiences of Test Automation at Spotify - EuroSTAR 2013
Kristian Karl - Experiences of Test Automation at Spotify - EuroSTAR 2013
Test driven development
Automated Developer Testing: Achievements and Challenges
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
 
Java Unit Testing Tool Competition — Fifth Round
Unit tests & TDD
API Performance Testing
Testing with JUnit 5 and Spring
May: Automated Developer Testing: Achievements and Challenges
Ad

More from Sam Brannen (20)

PPTX
Testing with Spring, AOT, GraalVM, and JUnit 5 - Spring I/O 2023
PDF
Testing with JUnit 5 and Spring - Spring I/O 2022
PDF
Testing with Spring: An Introduction
PDF
Spring Framework 4.1
PDF
Testing Spring MVC and REST Web Applications
PDF
Composable Software Architecture with Spring
PDF
Testing Web Apps with Spring Framework 3.2
PDF
Spring Framework 4.0 to 4.1
PDF
Spring Framework 4.0 - The Next Generation - Soft-Shake 2013
PPTX
Spring Framework 3.2 - What's New
PDF
Spring 3.1 and MVC Testing Support - 4Developers
PPTX
Effective out-of-container Integration Testing - 4Developers
PPTX
Spring 3.1 to 3.2 in a Nutshell - SDC2012
PPTX
Spring 3.1 to 3.2 in a Nutshell - Spring I/O 2012
PDF
Spring 3.1 and MVC Testing Support
PDF
Spring 3.1 in a Nutshell - JAX London 2011
PDF
Spring 3.1 in a Nutshell
PDF
Spring Web Services: SOAP vs. REST
PDF
Effective out-of-container Integration Testing
PPT
What's New in Spring 3.0
Testing with Spring, AOT, GraalVM, and JUnit 5 - Spring I/O 2023
Testing with JUnit 5 and Spring - Spring I/O 2022
Testing with Spring: An Introduction
Spring Framework 4.1
Testing Spring MVC and REST Web Applications
Composable Software Architecture with Spring
Testing Web Apps with Spring Framework 3.2
Spring Framework 4.0 to 4.1
Spring Framework 4.0 - The Next Generation - Soft-Shake 2013
Spring Framework 3.2 - What's New
Spring 3.1 and MVC Testing Support - 4Developers
Effective out-of-container Integration Testing - 4Developers
Spring 3.1 to 3.2 in a Nutshell - SDC2012
Spring 3.1 to 3.2 in a Nutshell - Spring I/O 2012
Spring 3.1 and MVC Testing Support
Spring 3.1 in a Nutshell - JAX London 2011
Spring 3.1 in a Nutshell
Spring Web Services: SOAP vs. REST
Effective out-of-container Integration Testing
What's New in Spring 3.0

Recently uploaded (20)

PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
AI in Product Development-omnex systems
PDF
medical staffing services at VALiNTRY
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Understanding Forklifts - TECH EHS Solution
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
Nekopoi APK 2025 free lastest update
PPTX
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
Digital Strategies for Manufacturing Companies
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PPT
Introduction Database Management System for Course Database
Operating system designcfffgfgggggggvggggggggg
AI in Product Development-omnex systems
medical staffing services at VALiNTRY
PTS Company Brochure 2025 (1).pdf.......
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Understanding Forklifts - TECH EHS Solution
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Nekopoi APK 2025 free lastest update
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
Upgrade and Innovation Strategies for SAP ERP Customers
How Creative Agencies Leverage Project Management Software.pdf
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Digital Strategies for Manufacturing Companies
How to Migrate SBCGlobal Email to Yahoo Easily
Which alternative to Crystal Reports is best for small or large businesses.pdf
Odoo POS Development Services by CandidRoot Solutions
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
VVF-Customer-Presentation2025-Ver1.9.pptx
Introduction Database Management System for Course Database

JUnit 5 - Evolution and Innovation - SpringOne Platform 2019

  • 1. JUnit 5 Sam Brannen @sam_brannen October 7–10, 2019 Austin Convention Center Evolution and Innovation
  • 2. 2@s1p @sam_brannen #JUnit5 #springone Sam Brannen Principal Software Engineer Java Developer for over 20 years Spring Framework Core Committer since 2007 JUnit 5 Core Committer since October 2015
  • 3. 3@s1p @sam_brannen #JUnit5 #springone Agenda JUnit 5 JUnit Jupiter What’s New What’s Coming Spring and JUnit Jupiter Q & A
  • 6. P L A T F O R M J U P I T E RV I N T A G E P A R T Y T H I R D
  • 7. 7@s1p @sam_brannen #JUnit5 #springone JUnit 5 = Platform + Jupiter + Vintage JUnit Platform • Foundation for launching testing frameworks on the JVM • Launcher and TestEngine APIs • ConsoleLauncher JUnit Jupiter • New programming model & extension model for JUnit 5 JUnit Vintage • TestEngine for running JUnit 3 & JUnit 4 based tests revolutionary evolutionary necessary
  • 8. 8@s1p @sam_brannen #JUnit5 #springone Third-party TestEngines Specsy Spek Cucumber Drools Scenario jqwik source: https://github.com/junit-team/junit5/wiki/Third-party-Extensions
  • 9. 9@s1p @sam_brannen #JUnit5 #springone Java Versions Baseline • AUTOMATIC-MODULE-NAME • Module descriptors (since 5.5) • module-path scanning Building and testing against 11, 12, 13, 14-ea
  • 10. 10@s1p @sam_brannen #JUnit5 #springone IDEs and Build Tools IntelliJ: since IDEA 2016.2+ Eclipse: since Eclipse Oxygen 4.7.1a+ VS Code: since March 2018 NetBeans: since Apache NetBeans 10.0 Gradle: official test task support since Gradle 4.6 Maven: official support since Maven Surefire 2.22.0 Ant: junitlauncher task since Ant 1.10.3 See user guide and sample apps for examples Or just go to start.spring.io
  • 11. 11@s1p @sam_brannen #JUnit5 #springone Releases Version Date 5.0.0 September 10th, 2017 … … 5.3.0 September 3rd, 2018 5.4.0 February 7th, 2019 5.5.0 June 30th, 2019 5.5.2 September 8th, 2019
  • 13. 13@s1p @sam_brannen #JUnit5 #springone In a Nutshell, JUnit Jupiter is … “The new programming model and extension model in JUnit 5” Programming Model • How you write tests • Annotations • Assertions • Assumptions • Types of tests Extension Model • How you and third parties extend the framework • Spring, Mockito, AssertJ, Selenium, …
  • 14. 14@s1p @sam_brannen #JUnit5 #springone More Powerful Programming Model What you can do with JUnit Jupiter that you can’t do with JUnit 4. Visibility • Everything does not have to be public Custom display names • @DisplayName: spaces, special characters, emoji 😱 • DisplayNameGenerator Tagging • @Tag replaces experimental @Category • Tag Expression Language
  • 16. 16@s1p @sam_brannen #JUnit5 #springone Example: CalculatorTests @DisplayName("Calculator Unit Tests") class CalculatorTests { private final Calculator calculator = new Calculator(); @Test @DisplayName("addition") void add() { assertEquals(5, calculator.add(2, 3), () -> "2 + 3 = " + (2 + 3)); } // ... }
  • 17. 17@s1p @sam_brannen #JUnit5 #springone Expected Exceptions @Test @DisplayName("n / 0 --> ArithmeticException") void divideByZero() { Exception exception = assertThrows(ArithmeticException.class, () -> calculator.divide(1, 0)); assertEquals("/ by zero", exception.getMessage()); }
  • 18. 18@s1p @sam_brannen #JUnit5 #springone Programmatic Timeouts @Test @DisplayName("Ensure Fibonacci computation is 'fast enough'") void fibonacci() { // assertTimeout(ofMillis(1000), // () -> calculator.fibonacci(30)); assertTimeoutPreemptively(ofMillis(1000), () -> calculator.fibonacci(30)); }
  • 19. 19@s1p @sam_brannen #JUnit5 #springone Even More Power and Expressiveness Meta-annotation support • Create your own custom composed annotations • Combine annotations from Spring and JUnit Conditional test execution Dependency injection for constructors and methods Lambda expressions and method references Interface default methods and testing traits @Nested test classes @RepeatedTest, @ParameterizedTest, @TestFactory @TestInstance lifecycle management
  • 21. 21@s1p @sam_brannen #JUnit5 #springone New Extension Model Extension • marker interface org.junit.jupiter.api.extension • package containing all extension APIs • implement as many as you like @ExtendWith(...) • used to register one or more extensions • interface, class, or method level o or as a meta-annotation @RegisterExtension • programmatic registration via fields
  • 22. 22@s1p @sam_brannen #JUnit5 #springone Extension APIs – Lifecycle Callbacks • BeforeAllCallback • BeforeEachCallback • BeforeTestExecutionCallback • AfterTestExecutionCallback • AfterEachCallback • AfterAllCallback Extensions wrap user-supplied lifecycle methods and test methods
  • 23. 23@s1p @sam_brannen #JUnit5 #springone Extension APIs – Exception Handling • TestExecutionExceptionHandler • @Test and @TestFactory methods • @RepeatedTest and @ParameterizedTest invocations • LifecycleMethodExecutionExceptionHandler (since 5.5) • @BeforeAll, @AfterAll, @BeforeEach, and @AfterEach methods
  • 24. 24@s1p @sam_brannen #JUnit5 #springone Extension APIs – Dependency Injection • TestInstanceFactory • TestInstancePostProcessor • ParameterResolver
  • 25. 25@s1p @sam_brannen #JUnit5 #springone Extension APIs – Miscellaneous • ExecutionCondition • @Disabled, @EnabledOnOs, @DisabledOnJre, … • InvocationInterceptor (since 5.5) • TestWatcher (since 5.4) • TestTemplateInvocationContextProvider • @TestTemplate, @RepeatedTest, @ParameterizedTest, …
  • 26. 26@s1p @sam_brannen #JUnit5 #springone Extension APIs – Discovery Phase • DisplayNameGenerator (since 5.4) • MethodOrderer (since 5.4)
  • 27. 27@s1p @sam_brannen #JUnit5 #springone InvocationInterceptor • API for intercepting constructor and method invocations • Test class constructor • @BeforeAll, @AfterAll, @BeforeEach, @AfterEach methods • @Test, @TestFactory, @TestTemplate methods • DynamicTest invocations • Can be used to execute user code in a separate thread • For example, to execute Swing code in the event dispatch thread (EDT)
  • 28. 28@s1p @sam_brannen #JUnit5 #springone TestWatcher • API for processing the results of test execution • Supported for @Test and @TestTemplate methods • Events fired: • disabled • aborted • succeeded • failed • Can be used for custom logging, reporting, conditional execution of subsequent tests, …
  • 29. 29@s1p @sam_brannen #JUnit5 #springone DisplayNameGenerator • SPI for generating custom display names for classes and methods • Configured via @DisplayNameGeneration • Implement your own • Or use a built-in implementation: • Standard: default behavior • ReplaceUnderscores: replaces underscores with spaces
  • 30. 30@s1p @sam_brannen #JUnit5 #springone MethodOrderer • API for controlling test method execution order • Configured via @TestMethodOrder • Implement your own • Or use a built-in implementation: • Alphanumeric: sorted alphanumerically • OrderAnnotation: sorted based on @Order • Random: pseudo-random ordering
  • 32. 32@s1p @sam_brannen #JUnit5 #springone New in JUnit 5.4 (1/2) • Discontinuation of the junit-platform-surefire-provider • New junit-jupiter dependency-aggregating artifact • LegacyXmlReportGeneratingListener • Test Kit for testing engines and extensions • null and empty argument sources for @ParameterizedTest methods • @TempDir support for temporary directories
  • 33. 33@s1p @sam_brannen #JUnit5 #springone New in JUnit 5.4 (2/2) • Custom display name generator API: DisplayNameGenerator • Ordering: @Test methods and @RegisterExtension fields • TestWatcher extension API • API for accessing outer test instances in ExtensionContext • Improved JUnit 4 migration support: Assumptions and @Ignore • Improved diagnostics and error reporting
  • 34. 34@s1p @sam_brannen #JUnit5 #springone Example: @TempDir @Test void writeItems(@TempDir Path tempDir) throws IOException { Path file = tempDir.resolve("test.txt"); new ListWriter(file).write("a", "b", "c"); assertEquals(singletonList("a,b,c"), Files.readAllLines(file)); }
  • 38. 38@s1p @sam_brannen #JUnit5 #springone Example: Test Kit @Test void verifyStats() { EngineTestKit.engine("junit-jupiter") .selectors(selectClass(ExampleTestCase.class)) .execute() .testEvents() .assertStatistics(stats -> stats .skipped(1) .started(3) .succeeded(1) .aborted(1) .failed(1)); }
  • 39. 39@s1p @sam_brannen #JUnit5 #springone New in JUnit 5.5 (1/2) • Global timeouts and @Timeout • @EnabledIf and @DisabledIf deprecated • @ValueSource supports boolean literal values • New emptyValue attribute in @CsvSource and @CsvFileSource • New junit.jupiter.displayname.generator.default config param to set default DisplayNameGenerator
  • 40. 40@s1p @sam_brannen #JUnit5 #springone New in JUnit 5.5 (2/2) • New InvocationInterceptor extension API • New LifecycleMethodExecutionExceptionHandler extension API • Configurable test discovery implementation for TestEngine authors • Explicit Java module descriptors
  • 45. 45@s1p @sam_brannen #JUnit5 #springone Coming in JUnit 5.6 (1/2) • @EnabledIf and @DisabledIf will be removed • Multi-character delimiters in @CsvSource and @CsvFileSource • Custom null values in @CsvSource and @CsvFileSource • Documented support for comments in CSV files loaded via @CsvFileSource • Auto-detection of enum type from method signature for @EnumSource • @EnabledForJreRange and @DisabledForJreRange • @Timeout disabled while in debug mode
  • 46. 46@s1p @sam_brannen #JUnit5 #springone Coming in JUnit 5.6 (2/2) • API to select and execute individual tests in inherited nested classes • New TestInstancePreDestroyCallback extension API • counterpart to TestInstancePostProcessor • New TypeBasedParameterResolver<T> abstract base class • generic adapter for the ParameterResolver API • simplifies parameter resolution of a specific type • Support for first/last order for extensions registered via @RegisterExtension • Significant performance improvements for the Vintage test engine
  • 47. 47@s1p @sam_brannen #JUnit5 #springone On the Horizon • Parameterized test classes • Custom ClassLoader • Declarative and programmatic test suites for the JUnit Platform • Scenario tests • Programmatic extension management • New XML / JSON reporting format • ...
  • 48. Spring and JUnit Jupiter
  • 49. 49@s1p @sam_brannen #JUnit5 #springone Spring Support for JUnit Jupiter • Fully integrated in Spring Framework 5.0! • Supports all Core Spring TestContext Framework features • Constructor and method injection via @Autowired, @Qualifier, @Value • Conditional test execution via SpEL expressions • ApplicationContext configuration annotations • Also works with Spring Framework 4.3 https://github.com/sbrannen/spring-test-junit5
  • 50. 50@s1p @sam_brannen #JUnit5 #springone Configuring JUnit Jupiter with Spring SpringExtension • @ExtendWith(SpringExtension.class) @SpringJUnitConfig • @ContextConfiguration + SpringExtension @SpringJUnitWebConfig • @SpringJUnitConfig + @WebAppConfiguration @EnabledIf / @DisabledIf • SpEL expression evaluation for conditional execution
  • 51. 51@s1p @sam_brannen #JUnit5 #springone Automatic Test Constructor Autowiring (5.2) By default, a test class constructor must be annotated with @Autowired The “default” can be changed • set spring.test.constructor.autowire.mode=all • JVM system property or SpringProperties mechanism @TestConstructor(autowireMode = ALL / ANNOTATED) • Overrides default on a per-class basis
  • 52. 52@s1p @sam_brannen #JUnit5 #springone What’s New in spring-test 5.2 https://github.com/spring-projects/spring-framework/wiki/What's-New-in-Spring-Framework-5.x#testing
  • 53. 53@s1p @sam_brannen #JUnit5 #springone Spring Boot 2.2 & JUnit Jupiter – Custom Config @Target(TYPE) @Retention(RUNTIME) // @ExtendWith(SpringExtension.class) @SpringBootTest @AutoConfigureMockMvc @Transactional public @interface SpringEventsWebTest { } @SpringBootTest + @AutoConfigureMockMvc + @ExtendWith(SpringExtension.class)
  • 54. 54@s1p @sam_brannen #JUnit5 #springone Spring Boot 2.2 & JUnit Jupiter – MockMvc Test @SpringEventsWebTest class EventsControllerTests { @Test @DisplayName("Home page should display more than 10 events") void listEvents(@Autowired MockMvc mockMvc) throws Exception { mockMvc.perform(get("/")) .andExpect(view().name("event/list")) .andExpect(model().attribute("events", hasSize(greaterThan(10)))); } } @SpringEventsWebTest + method-level DI + MockMvc
  • 55. 55@s1p @sam_brannen #JUnit5 #springone Tip: Upgrading JUnit 5 Version in Spring Boot Popular question… • https://stackoverflow.com/a/54605523/388980 Gradle: ext['junit-jupiter.version'] = '5.5.2' Maven: <properties> <junit-jupiter.version>5.5.2</junit-jupiter.version> </properties>
  • 57. 57@s1p @sam_brannen #JUnit5 #springone How can I help out? Participate on GitHub • Report issues • Suggest new features • Participate in discussions Answer questions on Stack Overflow and Gitter Support the JUnit Team with donations via Steady HQ https://steadyhq.com/en/junit
  • 59. 59@s1p @sam_brannen #JUnit5 #springone JUnit 5 Resources Project Homepage à http://junit.org/junit5 User Guide à http://junit.org/junit5/docs/current/user-guide Javadoc à http://junit.org/junit5/docs/current/api GitHub à https://github.com/junit-team Gitter à https://gitter.im/junit-team/junit5 Stack Overflow à http://stackoverflow.com/tags/junit5
  • 60. 60@s1p @sam_brannen #JUnit5 #springone Demos Used in this Presentation https://github.com/sbrannen/junit5-demo https://github.com/junit-team/junit5/tree/master/documentation/src/test
  • 61. Unless otherwise indicated, these slides are © 2013-2019 Pivotal Software, Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ Thank You! Sam Brannen @sam_brannen JUnit #springone@s1p