SlideShare uma empresa Scribd logo
1 de 42
Baixar para ler offline
Sam Brannen
@sam_brannen
SpringOne 2021
Testing with
and
Copyright © 2021 VMware, Inc. or its affiliates.
JUnit
©2020 VMware, Inc. 2
This presentation may contain product features or functionality that are currently under
development.
This overview of new technology represents no commitment from VMware to deliver these
features in any generally available product.
Features are subject to change, and must not be included in contracts, purchase orders, or sales
agreements of any kind.
Technical feasibility and market demand will affect final delivery.
Pricing and packaging for any new features/functionality/technology discussed or presented, have
not been determined.
The information in this presentation is for informational purposes only and may not be incorporated into any contract. There is no
commitment or obligation to deliver any items presented herein.
Disclaimer
Sam Brannen
● Staff Software Engineer
● Java Developer for over 20 years
● Spring Framework Core Committer since 2007
● JUnit 5 Core Committer since October 2015
Cover w/ Image
Agenda
● JUnit 5.7
● JUnit 5.8
● Spring 5.3
● GraalVM
● Q&A
JUnit Jupiter Support in Spring
JUnit Jupiter and Spring are a great match for testing
● Spring Framework
● @ExtendWith(SpringExtension.class)
● @SpringJUnitConfig
● @SpringJUnitWebConfig
● Spring Boot
● @SpringBootTest
● @WebMvcTest, etc.
JUnit 5.7
Odds and Ends
https://junit.org/junit5/docs/5.7.2/release-notes/
● Numerous APIs promoted from experimental to stable
● Improvements to EngineTestKit
● Improvements to Assertions
● Improvements to @CsvFileSource and @CsvSource
● Custom disabledReason for all @Enabled* / @Disabled* annotations
Major Features in 5.7
● Java Flight Recorder support
● junit.jupiter.testmethod.order.default configuration parameter to set the
default MethodOrderer
● used unless @TestMethodOrder is present
● @EnabledIf and @DisabledIf: based on condition methods
● @Isolated: run the test class in isolation during parallel execution
● TypedArgumentConverter for converting one specific type to another
○ use with @ConvertWith in a @ParameterizedTest
○ enhancements and bug fixes in 5.8
JUnit 5.8
Major Features in JUnit Platform 1.8
● Declarative test suites via @Suite classes
● SuiteTestEngine in junit-platform-suite-engine module
● new annotations in junit-platform-suite-api module
■ @Suite, @ConfigurationParameter, @SelectUris, @SelectFile, etc.
● UniqueIdTrackingListener
○ TestExecutionListener that tracks the unique IDs of all tests
○ generates a file containing the unique IDs
○ can be used to rerun those tests 
■ for example, with GraalVM Native Build Tools
Example: Suites before 5.8 – Soon to be Deprecated
// Uses JUnit 4 to run JUnit 5
@RunWith(JUnitPlatform.class)
@SuiteDisplayName("Integration Tests")
@IncludeEngines("junit-jupiter")
@SelectPackages("com.example")
@IncludeTags("integration-test")
public class IntegrationTestSuite {
}
Example: Suites with JUnit 5.8
// Uses JUnit 5 to run JUnit 5
@Suite
@SuiteDisplayName("Integration Tests")
@IncludeEngines("junit-jupiter")
@SelectPackages("com.example")
@IncludeTags("integration-test")
public class IntegrationTestSuite {
}
Small Enhancements in JUnit 5.8
https://junit.org/junit5/docs/snapshot/release-notes/
● More fine-grained Java Flight Recorder (JFR) events
● plus support on Java 8 update 262 or higher
● assertThrowsExactly()
○ alternative to assertThrows()
● assertInstanceOf()
○ instead of assertTrue(obj instanceof X)
● @RegisterExtension fields may now be private
New in JUnit Jupiter 5.8
Test Class Execution Order
● ClassOrderer API analogous to the MethodOrderer API
○ ClassName
○ DisplayName
○ OrderAnnotation
○ Random
● Global configuration via junit.jupiter.testclass.order.default configuration
parameter for all test classes
● for example, to optimize the build
● Local configuration via @TestClassOrder for @Nested test classes
Example: @TestClassOrder
@TestClassOrder(ClassOrderer.OrderAnnotation.class)
class OrderedNestedTests {
@Nested
@Order(1)
class PrimaryTests {
@Test
void test1() {}
}
@Nested
@Order(2)
class SecondaryTests {
@Test
void test2() {}
}
}
@TempDir – New Behavior
Due to popular demand from the community…
● @TempDir previously created a single temporary directory per context
● @TempDir can now be used to create multiple temporary directories
● JUnit now creates a separate temporary directory per @TempDir annotation
● Revert to the old behavior by setting the junit.jupiter.tempdir.scope
configuration parameter to per_context
@ExtendWith on Fields and Parameters
Improves programming model
● @RegisterExtension: register extensions via fields programmatically
○ nothing new
● @ExtendWith: can now register extensions via fields and parameters declaratively
● fields: static or instance
● parameters: constructor, lifecycle method, test method
● typically as a meta-annotation
● avoids the need to declare @ExtendWith at the class or method level
Example: RandomNumberExtension
@Target({ ElementType.FIELD, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
@ExtendWith(RandomNumberExtension.class)
public @interface Random {
}
class RandomNumberExtension implements BeforeAllCallback,
BeforeEachCallback, ParameterResolver {
// implementation...
}
Example: @Random in Action
class RandomNumberTests {
@Random
private int randomNumber1;
RandomNumberTests(@Random int randomNumber2) {
}
@BeforeEach
void beforeEach(@Random int randomNumber3) {
}
@Test
void test(@Random int randomNumber4) {
}
}
Named API
● Named: container that associates a name with a given payload
○ The meaning of the payload depends on the context
○ Named.of() vs. Named.named()
● DynamicTests.stream() can consume Named input and will use each name-value pair
as the display name and value for each generated dynamic test
● In parameterized tests using @MethodSource or @ArgumentSource, arguments can
now have explicit names supplied via the Named API
○ explicit name used in display name instead of the argument value
Example: Named Dynamic Tests
@TestFactory
Stream<DynamicTest> dynamicTests() {
Stream<Named<String>> inputStream = Stream.of(
named("racecar is a palindrome", "racecar"),
named("radar is also a palindrome", "radar"),
named("mom also seems to be a palindrome", "mom"),
named("dad is yet another palindrome", "dad")
);
return DynamicTest.stream(inputStream,
text -> assertTrue(isPalindrome(text)));
}
AutoCloseable Arguments in Parameterized Tests
● In parameterized tests, arguments that implement AutoCloseable will now be
automatically closed after the test completes
● Allows for automatic cleanup of resources
○ closing a file
○ stopping a server
○ etc.
● Similar to the CloseableResource support in the ExtensionContext.Store
Spring Framework 5.3
New in Spring Framework 5.3 GA to 5.3.9
https://github.com/spring-projects/spring-framework/releases
● Test configuration is now discovered on enclosing classes for @Nested test classes
● ApplicationEvents abstraction for capturing application events published in the
ApplicationContext during a test
● Set spring.test.constructor.autowire.mode in junit-platform.properties
● Detection for @Autowired violations in JUnit Jupiter
● Improvements for file uploads and multipart support in MockMvc and
MockRestServiceServer
● Various enhancements in MockHttpServletRequest and MockHttpServletResponse
● Improved SQL script parsing regarding delimiters and comments
Example: @Nested tests before 5.3
@SpringJUnitConfig(TestConfig.class)
@ActiveProfiles("dev")
@Transactional
class DevTests {
@Nested
@SpringJUnitConfig(TestConfig.class)
@ActiveProfiles("dev")
@Transactional
class OrderTests { /* tests */ }
@Nested
@SpringJUnitConfig(PricingConfig.class)
class PricingTests { /* tests */ }
}
Example: @Nested tests after 5.3
@SpringJUnitConfig(TestConfig.class)
@ActiveProfiles("dev")
@Transactional
class DevTests {
@Nested
class OrderTests { /* tests */ }
@Nested
@NestedTestConfiguration(OVERRIDE)
@SpringJUnitConfig(PricingConfig.class)
class PricingTests { /* tests */ }
}
Example: ApplicationEvents
@SpringJUnitConfig(/* ... */)
@RecordApplicationEvents
class OrderServiceTests {
@Autowired OrderService orderService;
@Autowired ApplicationEvents events;
@Test
void submitOrder() {
// Invoke method in OrderService that publishes an event
orderService.submitOrder(new Order(/* ... */));
// Verify that 1 OrderSubmitted event was published
assertThat(events.stream(OrderSubmitted.class)).hasSize(1);
}
}
Coming in Spring Framework 5.3.10
Improving every step of the way…
● ExceptionCollector testing utility
● Soft assertions for MockMvc and WebTestClient
● Support for HtmlFileInput.setData() with HtmlUnit and MockMvc
● setDefaultCharacterEncoding() in MockHttpServletResponse
● Default character encoding for responses in MockMvc
Example: MockMvc without Soft Assertions
mockMvc.perform(get("/person/5").accept(APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Jane"));
Example: MockMvc with Soft Assertions
mockMvc.perform(get("/person/5").accept(APPLICATION_JSON))
.andExpectAll(
status().isOk(),
jsonPath("$.name").value("Jane")
);
Example: WebTestClient without Soft Assertions
webTestClient.get().uri("/test").exchange()
.expectStatus().isOk()
.expectBody(String.class).isEqualTo("hello");
Example: WebTestClient with Soft Assertions
webTestClient.get().uri("/test").exchange()
.expectAll(
spec -> spec.expectStatus().isOk(),
spec -> spec.expectBody(String.class).isEqualTo("hello")
);
Example: MockMvc default response character encoding
MockMvc mockMvc;
@BeforeEach
void setup(WebApplicationContext wac) {
this.mockMvc = webAppContextSetup(wac)
.defaultResponseCharacterEncoding(StandardCharsets.UTF_8)
.build();
}
@Test
void getPerson() throws Exception {
this.mockMvc.perform(get("/person/1").characterEncoding(UTF_8))
.andExpect(status().isOk())
.andExpect(content().encoding(UTF_8));
}
GraalVM Native Build Tools
GraalVM Native Build Tools
“The Native Build Tools project provides plugins for different build
tools to add support for building and testing native applications
written in Java (or any other language compiled to JVM bytecode)”
● Collaboration between the GraalVM team, the Spring team, and recently the
Micronaut team as well
● Build tools
● Gradle plugin
● Maven plugin
● Compiling native images
● Testing within a native image using the JUnit Platform
Why test within a native image?
● Java is “write once; run anywhere”.
● … but a native image is not your app running on the JVM.
● You could just rely on your normal JVM-based test suite.
● … because your app is already tested – right?
● You could test your native app from the outside – for example, via HTTP endpoints.
○ … but do you have HTTP endpoints for every feature of your app?
● Best practice:
○ Write your JVM tests like you normally do.
○ Run the same tests (or a subset) within a native image.
How can a Native Build Tools plugin help?
● Runs your tests in the JVM first, using the UniqueIdTrackingListener
○ Tracks the tests you want to run in the native image
○ Necessary since classpath scanning doesn’t work in a native image
● If your tests or the code you’re testing requires reflection, you might need to run your
JVM tests with the GraalVM agent
● Compiles your app and tests into a native image using the JUnitPlatformFeature
(GraalVM Feature)
● Runs your tests within the native image using the NativeImageJUnitLauncher
○ Launches the JUnit Platform and selects your tests based on the output of the
UniqueIdTrackingListener
● Outputs results to the console and XML test reports
How to use Native Build Tools
● Follow the instructions for configuring your Gradle or Maven build
○ https://graalvm.github.io/native-build-tools/
● Or use the Spring Native support configured for your automatically
○ https://start.spring.io
● Gradle:
○ gradle nativeTest
○ gradle –Pagent test and gradle –Pagent nativeTest
● Maven:
○ mvn –Dskip -Pnative test
Things to keep in mind
● Not everything works in a native image
○ Classpath scanning
○ Dynamic class creation
○ Mockito and various mocking libraries
● You might need to exclude certain tests within a native image
○ For example, via tags or a custom ExecutionCondition in JUnit Jupiter
● Building a native image can take a long time
○ Probably not something you want to do multiple times a day
○ A dedicated CI pipeline might be a better choice
Q&A
Thank you
Twitter: @sam_brannen
Slack: #session-testing-with-junit-5-spring-and-native-images
© 2021 Spring. A VMware-backed project.
and JUnit

Mais conteúdo relacionado

Mais procurados

Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot IntroductionJeevesh Pandey
 
Clean architecture
Clean architectureClean architecture
Clean architectureandbed
 
Stateful set in kubernetes implementation & usecases
Stateful set in kubernetes implementation & usecases Stateful set in kubernetes implementation & usecases
Stateful set in kubernetes implementation & usecases Krishna-Kumar
 
Real Life Clean Architecture
Real Life Clean ArchitectureReal Life Clean Architecture
Real Life Clean ArchitectureMattia Battiston
 
Prod-Like Integration Testing for Distributed Containerized Applications
Prod-Like Integration Testing for Distributed Containerized ApplicationsProd-Like Integration Testing for Distributed Containerized Applications
Prod-Like Integration Testing for Distributed Containerized ApplicationsVMware Tanzu
 
Introduction to Spring WebFlux #jsug #sf_a1
Introduction to Spring WebFlux #jsug #sf_a1Introduction to Spring WebFlux #jsug #sf_a1
Introduction to Spring WebFlux #jsug #sf_a1Toshiaki Maki
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOPDzmitry Naskou
 
Testing with JUnit 5 and Spring - Spring I/O 2022
Testing with JUnit 5 and Spring - Spring I/O 2022Testing with JUnit 5 and Spring - Spring I/O 2022
Testing with JUnit 5 and Spring - Spring I/O 2022Sam Brannen
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework Serhat Can
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsYura Nosenko
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - CoreDzmitry Naskou
 
SpringBoot 3 Observability
SpringBoot 3 ObservabilitySpringBoot 3 Observability
SpringBoot 3 ObservabilityKnoldus Inc.
 
Spring boot
Spring bootSpring boot
Spring bootsdeeg
 

Mais procurados (20)

Introduction to spring boot
Introduction to spring bootIntroduction to spring boot
Introduction to spring boot
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Clean architecture
Clean architectureClean architecture
Clean architecture
 
Stateful set in kubernetes implementation & usecases
Stateful set in kubernetes implementation & usecases Stateful set in kubernetes implementation & usecases
Stateful set in kubernetes implementation & usecases
 
Spring Security 5
Spring Security 5Spring Security 5
Spring Security 5
 
An Intro into webpack
An Intro into webpackAn Intro into webpack
An Intro into webpack
 
Real Life Clean Architecture
Real Life Clean ArchitectureReal Life Clean Architecture
Real Life Clean Architecture
 
Clean Architecture
Clean ArchitectureClean Architecture
Clean Architecture
 
Prod-Like Integration Testing for Distributed Containerized Applications
Prod-Like Integration Testing for Distributed Containerized ApplicationsProd-Like Integration Testing for Distributed Containerized Applications
Prod-Like Integration Testing for Distributed Containerized Applications
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
CQRS in 4 steps
CQRS in 4 stepsCQRS in 4 steps
CQRS in 4 steps
 
Introduction to Spring WebFlux #jsug #sf_a1
Introduction to Spring WebFlux #jsug #sf_a1Introduction to Spring WebFlux #jsug #sf_a1
Introduction to Spring WebFlux #jsug #sf_a1
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Testing with JUnit 5 and Spring - Spring I/O 2022
Testing with JUnit 5 and Spring - Spring I/O 2022Testing with JUnit 5 and Spring - Spring I/O 2022
Testing with JUnit 5 and Spring - Spring I/O 2022
 
Spring GraphQL
Spring GraphQLSpring GraphQL
Spring GraphQL
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applications
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
SpringBoot 3 Observability
SpringBoot 3 ObservabilitySpringBoot 3 Observability
SpringBoot 3 Observability
 
Spring boot
Spring bootSpring boot
Spring boot
 

Semelhante a Testing with JUnit 5 and Spring

Spring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing SupportSpring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing SupportSam Brannen
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkOnkar Deshpande
 
Testing Django Applications
Testing Django ApplicationsTesting Django Applications
Testing Django ApplicationsGareth Rushgrove
 
WSO2 Test Automation Framework : Approach and Adoption
WSO2 Test Automation Framework : Approach and AdoptionWSO2 Test Automation Framework : Approach and Adoption
WSO2 Test Automation Framework : Approach and AdoptionWSO2
 
Testing Rest with Spring by Kostiantyn Baranov (Senior Software Engineer, Gl...
Testing Rest with Spring  by Kostiantyn Baranov (Senior Software Engineer, Gl...Testing Rest with Spring  by Kostiantyn Baranov (Senior Software Engineer, Gl...
Testing Rest with Spring by Kostiantyn Baranov (Senior Software Engineer, Gl...GlobalLogic Ukraine
 
Unit Testing Frameworks: A comparative study
Unit Testing Frameworks: A comparative studyUnit Testing Frameworks: A comparative study
Unit Testing Frameworks: A comparative studyIRJET Journal
 
Dusan Lukic Magento 2 Integration Tests Meet Magento Serbia 2016
Dusan Lukic Magento 2 Integration Tests Meet Magento Serbia 2016Dusan Lukic Magento 2 Integration Tests Meet Magento Serbia 2016
Dusan Lukic Magento 2 Integration Tests Meet Magento Serbia 2016Dusan Lukic
 
Unit testing framework
Unit testing frameworkUnit testing framework
Unit testing frameworkIgor Vavrish
 
S313352 optimizing java device testing with automatic feature discovering
S313352 optimizing java device testing with automatic feature discoveringS313352 optimizing java device testing with automatic feature discovering
S313352 optimizing java device testing with automatic feature discoveringromanovfedor
 
The 2014 Decision Makers Guide to Java Web Frameworks
The 2014 Decision Makers Guide to Java Web FrameworksThe 2014 Decision Makers Guide to Java Web Frameworks
The 2014 Decision Makers Guide to Java Web FrameworksKunal Ashar
 
Qtp questions and answers
Qtp questions and answersQtp questions and answers
Qtp questions and answersRamu Palanki
 
New features in qtp11
New features in qtp11New features in qtp11
New features in qtp11Ramu Palanki
 
Qtp 11 new enhacements in
Qtp 11 new enhacements inQtp 11 new enhacements in
Qtp 11 new enhacements inRamu Palanki
 
Testing Django APIs
Testing Django APIsTesting Django APIs
Testing Django APIstyomo4ka
 
Getting started with karate dsl
Getting started with karate dslGetting started with karate dsl
Getting started with karate dslKnoldus Inc.
 

Semelhante a Testing with JUnit 5 and Spring (20)

Junit4.0
Junit4.0Junit4.0
Junit4.0
 
Spring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing SupportSpring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing Support
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
 
Testing Django Applications
Testing Django ApplicationsTesting Django Applications
Testing Django Applications
 
Hybrid framework
Hybrid frameworkHybrid framework
Hybrid framework
 
WSO2 Test Automation Framework : Approach and Adoption
WSO2 Test Automation Framework : Approach and AdoptionWSO2 Test Automation Framework : Approach and Adoption
WSO2 Test Automation Framework : Approach and Adoption
 
Testing Rest with Spring by Kostiantyn Baranov (Senior Software Engineer, Gl...
Testing Rest with Spring  by Kostiantyn Baranov (Senior Software Engineer, Gl...Testing Rest with Spring  by Kostiantyn Baranov (Senior Software Engineer, Gl...
Testing Rest with Spring by Kostiantyn Baranov (Senior Software Engineer, Gl...
 
Wso2 test automation framework internal training
Wso2 test automation framework internal trainingWso2 test automation framework internal training
Wso2 test automation framework internal training
 
Unit Testing Frameworks: A comparative study
Unit Testing Frameworks: A comparative studyUnit Testing Frameworks: A comparative study
Unit Testing Frameworks: A comparative study
 
Dusan Lukic Magento 2 Integration Tests Meet Magento Serbia 2016
Dusan Lukic Magento 2 Integration Tests Meet Magento Serbia 2016Dusan Lukic Magento 2 Integration Tests Meet Magento Serbia 2016
Dusan Lukic Magento 2 Integration Tests Meet Magento Serbia 2016
 
L08 Unit Testing
L08 Unit TestingL08 Unit Testing
L08 Unit Testing
 
Unit testing framework
Unit testing frameworkUnit testing framework
Unit testing framework
 
S313352 optimizing java device testing with automatic feature discovering
S313352 optimizing java device testing with automatic feature discoveringS313352 optimizing java device testing with automatic feature discovering
S313352 optimizing java device testing with automatic feature discovering
 
The 2014 Decision Makers Guide to Java Web Frameworks
The 2014 Decision Makers Guide to Java Web FrameworksThe 2014 Decision Makers Guide to Java Web Frameworks
The 2014 Decision Makers Guide to Java Web Frameworks
 
Txet Document
Txet DocumentTxet Document
Txet Document
 
Qtp questions and answers
Qtp questions and answersQtp questions and answers
Qtp questions and answers
 
New features in qtp11
New features in qtp11New features in qtp11
New features in qtp11
 
Qtp 11 new enhacements in
Qtp 11 new enhacements inQtp 11 new enhacements in
Qtp 11 new enhacements in
 
Testing Django APIs
Testing Django APIsTesting Django APIs
Testing Django APIs
 
Getting started with karate dsl
Getting started with karate dslGetting started with karate dsl
Getting started with karate dsl
 

Mais de VMware Tanzu

What AI Means For Your Product Strategy And What To Do About It
What AI Means For Your Product Strategy And What To Do About ItWhat AI Means For Your Product Strategy And What To Do About It
What AI Means For Your Product Strategy And What To Do About ItVMware Tanzu
 
Make the Right Thing the Obvious Thing at Cardinal Health 2023
Make the Right Thing the Obvious Thing at Cardinal Health 2023Make the Right Thing the Obvious Thing at Cardinal Health 2023
Make the Right Thing the Obvious Thing at Cardinal Health 2023VMware Tanzu
 
Enhancing DevEx and Simplifying Operations at Scale
Enhancing DevEx and Simplifying Operations at ScaleEnhancing DevEx and Simplifying Operations at Scale
Enhancing DevEx and Simplifying Operations at ScaleVMware Tanzu
 
Spring Update | July 2023
Spring Update | July 2023Spring Update | July 2023
Spring Update | July 2023VMware Tanzu
 
Platforms, Platform Engineering, & Platform as a Product
Platforms, Platform Engineering, & Platform as a ProductPlatforms, Platform Engineering, & Platform as a Product
Platforms, Platform Engineering, & Platform as a ProductVMware Tanzu
 
Building Cloud Ready Apps
Building Cloud Ready AppsBuilding Cloud Ready Apps
Building Cloud Ready AppsVMware Tanzu
 
Spring Boot 3 And Beyond
Spring Boot 3 And BeyondSpring Boot 3 And Beyond
Spring Boot 3 And BeyondVMware Tanzu
 
Spring Cloud Gateway - SpringOne Tour 2023 Charles Schwab.pdf
Spring Cloud Gateway - SpringOne Tour 2023 Charles Schwab.pdfSpring Cloud Gateway - SpringOne Tour 2023 Charles Schwab.pdf
Spring Cloud Gateway - SpringOne Tour 2023 Charles Schwab.pdfVMware Tanzu
 
Simplify and Scale Enterprise Apps in the Cloud | Boston 2023
Simplify and Scale Enterprise Apps in the Cloud | Boston 2023Simplify and Scale Enterprise Apps in the Cloud | Boston 2023
Simplify and Scale Enterprise Apps in the Cloud | Boston 2023VMware Tanzu
 
Simplify and Scale Enterprise Apps in the Cloud | Seattle 2023
Simplify and Scale Enterprise Apps in the Cloud | Seattle 2023Simplify and Scale Enterprise Apps in the Cloud | Seattle 2023
Simplify and Scale Enterprise Apps in the Cloud | Seattle 2023VMware Tanzu
 
tanzu_developer_connect.pptx
tanzu_developer_connect.pptxtanzu_developer_connect.pptx
tanzu_developer_connect.pptxVMware Tanzu
 
Tanzu Virtual Developer Connect Workshop - French
Tanzu Virtual Developer Connect Workshop - FrenchTanzu Virtual Developer Connect Workshop - French
Tanzu Virtual Developer Connect Workshop - FrenchVMware Tanzu
 
Tanzu Developer Connect Workshop - English
Tanzu Developer Connect Workshop - EnglishTanzu Developer Connect Workshop - English
Tanzu Developer Connect Workshop - EnglishVMware Tanzu
 
Virtual Developer Connect Workshop - English
Virtual Developer Connect Workshop - EnglishVirtual Developer Connect Workshop - English
Virtual Developer Connect Workshop - EnglishVMware Tanzu
 
Tanzu Developer Connect - French
Tanzu Developer Connect - FrenchTanzu Developer Connect - French
Tanzu Developer Connect - FrenchVMware Tanzu
 
Simplify and Scale Enterprise Apps in the Cloud | Dallas 2023
Simplify and Scale Enterprise Apps in the Cloud | Dallas 2023Simplify and Scale Enterprise Apps in the Cloud | Dallas 2023
Simplify and Scale Enterprise Apps in the Cloud | Dallas 2023VMware Tanzu
 
SpringOne Tour: Deliver 15-Factor Applications on Kubernetes with Spring Boot
SpringOne Tour: Deliver 15-Factor Applications on Kubernetes with Spring BootSpringOne Tour: Deliver 15-Factor Applications on Kubernetes with Spring Boot
SpringOne Tour: Deliver 15-Factor Applications on Kubernetes with Spring BootVMware Tanzu
 
SpringOne Tour: The Influential Software Engineer
SpringOne Tour: The Influential Software EngineerSpringOne Tour: The Influential Software Engineer
SpringOne Tour: The Influential Software EngineerVMware Tanzu
 
SpringOne Tour: Domain-Driven Design: Theory vs Practice
SpringOne Tour: Domain-Driven Design: Theory vs PracticeSpringOne Tour: Domain-Driven Design: Theory vs Practice
SpringOne Tour: Domain-Driven Design: Theory vs PracticeVMware Tanzu
 
SpringOne Tour: Spring Recipes: A Collection of Common-Sense Solutions
SpringOne Tour: Spring Recipes: A Collection of Common-Sense SolutionsSpringOne Tour: Spring Recipes: A Collection of Common-Sense Solutions
SpringOne Tour: Spring Recipes: A Collection of Common-Sense SolutionsVMware Tanzu
 

Mais de VMware Tanzu (20)

What AI Means For Your Product Strategy And What To Do About It
What AI Means For Your Product Strategy And What To Do About ItWhat AI Means For Your Product Strategy And What To Do About It
What AI Means For Your Product Strategy And What To Do About It
 
Make the Right Thing the Obvious Thing at Cardinal Health 2023
Make the Right Thing the Obvious Thing at Cardinal Health 2023Make the Right Thing the Obvious Thing at Cardinal Health 2023
Make the Right Thing the Obvious Thing at Cardinal Health 2023
 
Enhancing DevEx and Simplifying Operations at Scale
Enhancing DevEx and Simplifying Operations at ScaleEnhancing DevEx and Simplifying Operations at Scale
Enhancing DevEx and Simplifying Operations at Scale
 
Spring Update | July 2023
Spring Update | July 2023Spring Update | July 2023
Spring Update | July 2023
 
Platforms, Platform Engineering, & Platform as a Product
Platforms, Platform Engineering, & Platform as a ProductPlatforms, Platform Engineering, & Platform as a Product
Platforms, Platform Engineering, & Platform as a Product
 
Building Cloud Ready Apps
Building Cloud Ready AppsBuilding Cloud Ready Apps
Building Cloud Ready Apps
 
Spring Boot 3 And Beyond
Spring Boot 3 And BeyondSpring Boot 3 And Beyond
Spring Boot 3 And Beyond
 
Spring Cloud Gateway - SpringOne Tour 2023 Charles Schwab.pdf
Spring Cloud Gateway - SpringOne Tour 2023 Charles Schwab.pdfSpring Cloud Gateway - SpringOne Tour 2023 Charles Schwab.pdf
Spring Cloud Gateway - SpringOne Tour 2023 Charles Schwab.pdf
 
Simplify and Scale Enterprise Apps in the Cloud | Boston 2023
Simplify and Scale Enterprise Apps in the Cloud | Boston 2023Simplify and Scale Enterprise Apps in the Cloud | Boston 2023
Simplify and Scale Enterprise Apps in the Cloud | Boston 2023
 
Simplify and Scale Enterprise Apps in the Cloud | Seattle 2023
Simplify and Scale Enterprise Apps in the Cloud | Seattle 2023Simplify and Scale Enterprise Apps in the Cloud | Seattle 2023
Simplify and Scale Enterprise Apps in the Cloud | Seattle 2023
 
tanzu_developer_connect.pptx
tanzu_developer_connect.pptxtanzu_developer_connect.pptx
tanzu_developer_connect.pptx
 
Tanzu Virtual Developer Connect Workshop - French
Tanzu Virtual Developer Connect Workshop - FrenchTanzu Virtual Developer Connect Workshop - French
Tanzu Virtual Developer Connect Workshop - French
 
Tanzu Developer Connect Workshop - English
Tanzu Developer Connect Workshop - EnglishTanzu Developer Connect Workshop - English
Tanzu Developer Connect Workshop - English
 
Virtual Developer Connect Workshop - English
Virtual Developer Connect Workshop - EnglishVirtual Developer Connect Workshop - English
Virtual Developer Connect Workshop - English
 
Tanzu Developer Connect - French
Tanzu Developer Connect - FrenchTanzu Developer Connect - French
Tanzu Developer Connect - French
 
Simplify and Scale Enterprise Apps in the Cloud | Dallas 2023
Simplify and Scale Enterprise Apps in the Cloud | Dallas 2023Simplify and Scale Enterprise Apps in the Cloud | Dallas 2023
Simplify and Scale Enterprise Apps in the Cloud | Dallas 2023
 
SpringOne Tour: Deliver 15-Factor Applications on Kubernetes with Spring Boot
SpringOne Tour: Deliver 15-Factor Applications on Kubernetes with Spring BootSpringOne Tour: Deliver 15-Factor Applications on Kubernetes with Spring Boot
SpringOne Tour: Deliver 15-Factor Applications on Kubernetes with Spring Boot
 
SpringOne Tour: The Influential Software Engineer
SpringOne Tour: The Influential Software EngineerSpringOne Tour: The Influential Software Engineer
SpringOne Tour: The Influential Software Engineer
 
SpringOne Tour: Domain-Driven Design: Theory vs Practice
SpringOne Tour: Domain-Driven Design: Theory vs PracticeSpringOne Tour: Domain-Driven Design: Theory vs Practice
SpringOne Tour: Domain-Driven Design: Theory vs Practice
 
SpringOne Tour: Spring Recipes: A Collection of Common-Sense Solutions
SpringOne Tour: Spring Recipes: A Collection of Common-Sense SolutionsSpringOne Tour: Spring Recipes: A Collection of Common-Sense Solutions
SpringOne Tour: Spring Recipes: A Collection of Common-Sense Solutions
 

Último

Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
WSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AIWSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AIWSO2
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Bert Jan Schrijver
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2
 
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...WSO2
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benonimasabamasaba
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburgmasabamasaba
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 

Último (20)

Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
WSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AIWSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AI
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 

Testing with JUnit 5 and Spring

  • 1. Sam Brannen @sam_brannen SpringOne 2021 Testing with and Copyright © 2021 VMware, Inc. or its affiliates. JUnit
  • 2. ©2020 VMware, Inc. 2 This presentation may contain product features or functionality that are currently under development. This overview of new technology represents no commitment from VMware to deliver these features in any generally available product. Features are subject to change, and must not be included in contracts, purchase orders, or sales agreements of any kind. Technical feasibility and market demand will affect final delivery. Pricing and packaging for any new features/functionality/technology discussed or presented, have not been determined. The information in this presentation is for informational purposes only and may not be incorporated into any contract. There is no commitment or obligation to deliver any items presented herein. Disclaimer
  • 3. Sam Brannen ● Staff Software Engineer ● Java Developer for over 20 years ● Spring Framework Core Committer since 2007 ● JUnit 5 Core Committer since October 2015
  • 4. Cover w/ Image Agenda ● JUnit 5.7 ● JUnit 5.8 ● Spring 5.3 ● GraalVM ● Q&A
  • 5. JUnit Jupiter Support in Spring JUnit Jupiter and Spring are a great match for testing ● Spring Framework ● @ExtendWith(SpringExtension.class) ● @SpringJUnitConfig ● @SpringJUnitWebConfig ● Spring Boot ● @SpringBootTest ● @WebMvcTest, etc.
  • 7. Odds and Ends https://junit.org/junit5/docs/5.7.2/release-notes/ ● Numerous APIs promoted from experimental to stable ● Improvements to EngineTestKit ● Improvements to Assertions ● Improvements to @CsvFileSource and @CsvSource ● Custom disabledReason for all @Enabled* / @Disabled* annotations
  • 8. Major Features in 5.7 ● Java Flight Recorder support ● junit.jupiter.testmethod.order.default configuration parameter to set the default MethodOrderer ● used unless @TestMethodOrder is present ● @EnabledIf and @DisabledIf: based on condition methods ● @Isolated: run the test class in isolation during parallel execution ● TypedArgumentConverter for converting one specific type to another ○ use with @ConvertWith in a @ParameterizedTest ○ enhancements and bug fixes in 5.8
  • 10. Major Features in JUnit Platform 1.8 ● Declarative test suites via @Suite classes ● SuiteTestEngine in junit-platform-suite-engine module ● new annotations in junit-platform-suite-api module ■ @Suite, @ConfigurationParameter, @SelectUris, @SelectFile, etc. ● UniqueIdTrackingListener ○ TestExecutionListener that tracks the unique IDs of all tests ○ generates a file containing the unique IDs ○ can be used to rerun those tests  ■ for example, with GraalVM Native Build Tools
  • 11. Example: Suites before 5.8 – Soon to be Deprecated // Uses JUnit 4 to run JUnit 5 @RunWith(JUnitPlatform.class) @SuiteDisplayName("Integration Tests") @IncludeEngines("junit-jupiter") @SelectPackages("com.example") @IncludeTags("integration-test") public class IntegrationTestSuite { }
  • 12. Example: Suites with JUnit 5.8 // Uses JUnit 5 to run JUnit 5 @Suite @SuiteDisplayName("Integration Tests") @IncludeEngines("junit-jupiter") @SelectPackages("com.example") @IncludeTags("integration-test") public class IntegrationTestSuite { }
  • 13. Small Enhancements in JUnit 5.8 https://junit.org/junit5/docs/snapshot/release-notes/ ● More fine-grained Java Flight Recorder (JFR) events ● plus support on Java 8 update 262 or higher ● assertThrowsExactly() ○ alternative to assertThrows() ● assertInstanceOf() ○ instead of assertTrue(obj instanceof X) ● @RegisterExtension fields may now be private
  • 14. New in JUnit Jupiter 5.8
  • 15. Test Class Execution Order ● ClassOrderer API analogous to the MethodOrderer API ○ ClassName ○ DisplayName ○ OrderAnnotation ○ Random ● Global configuration via junit.jupiter.testclass.order.default configuration parameter for all test classes ● for example, to optimize the build ● Local configuration via @TestClassOrder for @Nested test classes
  • 16. Example: @TestClassOrder @TestClassOrder(ClassOrderer.OrderAnnotation.class) class OrderedNestedTests { @Nested @Order(1) class PrimaryTests { @Test void test1() {} } @Nested @Order(2) class SecondaryTests { @Test void test2() {} } }
  • 17. @TempDir – New Behavior Due to popular demand from the community… ● @TempDir previously created a single temporary directory per context ● @TempDir can now be used to create multiple temporary directories ● JUnit now creates a separate temporary directory per @TempDir annotation ● Revert to the old behavior by setting the junit.jupiter.tempdir.scope configuration parameter to per_context
  • 18. @ExtendWith on Fields and Parameters Improves programming model ● @RegisterExtension: register extensions via fields programmatically ○ nothing new ● @ExtendWith: can now register extensions via fields and parameters declaratively ● fields: static or instance ● parameters: constructor, lifecycle method, test method ● typically as a meta-annotation ● avoids the need to declare @ExtendWith at the class or method level
  • 19. Example: RandomNumberExtension @Target({ ElementType.FIELD, ElementType.PARAMETER }) @Retention(RetentionPolicy.RUNTIME) @ExtendWith(RandomNumberExtension.class) public @interface Random { } class RandomNumberExtension implements BeforeAllCallback, BeforeEachCallback, ParameterResolver { // implementation... }
  • 20. Example: @Random in Action class RandomNumberTests { @Random private int randomNumber1; RandomNumberTests(@Random int randomNumber2) { } @BeforeEach void beforeEach(@Random int randomNumber3) { } @Test void test(@Random int randomNumber4) { } }
  • 21. Named API ● Named: container that associates a name with a given payload ○ The meaning of the payload depends on the context ○ Named.of() vs. Named.named() ● DynamicTests.stream() can consume Named input and will use each name-value pair as the display name and value for each generated dynamic test ● In parameterized tests using @MethodSource or @ArgumentSource, arguments can now have explicit names supplied via the Named API ○ explicit name used in display name instead of the argument value
  • 22. Example: Named Dynamic Tests @TestFactory Stream<DynamicTest> dynamicTests() { Stream<Named<String>> inputStream = Stream.of( named("racecar is a palindrome", "racecar"), named("radar is also a palindrome", "radar"), named("mom also seems to be a palindrome", "mom"), named("dad is yet another palindrome", "dad") ); return DynamicTest.stream(inputStream, text -> assertTrue(isPalindrome(text))); }
  • 23. AutoCloseable Arguments in Parameterized Tests ● In parameterized tests, arguments that implement AutoCloseable will now be automatically closed after the test completes ● Allows for automatic cleanup of resources ○ closing a file ○ stopping a server ○ etc. ● Similar to the CloseableResource support in the ExtensionContext.Store
  • 25. New in Spring Framework 5.3 GA to 5.3.9 https://github.com/spring-projects/spring-framework/releases ● Test configuration is now discovered on enclosing classes for @Nested test classes ● ApplicationEvents abstraction for capturing application events published in the ApplicationContext during a test ● Set spring.test.constructor.autowire.mode in junit-platform.properties ● Detection for @Autowired violations in JUnit Jupiter ● Improvements for file uploads and multipart support in MockMvc and MockRestServiceServer ● Various enhancements in MockHttpServletRequest and MockHttpServletResponse ● Improved SQL script parsing regarding delimiters and comments
  • 26. Example: @Nested tests before 5.3 @SpringJUnitConfig(TestConfig.class) @ActiveProfiles("dev") @Transactional class DevTests { @Nested @SpringJUnitConfig(TestConfig.class) @ActiveProfiles("dev") @Transactional class OrderTests { /* tests */ } @Nested @SpringJUnitConfig(PricingConfig.class) class PricingTests { /* tests */ } }
  • 27. Example: @Nested tests after 5.3 @SpringJUnitConfig(TestConfig.class) @ActiveProfiles("dev") @Transactional class DevTests { @Nested class OrderTests { /* tests */ } @Nested @NestedTestConfiguration(OVERRIDE) @SpringJUnitConfig(PricingConfig.class) class PricingTests { /* tests */ } }
  • 28. Example: ApplicationEvents @SpringJUnitConfig(/* ... */) @RecordApplicationEvents class OrderServiceTests { @Autowired OrderService orderService; @Autowired ApplicationEvents events; @Test void submitOrder() { // Invoke method in OrderService that publishes an event orderService.submitOrder(new Order(/* ... */)); // Verify that 1 OrderSubmitted event was published assertThat(events.stream(OrderSubmitted.class)).hasSize(1); } }
  • 29. Coming in Spring Framework 5.3.10 Improving every step of the way… ● ExceptionCollector testing utility ● Soft assertions for MockMvc and WebTestClient ● Support for HtmlFileInput.setData() with HtmlUnit and MockMvc ● setDefaultCharacterEncoding() in MockHttpServletResponse ● Default character encoding for responses in MockMvc
  • 30. Example: MockMvc without Soft Assertions mockMvc.perform(get("/person/5").accept(APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.name").value("Jane"));
  • 31. Example: MockMvc with Soft Assertions mockMvc.perform(get("/person/5").accept(APPLICATION_JSON)) .andExpectAll( status().isOk(), jsonPath("$.name").value("Jane") );
  • 32. Example: WebTestClient without Soft Assertions webTestClient.get().uri("/test").exchange() .expectStatus().isOk() .expectBody(String.class).isEqualTo("hello");
  • 33. Example: WebTestClient with Soft Assertions webTestClient.get().uri("/test").exchange() .expectAll( spec -> spec.expectStatus().isOk(), spec -> spec.expectBody(String.class).isEqualTo("hello") );
  • 34. Example: MockMvc default response character encoding MockMvc mockMvc; @BeforeEach void setup(WebApplicationContext wac) { this.mockMvc = webAppContextSetup(wac) .defaultResponseCharacterEncoding(StandardCharsets.UTF_8) .build(); } @Test void getPerson() throws Exception { this.mockMvc.perform(get("/person/1").characterEncoding(UTF_8)) .andExpect(status().isOk()) .andExpect(content().encoding(UTF_8)); }
  • 36. GraalVM Native Build Tools “The Native Build Tools project provides plugins for different build tools to add support for building and testing native applications written in Java (or any other language compiled to JVM bytecode)” ● Collaboration between the GraalVM team, the Spring team, and recently the Micronaut team as well ● Build tools ● Gradle plugin ● Maven plugin ● Compiling native images ● Testing within a native image using the JUnit Platform
  • 37. Why test within a native image? ● Java is “write once; run anywhere”. ● … but a native image is not your app running on the JVM. ● You could just rely on your normal JVM-based test suite. ● … because your app is already tested – right? ● You could test your native app from the outside – for example, via HTTP endpoints. ○ … but do you have HTTP endpoints for every feature of your app? ● Best practice: ○ Write your JVM tests like you normally do. ○ Run the same tests (or a subset) within a native image.
  • 38. How can a Native Build Tools plugin help? ● Runs your tests in the JVM first, using the UniqueIdTrackingListener ○ Tracks the tests you want to run in the native image ○ Necessary since classpath scanning doesn’t work in a native image ● If your tests or the code you’re testing requires reflection, you might need to run your JVM tests with the GraalVM agent ● Compiles your app and tests into a native image using the JUnitPlatformFeature (GraalVM Feature) ● Runs your tests within the native image using the NativeImageJUnitLauncher ○ Launches the JUnit Platform and selects your tests based on the output of the UniqueIdTrackingListener ● Outputs results to the console and XML test reports
  • 39. How to use Native Build Tools ● Follow the instructions for configuring your Gradle or Maven build ○ https://graalvm.github.io/native-build-tools/ ● Or use the Spring Native support configured for your automatically ○ https://start.spring.io ● Gradle: ○ gradle nativeTest ○ gradle –Pagent test and gradle –Pagent nativeTest ● Maven: ○ mvn –Dskip -Pnative test
  • 40. Things to keep in mind ● Not everything works in a native image ○ Classpath scanning ○ Dynamic class creation ○ Mockito and various mocking libraries ● You might need to exclude certain tests within a native image ○ For example, via tags or a custom ExecutionCondition in JUnit Jupiter ● Building a native image can take a long time ○ Probably not something you want to do multiple times a day ○ A dedicated CI pipeline might be a better choice
  • 41. Q&A
  • 42. Thank you Twitter: @sam_brannen Slack: #session-testing-with-junit-5-spring-and-native-images © 2021 Spring. A VMware-backed project. and JUnit