SlideShare a Scribd company logo
Migrating to
JUnit 5 (alpha)
JUnit 4 JUnit 5
import org.junit.Test;
public class JUnit4Test {
@Test
public void aJunit4TestCase() {
// write test here
}
}
import org.junit.gen5.api.Test;
class JUnit5Test {
@Test
void aJunit5TestCase() {
// write test here
}
}
public @interface Test {
Class<? extends Throwable>
expected() default None.class;
long timeout() default 0L;
}
JUnit 4 JUnit 5
public @interface Test {
}
public @interface Before {}
public @interface After {}
public @interface BeforeEach {}
public @interface AfterEach {}
public @interface BeforeClass {}
public @interface AfterClass {}
public @interface BeforeAll {}
public @interface AfterAll {}
public @interface Ignore {
String value() default "";
}
public @interface Disabled {
String value() default "";
}
class FunctionalAssertionsWithHamcrest {
@Test
void testProcedural() {
File file = new File("/some/property.file");
assertTrue(file.exists());
}
@Test
void testFunctional() {
File file = new File("/some/property.file");
assertTrue(file::exists);
}
@Test
void testFunctionalGrouped() {
File file = new File("/some/property.file");
assertAll(() -> file.canWrite(), () -> file.canRead());
}
}
class AssumptionsAndExceptions {
@Test
void testFullyConditional() {
File file = new File("/some/property.file");
assumeTrue(file.exists());
runSomeRoutineDependingOn(file);
}
@Test
void testPartlyConditional() {
File file = new File("/some/property.file");
assumingThat(file.exists()), () -> {
runSomeRoutineDependingOn(file);
});
}
@Test
void testThrowsExcption() {
IOException exception = expectThrows(IOException.class, () -> {
new File("?").getCanonicalPath();
});
validate(exception);
}
}
JUnit 4 JUnit 5
public class ATest {
@Test
public void foo() {}
}
public class BTest {
@Test
public void bar() {}
}
@RunWith(Suite.class)
@Suite.SuiteClasses({
ATest.class,
BTest.class
})
public class MySuite {}
@Tag(SuiteA.class)
public class ATest {
@Test
public void foo() {}
}
@Tags(
@Tag(SuiteA.class),
@Tag(SuiteB.class)
)
public class BTest {
@Test
public void bar() {}
}
JUnit 4 JUnit 5
public class ATest {
@Test
public void foo() {}
}
public class BTest {
@Test
public void bar() {}
}
@RunWith(Suite.class)
@Suite.SuiteClasses({
ATest.class,
BTest.class
})
public class MySuite {}
@Tag(SuiteA.class)
public class ATest {
@Test
public void foo() {}
}
@Tag(SuiteA.class)
@Tag(SuiteB.class)
@Retention(RUNTIME)
public @interface Meta {}
@Meta
public class BTest {
@Test
public void bar() {}
}
@DisplayName("A stack")
class TestingAStack {
Stack<Object> stack = new Stack<Object>();
@Test @DisplayName("is empty") void isEmpty() {
Assertions.assertTrue(stack.isEmpty());
}
@Nested @DisplayName("after pushing an element")
class AfterPushing {
String anElement = "an element";
@BeforeEach void init() {
stack.push(anElement);
}
@Test @DisplayName("it is no longer empty") void isEmpty() {
Assertions.assertFalse(stack.isEmpty());
}
@Test @DisplayName("returns the element when popped")
void returnElementWhenPopped() {
Assertions.assertEquals(anElement, stack.pop());
}
}
}
class DependencyInjection {
@Test
void testSelfAware(TestInfo testInfo) {
String name = testInfo.getName();
assertTrue("selfAwareTest", name);
}
}
public interface TestInfo {
String getName();
String getDisplayName();
Set<String> getTags();
}
class DependencyInjection {
@Test
void testSelfReport(TestReporter testReporter) {
long start = System.nanoTime();
doHeavyLifting();
testReporter.publishEntry("time", System.nanoTime() - start);
}
}
public interface TestReporter {
void publishEntry(String key, String value);
void publishEntry(Map<String, String> values);
}
JUnit 4 JUnit 5
public @interface Rule {
String value() default "";
}
public @interface RunWith {
Class<? extends Runner> value();
}
public @interface ExtendWith {
Class<? extends Extension>[]
value();
}
interface ContainerExecutionCondition {...}
interface TestExecutionCondition { ... }
interface BeforeAllExtensionPoint { ... }
interface BeforeEachExtensionPoint { ... }
interface InstancePostProcessor { ... }
interface MethodParameterResolver { ... }
interface ExceptionHandlerExtensionPoint { ... }
interface AfterEachExtensionPoint { ... }
interface AfterAllExtensionPoint { ... }
@ExtendWith(FooExtension.class)
class FunctionalAssertionsWithHamcrest {
@Test
void testProcedural(@Foo File file) {
assertTrue(file.exists());
}
}
@Retention(RUNTIME)
@interface Foo {}
class FooExtension implements MethodParameterResolver {
@Override public boolean supports(Parameter parameter,
MethodInvocationContext methodInvocationContext,
ExtensionContext extensionContext) {
return parameter.isAnnotationPresent(Foo.class);
}
@Override public Object resolve(Parameter parameter,
MethodInvocationContext methodInvocationContext,
ExtensionContext extensionContext){
return new File("some/file");
}
}
Currently still unsupported:
1. Parameterized tests (no test-runner equivalent)
2. No test-timeout
3. No sorting of test methods
JInit 5 is work-in-progress and the development has slowed
down significantly. Tickets for M1 are up-for-grab on GitHub!
http://rafael.codes
@rafaelcodes
http://documents4j.com
https://github.com/documents4j/documents4j
http://bytebuddy.net
https://github.com/raphw/byte-buddy

More Related Content

What's hot (20)

PPTX
TDD? Sure, but What About My Legacy Code?
Rob Myers
 
PDF
Lambda Functions in Java 8
Ganesh Samarthyam
 
PDF
Server1
FahriIrawan3
 
PPTX
Generating characterization tests for legacy code
Jonas Follesø
 
PDF
Java Fundamentals
Shalabh Chaudhary
 
PDF
Java 8 Lambda Built-in Functional Interfaces
Ganesh Samarthyam
 
PDF
Java programs
Mukund Gandrakota
 
PDF
Easy Going Groovy 2nd season on DevLOVE
Uehara Junji
 
PDF
GeeCON 2017 - TestContainers. Integration testing without the hassle
Anton Arhipov
 
PDF
Java Simple Programs
Upender Upr
 
PDF
Lab4
siragezeynu
 
ODP
Java Concurrency
Carol McDonald
 
ODP
Groovy Ast Transformations (greach)
HamletDRC
 
PDF
Software Testing - Invited Lecture at UNSW Sydney
julien.ponge
 
PDF
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
julien.ponge
 
PDF
Java 7 LavaJUG
julien.ponge
 
PPT
Exception Handling
Sunil OS
 
PDF
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
Uehara Junji
 
PDF
An introduction to Google test framework
Abner Chih Yi Huang
 
PPTX
Mockito intro
Jonathan Holloway
 
TDD? Sure, but What About My Legacy Code?
Rob Myers
 
Lambda Functions in Java 8
Ganesh Samarthyam
 
Server1
FahriIrawan3
 
Generating characterization tests for legacy code
Jonas Follesø
 
Java Fundamentals
Shalabh Chaudhary
 
Java 8 Lambda Built-in Functional Interfaces
Ganesh Samarthyam
 
Java programs
Mukund Gandrakota
 
Easy Going Groovy 2nd season on DevLOVE
Uehara Junji
 
GeeCON 2017 - TestContainers. Integration testing without the hassle
Anton Arhipov
 
Java Simple Programs
Upender Upr
 
Java Concurrency
Carol McDonald
 
Groovy Ast Transformations (greach)
HamletDRC
 
Software Testing - Invited Lecture at UNSW Sydney
julien.ponge
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
julien.ponge
 
Java 7 LavaJUG
julien.ponge
 
Exception Handling
Sunil OS
 
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
Uehara Junji
 
An introduction to Google test framework
Abner Chih Yi Huang
 
Mockito intro
Jonathan Holloway
 

Similar to Migrating to JUnit 5 (20)

PDF
JUnit 5
Scott Leberknight
 
PPT
3 j unit
kishoregali
 
PDF
Understanding JavaScript Testing
jeresig
 
PDF
Testing, Performance Analysis, and jQuery 1.4
jeresig
 
PPTX
Junit 5 - Maior e melhor
Tiago de Freitas Lima
 
PPT
Java Serialization
jeslie
 
PPTX
JUnit 5 - The Next Generation of JUnit - Ted's Tool Time
Ted Vinke
 
PDF
Implement the ADT stack by using an array stack to contain its entri.pdf
SIGMATAX1
 
KEY
Unittesting JavaScript with Evidence
Tobie Langel
 
PDF
Please review my code (java)Someone helped me with it but i cannot.pdf
fathimafancyjeweller
 
PDF
Having a problem figuring out where my errors are- The code is not run.pdf
NicholasflqStewartl
 
PDF
Description (Part A) In this lab you will write a Queue implementati.pdf
rishabjain5053
 
KEY
How to Start Test-Driven Development in Legacy Code
Daniel Wellman
 
DOCX
EmptyCollectionException-java -- - Represents the situation in which.docx
BlakeSGMHemmingss
 
PPT
Java Generics
jeslie
 
PPTX
Java Programs
vvpadhu
 
PDF
Kotlin, 어떻게 동작하나요
Chang W. Doh
 
DOCX
VISUALIZAR REGISTROS EN UN JTABLE
Darwin Durand
 
3 j unit
kishoregali
 
Understanding JavaScript Testing
jeresig
 
Testing, Performance Analysis, and jQuery 1.4
jeresig
 
Junit 5 - Maior e melhor
Tiago de Freitas Lima
 
Java Serialization
jeslie
 
JUnit 5 - The Next Generation of JUnit - Ted's Tool Time
Ted Vinke
 
Implement the ADT stack by using an array stack to contain its entri.pdf
SIGMATAX1
 
Unittesting JavaScript with Evidence
Tobie Langel
 
Please review my code (java)Someone helped me with it but i cannot.pdf
fathimafancyjeweller
 
Having a problem figuring out where my errors are- The code is not run.pdf
NicholasflqStewartl
 
Description (Part A) In this lab you will write a Queue implementati.pdf
rishabjain5053
 
How to Start Test-Driven Development in Legacy Code
Daniel Wellman
 
EmptyCollectionException-java -- - Represents the situation in which.docx
BlakeSGMHemmingss
 
Java Generics
jeslie
 
Java Programs
vvpadhu
 
Kotlin, 어떻게 동작하나요
Chang W. Doh
 
VISUALIZAR REGISTROS EN UN JTABLE
Darwin Durand
 
Ad

More from Rafael Winterhalter (12)

PPTX
Java and OpenJDK: disecting the ecosystem
Rafael Winterhalter
 
PPTX
The definitive guide to java agents
Rafael Winterhalter
 
PPTX
Event-Sourcing Microservices on the JVM
Rafael Winterhalter
 
PPTX
Java 10, Java 11 and beyond
Rafael Winterhalter
 
PPTX
Getting started with Java 9 modules
Rafael Winterhalter
 
PPTX
Monitoring distributed (micro-)services
Rafael Winterhalter
 
PPTX
An Overview of Project Jigsaw
Rafael Winterhalter
 
PPTX
The Java memory model made easy
Rafael Winterhalter
 
PPTX
An introduction to JVM performance
Rafael Winterhalter
 
PPTX
Java byte code in practice
Rafael Winterhalter
 
PPTX
Making Java more dynamic: runtime code generation for the JVM
Rafael Winterhalter
 
PPTX
A topology of memory leaks on the JVM
Rafael Winterhalter
 
Java and OpenJDK: disecting the ecosystem
Rafael Winterhalter
 
The definitive guide to java agents
Rafael Winterhalter
 
Event-Sourcing Microservices on the JVM
Rafael Winterhalter
 
Java 10, Java 11 and beyond
Rafael Winterhalter
 
Getting started with Java 9 modules
Rafael Winterhalter
 
Monitoring distributed (micro-)services
Rafael Winterhalter
 
An Overview of Project Jigsaw
Rafael Winterhalter
 
The Java memory model made easy
Rafael Winterhalter
 
An introduction to JVM performance
Rafael Winterhalter
 
Java byte code in practice
Rafael Winterhalter
 
Making Java more dynamic: runtime code generation for the JVM
Rafael Winterhalter
 
A topology of memory leaks on the JVM
Rafael Winterhalter
 
Ad

Recently uploaded (20)

PDF
Predicting the unpredictable: re-engineering recommendation algorithms for fr...
Speck&Tech
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PPTX
MSP360 Backup Scheduling and Retention Best Practices.pptx
MSP360
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
Wojciech Ciemski for Top Cyber News MAGAZINE. June 2025
Dr. Ludmila Morozova-Buss
 
PDF
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
PDF
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
Human-centred design in online workplace learning and relationship to engagem...
Tracy Tang
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PDF
Why Orbit Edge Tech is a Top Next JS Development Company in 2025
mahendraalaska08
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
Smart Air Quality Monitoring with Serrax AQM190 LITE
SERRAX TECHNOLOGIES LLP
 
PPTX
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
TrustArc Webinar - Data Privacy Trends 2025: Mid-Year Insights & Program Stra...
TrustArc
 
Predicting the unpredictable: re-engineering recommendation algorithms for fr...
Speck&Tech
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
MSP360 Backup Scheduling and Retention Best Practices.pptx
MSP360
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
Wojciech Ciemski for Top Cyber News MAGAZINE. June 2025
Dr. Ludmila Morozova-Buss
 
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Human-centred design in online workplace learning and relationship to engagem...
Tracy Tang
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
Why Orbit Edge Tech is a Top Next JS Development Company in 2025
mahendraalaska08
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
Smart Air Quality Monitoring with Serrax AQM190 LITE
SERRAX TECHNOLOGIES LLP
 
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
TrustArc Webinar - Data Privacy Trends 2025: Mid-Year Insights & Program Stra...
TrustArc
 

Migrating to JUnit 5

  • 2. JUnit 4 JUnit 5 import org.junit.Test; public class JUnit4Test { @Test public void aJunit4TestCase() { // write test here } } import org.junit.gen5.api.Test; class JUnit5Test { @Test void aJunit5TestCase() { // write test here } }
  • 3. public @interface Test { Class<? extends Throwable> expected() default None.class; long timeout() default 0L; } JUnit 4 JUnit 5 public @interface Test { } public @interface Before {} public @interface After {} public @interface BeforeEach {} public @interface AfterEach {} public @interface BeforeClass {} public @interface AfterClass {} public @interface BeforeAll {} public @interface AfterAll {} public @interface Ignore { String value() default ""; } public @interface Disabled { String value() default ""; }
  • 4. class FunctionalAssertionsWithHamcrest { @Test void testProcedural() { File file = new File("/some/property.file"); assertTrue(file.exists()); } @Test void testFunctional() { File file = new File("/some/property.file"); assertTrue(file::exists); } @Test void testFunctionalGrouped() { File file = new File("/some/property.file"); assertAll(() -> file.canWrite(), () -> file.canRead()); } }
  • 5. class AssumptionsAndExceptions { @Test void testFullyConditional() { File file = new File("/some/property.file"); assumeTrue(file.exists()); runSomeRoutineDependingOn(file); } @Test void testPartlyConditional() { File file = new File("/some/property.file"); assumingThat(file.exists()), () -> { runSomeRoutineDependingOn(file); }); } @Test void testThrowsExcption() { IOException exception = expectThrows(IOException.class, () -> { new File("?").getCanonicalPath(); }); validate(exception); } }
  • 6. JUnit 4 JUnit 5 public class ATest { @Test public void foo() {} } public class BTest { @Test public void bar() {} } @RunWith(Suite.class) @Suite.SuiteClasses({ ATest.class, BTest.class }) public class MySuite {} @Tag(SuiteA.class) public class ATest { @Test public void foo() {} } @Tags( @Tag(SuiteA.class), @Tag(SuiteB.class) ) public class BTest { @Test public void bar() {} }
  • 7. JUnit 4 JUnit 5 public class ATest { @Test public void foo() {} } public class BTest { @Test public void bar() {} } @RunWith(Suite.class) @Suite.SuiteClasses({ ATest.class, BTest.class }) public class MySuite {} @Tag(SuiteA.class) public class ATest { @Test public void foo() {} } @Tag(SuiteA.class) @Tag(SuiteB.class) @Retention(RUNTIME) public @interface Meta {} @Meta public class BTest { @Test public void bar() {} }
  • 8. @DisplayName("A stack") class TestingAStack { Stack<Object> stack = new Stack<Object>(); @Test @DisplayName("is empty") void isEmpty() { Assertions.assertTrue(stack.isEmpty()); } @Nested @DisplayName("after pushing an element") class AfterPushing { String anElement = "an element"; @BeforeEach void init() { stack.push(anElement); } @Test @DisplayName("it is no longer empty") void isEmpty() { Assertions.assertFalse(stack.isEmpty()); } @Test @DisplayName("returns the element when popped") void returnElementWhenPopped() { Assertions.assertEquals(anElement, stack.pop()); } } }
  • 9. class DependencyInjection { @Test void testSelfAware(TestInfo testInfo) { String name = testInfo.getName(); assertTrue("selfAwareTest", name); } } public interface TestInfo { String getName(); String getDisplayName(); Set<String> getTags(); }
  • 10. class DependencyInjection { @Test void testSelfReport(TestReporter testReporter) { long start = System.nanoTime(); doHeavyLifting(); testReporter.publishEntry("time", System.nanoTime() - start); } } public interface TestReporter { void publishEntry(String key, String value); void publishEntry(Map<String, String> values); }
  • 11. JUnit 4 JUnit 5 public @interface Rule { String value() default ""; } public @interface RunWith { Class<? extends Runner> value(); } public @interface ExtendWith { Class<? extends Extension>[] value(); } interface ContainerExecutionCondition {...} interface TestExecutionCondition { ... } interface BeforeAllExtensionPoint { ... } interface BeforeEachExtensionPoint { ... } interface InstancePostProcessor { ... } interface MethodParameterResolver { ... } interface ExceptionHandlerExtensionPoint { ... } interface AfterEachExtensionPoint { ... } interface AfterAllExtensionPoint { ... }
  • 12. @ExtendWith(FooExtension.class) class FunctionalAssertionsWithHamcrest { @Test void testProcedural(@Foo File file) { assertTrue(file.exists()); } } @Retention(RUNTIME) @interface Foo {} class FooExtension implements MethodParameterResolver { @Override public boolean supports(Parameter parameter, MethodInvocationContext methodInvocationContext, ExtensionContext extensionContext) { return parameter.isAnnotationPresent(Foo.class); } @Override public Object resolve(Parameter parameter, MethodInvocationContext methodInvocationContext, ExtensionContext extensionContext){ return new File("some/file"); } }
  • 13. Currently still unsupported: 1. Parameterized tests (no test-runner equivalent) 2. No test-timeout 3. No sorting of test methods JInit 5 is work-in-progress and the development has slowed down significantly. Tickets for M1 are up-for-grab on GitHub!