Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

JUnit 5 - Evolution and Innovation - SpringOne Platform 2019

332 views

Published on

Join core JUnit 5 committer Sam Brannen to gain insight on the latest new features in JUnit 5 as well as what’s on the horizon.

In this presentation we will look at exciting new features that have been added in JUnit 5 over the past year, including temporary directories, custom display name generators, method ordering, timeouts, the Test Kit, and powerful new extension APIs. If you haven't yet made the switch from JUnit 4 to JUnit 5 you will definitely want to check out this presentation.

In closing, Sam will also provide a few tips on how to use JUnit Jupiter to test Spring and Spring Boot apps.

Published in: Software
  • Ex-Student reveals the number one secret to scoring an A* in GCSE/IGCSE Maths, click here to find out more ♣♣♣ http://t.cn/AirrSv7D
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THAT BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { http://bit.ly/2m77EgH } ......................................................................................................................... Download Full EPUB Ebook here { http://bit.ly/2m77EgH } ......................................................................................................................... Download Full doc Ebook here { http://bit.ly/2m77EgH } ......................................................................................................................... Download PDF EBOOK here { http://bit.ly/2m77EgH } ......................................................................................................................... Download EPUB Ebook here { http://bit.ly/2m77EgH } ......................................................................................................................... Download doc Ebook here { http://bit.ly/2m77EgH } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book that can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer that is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story That Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money That the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths that Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

JUnit 5 - Evolution and Innovation - SpringOne Platform 2019

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

×