SlideShare a Scribd company logo
1 of 52
JUnit 5
JUnit 5
=
JUnit Platform
+
JUnit Jupiter
+
JUnit Vintage
➔ JUnit Platform: É o responsável pela descoberta e execução de testes na
JVM, definindo a relação entre os testes e plataforma de execução (IDEs,
console, ferramentas de build). Esse módulo também expõe a interface
TestEngine, que define o contrato de execução de qualquer ferramenta de
testes sobre a plataforma do JUnit.
➔ JUnit Jupiter: Este módulo contém os novos recursos para construção de
testes usando o JUnit, e fornece uma implementação de TestEngine para
execução dos testes escritos com o JUnit Jupiter.
➔ JUnit Vintage: Fornece um TestEngine para execução de testes escritos em
JUnit 3 e 4.
JUnit Jupiter
import org.junit.jupiter.api.Test;
import static
org.junit.jupiter.api.Assertions.assertEquals;
public class Sample1 {
@Test
public void myFirstJUnit5Test() {
assertEquals(2, 1 + 1);
}
}
public class Sample2 {
@SlowTest
public void testWithMyAnnotation() {
assertEquals(2, verySlowComputation());
}
}
@Test
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface SlowTest {
}
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
public class Sample3 {
@BeforeAll
public static void beforeAll() {
System.out.println("Hello, i'm running 'before all'");
}
@BeforeEach
public void beforeEach() {
System.out.println("Hello, i'm running 'before each'");
}
@Test
public void sample() {
System.out.println("Hello, i'm a test!");
}
}
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.AfterAll;
public class Sample3 {
@Test
public void sample() {
System.out.println("Hello, i'm a test!");
}
@AfterEach
public void afterEach() {
System.out.println("Hello, i'm running 'after each'");
}
@AfterAll
public static void afterAll() {
System.out.println("Hello, i'm running 'after all'");
}
}
import org.junit.jupiter.api.TestInstance;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
//@TestInstance(TestInstance.Lifecycle.PER_METHOD)
public class Sample4 {
@Test
public void sample() {
System.out.println("Hello, i'm a test!, on instance " +
this);
}
@Test
public void sample2() {
System.out.println("Hello, i'm a another test!, on instance "
+ this);
}
}
import org.junit.jupiter.api.DisplayName;
public class Sample5 {
@Test
@DisplayName("The sum (1 + 1) must be 2")
public void testWithDisplayName() {
assertEquals(2, 1 + 1);
}
@Test
@DisplayName("The sum (1 + 1) must be 2, with emoji 😃!")
public void testWithDisplayName2() {
assertEquals(2, 1 + 1);
}
}
@DisplayName - output
Assertions
import static org.junit.jupiter.api.Assertions.assertEquals;
public class Sample6 {
@Test
public void sample() {
assertEquals(2, 1 + 1, “The sum (1 + 1) must be 2”);
}
@Test
public void sample2() {
assertEquals(2, 1 + 1, () -> “The sum (1 + 1) must be
2”);
}
}
Assertions
assertAll
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
import static org.junit.jupiter.api.Assertions.assertAll;
public class Sample7 {
@Test
public void sample() {
Person person = new Person("Tiago de Freitas Lima", 20);
assertAll(
() -> assertEquals("Tiago Lima", person.name),
() -> assertEquals(32, person.age));
}
@Test
public void sample2() {
Person person = new Person("Tiago de Freitas Lima", 20);
assertAll("Something is wrong...",
() -> assertEquals("Tiago Lima", person.name),
() -> assertEquals(32, person.age));
}
}
Expected :Tiago Lima
Actual :Tiago de Freitas Lima
Expected :32
Actual :20
org.opentest4j.MultipleFailuresError:
Multiple Failures (2 failures)
expected: <Tiago Lima> but was: <Tiago de
Freitas Lima>
expected: <32> but was: <20>
Assertions
exceptions
class MyObject {
void dangerous(String arg) {
throw new
IllegalArgumentException("Invalid argument:
" + arg);
}
void safe() {
}
}
import static org.junit.jupiter.api.Assertions.assertThrows;
public class Sample8 {
@Test
public void sample() {
MyObject myObject = new MyObject();
assertThrows(IllegalArgumentException.class, () ->
myObject.dangerous("bla"));
}
@Test
public void sample2() {
MyObject myObject = new MyObject();
assertThrows(IllegalStateException.class, () ->
myObject.dangerous("bla"));
}
}
import static org.junit.jupiter.api.Assertions.assertThrows;
public class Sample8 {
@Test
public void sample3() {
MyObject myObject = new MyObject();
assertThrows(IllegalStateException.class, myObject::safe);
}
@Test
public void sample4() {
MyObject myObject = new MyObject();
IllegalArgumentException exception =
assertThrows(IllegalArgumentException.class,
() -> myObject.dangerous("bla"));
assertEquals("Invalid argument: bla", exception.getMessage());
}
}
Assertions
timeouts
class MyObject {
String slow() {
//...very slow…
return “”;
}
}
import static org.junit.jupiter.api.Assertions.assertTimeout;
public class Sample9 {
@Test
public void sample() {
MyObject myObject = new MyObject();
assertTimeout(Duration.ofMillis(2000), myObject::slow);
}
@Test
public void sample2() {
MyObject myObject = new MyObject();
String output = assertTimeout(Duration.ofMillis(2000), myObject::slow);
assertEquals("slow...", output);
}
}
import static
org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
public class Sample9 {
@Test
public void sample3() {
MyObject myObject = new MyObject();
assertTimeoutPreemptively(Duration.ofMillis(2000),
myObject::slow);
}
}
Parameterized Tests
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>5.0.0</version>
<scope>test</scope>
</dependency>
import org.junit.jupiter.params.ParameterizedTest;
import
org.junit.jupiter.params.provider.ValueSource;
public class Sample10 {
@ParameterizedTest
@ValueSource(strings = { "Hello", "World" })
public void parameterizedTest(String argument) {
assertNotNull(argument);
}
}
import
org.junit.jupiter.params.ParameterizedTest;
import
org.junit.jupiter.params.provider.EnumSource;
public class Sample11 {
@ParameterizedTest
@EnumSource(TimeUnit.class)
public void parameterizedTest(TimeUnit
timeUnit) {
assertNotNull(timeUnit);
}
}
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
public class Sample12 {
@ParameterizedTest
@MethodSource("parameterFactory")
public void parameterizedTest(String argument) {
assertNotNull(argument);
}
static Collection<String> parameterFactory() {
return Arrays.asList("Hello", "World");
}
}
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
public class Sample13 {
@ParameterizedTest
@MethodSource("parameterFactory")
public void parameterizedTest(String argument, int count) {
assertNotNull(argument);
assertTrue(count > 0);
}
static Collection<Arguments> parameterFactory() {
return Arrays.asList(Arguments.of("Hello", 1),
Arguments.of("World", 1));
}
}
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
public class Sample14 {
@ParameterizedTest
@CsvSource({ "Hello, 1", "World, 2"})
public void parameterizedTest(String argument,
int count) {
assertNotNull(argument);
assertTrue(count > 0);
}
}
import org.junit.jupiter.params.ParameterizedTest;
import
org.junit.jupiter.params.provider.CsvFileSource;
public class Sample15 {
@ParameterizedTest
@CsvFileSource(resources = "/parameters.csv")
public void parameterizedTest(String argument,
int count) {
assertNotNull(argument);
assertTrue(count > 0);
}
}
Parameterized Tests
custom argument
provider
import org.junit.jupiter.params.ParameterizedTest;
import
org.junit.jupiter.params.provider.ArgumentsSource;
public class Sample16 {
@ParameterizedTest
@ArgumentsSource(CustomArgumentProvider.class)
public void parameterizedTest(String argument, int
count) {
assertNotNull(argument);
assertTrue(count > 0);
}
}
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.ArgumentsProvider;
class CustomArgumentProvider implements ArgumentsProvider {
@Override
public Stream<? extends Arguments>
provideArguments(ExtensionContext context) throws Exception {
return Stream.of(Arguments.of("Hello", 1),
Arguments.of("World", 1));
}
}
import org.junit.jupiter.params.ParameterizedTest;
public class Sample17 {
@ParameterizedTest
@ExcelSource(file = "test.xls")
public void parameterizedTest(String argument) {
assertNotNull(argument);
}
}
import org.junit.jupiter.params.provider.ArgumentsSource;
@ArgumentsSource(ExcelArgumentProvider.class)
@interface ExcelSource {
String file();
}
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.ArgumentsProvider;
import org.junit.jupiter.params.support.AnnotationConsumer;
class ExcelArgumentProvider implements ArgumentsProvider,
AnnotationConsumer<ExcelSource> {
private String fileName;
@Override
public void accept(ExcelSource excelSource) {
this.fileName = excelSource.file();
}
@Override
public Stream<? extends Arguments> provideArguments(ExtensionContext
context) throws Exception {
return Stream.empty();
}
}
Nested Tests
public class Sample18 {
private Stack<String> stack;
@Test
@DisplayName("is instantiated with new Stack()")
void isInstantiatedWithNew() {
new Stack<>();
}
@Nested
@DisplayName("when new")
class WhenNew {
@BeforeEach
void createNewStack() {
stack = new Stack<>();
}
...
@Test
@DisplayName("is empty")
void isEmpty() {
assertTrue(stack.isEmpty());
}
@Test
@DisplayName("throws EmptyStackException when popped")
void throwsExceptionWhenPopped() {
assertThrows(EmptyStackException.class, () -> stack.pop());
}
@Nested
@DisplayName("after pushing an element")
class AfterPushing {
String anElement = "an element";
@BeforeEach
void pushAnElement() {
stack.push(anElement);
}
...
...
@Test
@DisplayName("it is no longer empty")
void isNotEmpty() {
assertFalse(stack.isEmpty());
}
@Test
@DisplayName("returns the element when popped and is empty")
void returnElementWhenPopped() {
assertEquals(anElement, stack.pop());
assertTrue(stack.isEmpty());
}
@Test
@DisplayName("returns the element when peeked but remains not empty")
void returnElementWhenPeeked() {
assertEquals(anElement, stack.peek());
assertFalse(stack.isEmpty());
}
}
}
}
Nested tests - output
Test interfaces
public interface Testable<T> {
T createValue();
}
public interface EqualsContract<T> extends Testable<T> {
T createNotEqualValue();
@Test
default void valueEqualsItself() {
T value = createValue();
assertEquals(value, value);
}
@Test
default void valueDoesNotEqualNull() {
T value = createValue();
assertFalse(value.equals(null));
}
@Test
default void valueDoesNotEqualDifferentValue() {
T value = createValue();
T differentValue = createNotEqualValue();
assertNotEquals(value, differentValue);
assertNotEquals(differentValue, value);
}
}
public class Sample20 implements EqualsContract<String> {
@Override
public String createValue() {
return "Hello";
}
@Override
public String createNotEqualValue() {
return "World";
}
}
Tags
import org.junit.jupiter.api.Tag;
public class Sample21 {
@Test
@Tag("slow")
@Tag("whatever")
public void sample() {
assertNotNull("...");
}
}
O que mais?
https://engenharia.elo7.com.br/novidades-do-junit-5-parte-1/
https://engenharia.elo7.com.br/novidades-do-junit-5-parte-2/
Obrigado!
github.com/ljtfreitas/junit-5-samples

More Related Content

What's hot

Testing Android apps based on Dagger and RxJava Droidcon UK
Testing Android apps based on Dagger and RxJava Droidcon UKTesting Android apps based on Dagger and RxJava Droidcon UK
Testing Android apps based on Dagger and RxJava Droidcon UKFabio Collini
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good TestsTomek Kaczanowski
 
OSGi and Eclipse RCP
OSGi and Eclipse RCPOSGi and Eclipse RCP
OSGi and Eclipse RCPEric Jain
 
GeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassleGeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassleAnton Arhipov
 
The uniform interface is 42
The uniform interface is 42The uniform interface is 42
The uniform interface is 42Yevhen Bobrov
 
Demystifying dependency Injection: Dagger and Toothpick
Demystifying dependency Injection: Dagger and ToothpickDemystifying dependency Injection: Dagger and Toothpick
Demystifying dependency Injection: Dagger and ToothpickDanny Preussler
 
T.Y.B.S.CS Advance Java Practicals Sem 5 Mumbai University
T.Y.B.S.CS Advance Java Practicals Sem 5 Mumbai UniversityT.Y.B.S.CS Advance Java Practicals Sem 5 Mumbai University
T.Y.B.S.CS Advance Java Practicals Sem 5 Mumbai UniversityNiraj Bharambe
 
Testing Android apps based on Dagger and RxJava
Testing Android apps based on Dagger and RxJavaTesting Android apps based on Dagger and RxJava
Testing Android apps based on Dagger and RxJavaFabio Collini
 
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloadingRiga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloadingAnton Arhipov
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockRobot Media
 
Easy REST APIs with Jersey and RestyGWT
Easy REST APIs with Jersey and RestyGWTEasy REST APIs with Jersey and RestyGWT
Easy REST APIs with Jersey and RestyGWTDavid Chandler
 
The Ring programming language version 1.5 book - Part 12 of 31
The Ring programming language version 1.5 book - Part 12 of 31The Ring programming language version 1.5 book - Part 12 of 31
The Ring programming language version 1.5 book - Part 12 of 31Mahmoud Samir Fayed
 
Pragmatic unittestingwithj unit
Pragmatic unittestingwithj unitPragmatic unittestingwithj unit
Pragmatic unittestingwithj unitliminescence
 
Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptRyan Anklam
 
Tomasz Polanski - Automated mobile testing 2016 - Testing: why, when, how
Tomasz Polanski - Automated mobile testing 2016 - Testing: why, when, howTomasz Polanski - Automated mobile testing 2016 - Testing: why, when, how
Tomasz Polanski - Automated mobile testing 2016 - Testing: why, when, howTomasz Polanski
 
JEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistJEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistAnton Arhipov
 
Making the most of your gradle build - Gr8Conf 2017
Making the most of your gradle build - Gr8Conf 2017Making the most of your gradle build - Gr8Conf 2017
Making the most of your gradle build - Gr8Conf 2017Andres Almiray
 
Making the most of your gradle build - Greach 2017
Making the most of your gradle build - Greach 2017Making the most of your gradle build - Greach 2017
Making the most of your gradle build - Greach 2017Andres Almiray
 

What's hot (20)

Agile Swift
Agile SwiftAgile Swift
Agile Swift
 
Testing Android apps based on Dagger and RxJava Droidcon UK
Testing Android apps based on Dagger and RxJava Droidcon UKTesting Android apps based on Dagger and RxJava Droidcon UK
Testing Android apps based on Dagger and RxJava Droidcon UK
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
OSGi and Eclipse RCP
OSGi and Eclipse RCPOSGi and Eclipse RCP
OSGi and Eclipse RCP
 
GeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassleGeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassle
 
The uniform interface is 42
The uniform interface is 42The uniform interface is 42
The uniform interface is 42
 
Demystifying dependency Injection: Dagger and Toothpick
Demystifying dependency Injection: Dagger and ToothpickDemystifying dependency Injection: Dagger and Toothpick
Demystifying dependency Injection: Dagger and Toothpick
 
T.Y.B.S.CS Advance Java Practicals Sem 5 Mumbai University
T.Y.B.S.CS Advance Java Practicals Sem 5 Mumbai UniversityT.Y.B.S.CS Advance Java Practicals Sem 5 Mumbai University
T.Y.B.S.CS Advance Java Practicals Sem 5 Mumbai University
 
Testing Android apps based on Dagger and RxJava
Testing Android apps based on Dagger and RxJavaTesting Android apps based on Dagger and RxJava
Testing Android apps based on Dagger and RxJava
 
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloadingRiga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloading
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
 
Easy REST APIs with Jersey and RestyGWT
Easy REST APIs with Jersey and RestyGWTEasy REST APIs with Jersey and RestyGWT
Easy REST APIs with Jersey and RestyGWT
 
The Ring programming language version 1.5 book - Part 12 of 31
The Ring programming language version 1.5 book - Part 12 of 31The Ring programming language version 1.5 book - Part 12 of 31
The Ring programming language version 1.5 book - Part 12 of 31
 
Pragmatic unittestingwithj unit
Pragmatic unittestingwithj unitPragmatic unittestingwithj unit
Pragmatic unittestingwithj unit
 
Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScript
 
Tomasz Polanski - Automated mobile testing 2016 - Testing: why, when, how
Tomasz Polanski - Automated mobile testing 2016 - Testing: why, when, howTomasz Polanski - Automated mobile testing 2016 - Testing: why, when, how
Tomasz Polanski - Automated mobile testing 2016 - Testing: why, when, how
 
JEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistJEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with Javassist
 
Making the most of your gradle build - Gr8Conf 2017
Making the most of your gradle build - Gr8Conf 2017Making the most of your gradle build - Gr8Conf 2017
Making the most of your gradle build - Gr8Conf 2017
 
Making the most of your gradle build - Greach 2017
Making the most of your gradle build - Greach 2017Making the most of your gradle build - Greach 2017
Making the most of your gradle build - Greach 2017
 
Unit testing with mock libs
Unit testing with mock libsUnit testing with mock libs
Unit testing with mock libs
 

Similar to Junit 5 - Maior e melhor

Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developersAnton Udovychenko
 
Android testing
Android testingAndroid testing
Android testingSean Tsai
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testingjeresig
 
JUnit 5 - The Next Generation of JUnit - Ted's Tool Time
JUnit 5 - The Next Generation of JUnit - Ted's Tool TimeJUnit 5 - The Next Generation of JUnit - Ted's Tool Time
JUnit 5 - The Next Generation of JUnit - Ted's Tool TimeTed Vinke
 
JUnit5 and TestContainers
JUnit5 and TestContainersJUnit5 and TestContainers
JUnit5 and TestContainersSunghyouk Bae
 
Unit Testing - Nakov's Talk @ VarnaConf 2013
Unit Testing - Nakov's Talk @ VarnaConf 2013Unit Testing - Nakov's Talk @ VarnaConf 2013
Unit Testing - Nakov's Talk @ VarnaConf 2013Svetlin Nakov
 
Unit testing by Svetlin Nakov
Unit testing by Svetlin NakovUnit testing by Svetlin Nakov
Unit testing by Svetlin Nakovit-tour
 
Confitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good TestsConfitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good TestsTomek Kaczanowski
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
GeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good TestsGeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good TestsTomek Kaczanowski
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good TestsTomek Kaczanowski
 

Similar to Junit 5 - Maior e melhor (20)

Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developers
 
Android testing
Android testingAndroid testing
Android testing
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
 
JUnit 5 - The Next Generation of JUnit - Ted's Tool Time
JUnit 5 - The Next Generation of JUnit - Ted's Tool TimeJUnit 5 - The Next Generation of JUnit - Ted's Tool Time
JUnit 5 - The Next Generation of JUnit - Ted's Tool Time
 
3 j unit
3 j unit3 j unit
3 j unit
 
Junit With Eclipse
Junit With EclipseJunit With Eclipse
Junit With Eclipse
 
JUnit5 and TestContainers
JUnit5 and TestContainersJUnit5 and TestContainers
JUnit5 and TestContainers
 
Junit and testNG
Junit and testNGJunit and testNG
Junit and testNG
 
Unit Testing - Nakov's Talk @ VarnaConf 2013
Unit Testing - Nakov's Talk @ VarnaConf 2013Unit Testing - Nakov's Talk @ VarnaConf 2013
Unit Testing - Nakov's Talk @ VarnaConf 2013
 
Unit testing by Svetlin Nakov
Unit testing by Svetlin NakovUnit testing by Svetlin Nakov
Unit testing by Svetlin Nakov
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 
TestNG vs Junit
TestNG vs JunitTestNG vs Junit
TestNG vs Junit
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Test Time Bombs
Test Time BombsTest Time Bombs
Test Time Bombs
 
JUnit
JUnitJUnit
JUnit
 
Confitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good TestsConfitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good Tests
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
GeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good TestsGeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good Tests
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 

Recently uploaded

ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 

Recently uploaded (20)

ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 

Junit 5 - Maior e melhor

Editor's Notes

  1. Apresentação geral do Junit5
  2. JUnit dividido em projetos com conceitos diferentes: Platform (descoberta e execução de testes), Jupiter (construção de testes), Vintage (compatibilidade com versões anteriores para execução no JUnit Platform)
  3. Explicação geral dos três níveis da arquitetura
  4. JUnit Jupiter = construção de testes. Exemplos a seguir.
  5. Exemplo básico - destacar: o pacote org.junit.jupiter não confilta com as versões anteriores. Classe Assert substituída por Assertions
  6. Uso de meta anotações (anotações marcadas com Test)
  7. BeforeAll - antiga BeforeClass BeforeEach - antiga Before
  8. AfterAll - antiga AfterClass AfterEach - antiga After
  9. Comentar sobre isolamento - cada teste em uma instância da classe. Possibilidade de alterar esse comportamento usando @TestInstance
  10. @DisplayName - saída no output
  11. Output no Intelij
  12. JUnit Jupiter = construção de testes. Exemplos a seguir.
  13. Comentar sobre o último parâmetro - mensagem exibida em caso de erro. No segundo exemplo a mensagem é fornecida por um Supplier Comentar que outros métodos continuam existindo (assertNotEquals, assertSame, assertTrue, etc)
  14. assertAll - encapsula vários asserts em um único teste
  15. Mensagem de erro do assertAll
  16. Testes de exceptions - comentar sobre como são feitos no Junit 4 (parametro expected da anotação Test, rule ExpectedException ou try/catch)
  17. Exemplo básico - destacar: o pacote org.junit.jupiter não confilta com as versões anteriores. Classe Assert substituída por Assertions
  18. assertThrows O segundo exemplo captura a exception lançada para validação
  19. Testes de timeouts - comentar sobre como são feitos no Junit 4 (parametro timeout da anotação Test, rule Timeout)
  20. Exemplo básico - destacar: o pacote org.junit.jupiter não confilta com as versões anteriores. Classe Assert substituída por Assertions
  21. assertTimeout. Executado na mesma thread O segundo exemplo captura o retorno do método para validação. O parametro é um ThrowingSupplier
  22. assertTimeoutPreemptively. Executado em outra thread
  23. Testes parametrizados. Explicar a motivação e como são feitos no Junit 4 (array bidimensional com parametros injetados via construtor)
  24. artefato necessário
  25. @ParameterizedTest ao inves de @Test @ValueSource - parameter provider do teste. Parametros fixos
  26. @EnumSource - teste executado para cada elemento do enum
  27. @MethodSource - método fornecedor de parametros. O retorno deve ser uma Collection, array ou Stream. Esse exemplo utiliza apenas um parâmetro por teste.
  28. @MethodSource - Esse exemplo utiliza multiplos parâmetro por teste, retornando uma coleção de Arguments
  29. @CvsSource - parâmetros no formato CSV (separados por vírgula)
  30. @CvsFileSource - permite informar um arquivo csv
  31. Argument providers customizados
  32. @ArgumentSource usando um CustomArgumentProvider
  33. CustomArgumentProvider - implements ArgumentsProvider
  34. custom annotation
  35. anotação deve estar anotada com @ArgumentsSource
  36. Também implementa AnnotationConsumer, que permite acesso a meta anotacao que encapsula o ArgumentProvider
  37. Testes aninhados - relação de dependencia e hierarquia
  38. Exemplo retirado da documentação - testes da classe Stack em varios cenarios
  39. Output no Intelij
  40. Testes utilizando default methods de interfaces
  41. Exemplo retirado da documentação
  42. Exemplo retirado da documentação
  43. Implementação da interface no teste - template method
  44. Tags em testes - utilizados para filtros