0% found this document useful (0 votes)
113 views5 pages

JUnit 5 Testing Framework Overview

The document discusses JUnit 5, including the JUnit Platform which launches testing frameworks on the JVM. It describes TestRunners, TestEngines, and annotations used in JUnit 5 like @Test, @BeforeEach, and @AfterEach. It also discusses how JUnit Vintage allows running previous JUnit 3 and 4 tests on the new platform and how to configure test filtering and ordering.

Uploaded by

amitfegade121
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
113 views5 pages

JUnit 5 Testing Framework Overview

The document discusses JUnit 5, including the JUnit Platform which launches testing frameworks on the JVM. It describes TestRunners, TestEngines, and annotations used in JUnit 5 like @Test, @BeforeEach, and @AfterEach. It also discusses how JUnit Vintage allows running previous JUnit 3 and 4 tests on the new platform and how to configure test filtering and ordering.

Uploaded by

amitfegade121
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

junit paltform:

JUnit Platform
Launches testing frameworks on the JVM
Has TestEngine API used to build a testing framework that runs on the JUnit
platform

-- Test Runners
-- Provides context to run tests
-- Test Engine

We can't directly use/interact with platform.


API @Test, assert part of jupiter - while writing code we have to use jupiter
Vintage - You can use the vintage to interact with older version of Junit.

Unit Jupiter
Blend of new programming model for writing tests and extension model for extensions
Addition of new annotations like @BeforeEach, @AfterEach, @AfterAll, @BeforeAll
etc.

JUnit Vintage
Provides support to execute previous JUnit version 3 and 4 tests on this new
platform

@TestInstance([Link].PER_CLASS)

@DisplayName
@Disabled
@Timeout(value = 500, unit = [Link])

@RepeatedTest

@Nested

assertAll()
assertThrow(expectedType, Executable)

Conditional Execution:

@EnableOnOS([Link]) @DisabledOnOS
@EnableOnJre()JRE.JAVA_11) @DisabledOnJre
@EnableIf
@EnabledIfSystemProperty
@EnabledIfEnvironmentVariable

Properties properties = [Link]();


[Link]((k, v) -> [Link](k + ":" + v));

Map<String, String> env = [Link]();


[Link]((k, v) -> [Link](k + ":" + v));

Assumptions:

assertTrue()
assertFalse()

<plugin>
<groupId>[Link]</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M3</version>
<configuration>
<!-- include tags -->
<groups>integration, feature-168</groups>
<!-- exclude tags -->
<excludedGroups>slow</excludedGroups>
</configuration>
</plugin>

mvn -Dgroups="integration, fast, feature-168"

mvn -DexcludedGroups="slow"

MethodOrderer

Alphanumeric
OrderAnnotation
Random
Custom Order

Alphanumeric
1.1 It sorts test methods alphanumerically.

@TestMethodOrder([Link])

@TestMethodOrder([Link])
It sorts test methods based on the @Order values.

@Order(2)

@TestMethodOrder([Link])

TestSuite in JUnit 5

@SelectPackages("....")
@SelectPackages({"..." , "..." })

@SelectClasses(...)
@SelectClasses({..., ..., ...})

@RunWith([Link])

@SelectPackages("....")
@IncludePackages()
@ExcludePackages()

@IncludeTags()
@ExcludeTags()

In JUnit, you can organize the test cases into different categories, and run those
categorized test cases with @[Link] or
@[Link]

This @Categories annotation is available since JUnit 4.12

@Category([Link])

@Category({[Link], [Link]})
public class ClassB {

@Test
public void test_b_1() {
assertThat(1 == 1, is(true));
}
}

@RunWith([Link])
@[Link]([Link])
//Include multiple categories
//@[Link]({[Link], [Link]})
@[Link]({[Link], [Link], [Link]})
public class PerformanceTestSuite {
}

@RunWith([Link])
@[Link]([Link])
@[Link]({[Link], [Link], [Link]})
public class ExcludePerformanceTestSuite {
}

<dependency>
<groupId>[Link]</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.1.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>junit-platform-runner</artifactId>
<version> 1.1.1</version>
<scope>test</scope>
</dependency>

1. Junit 5 Parameterized Test


Some times we may need to run same tests with different arguments or values, Junit
5 Parameterized tests make it possible to run a test multiple times with different
arguments. They are declared just like regular @Test methods but use the
@ParameterizedTest annotation instead of @Test annotation.

1.1. Writing parameterized tests


Following are the steps to create parameterized tests in Junit 5.

Declare @ParameterizedTest to the test.


Declare at least one source (example � @ValueSource) that will provide the
arguments for each invocation of test.
Consume the arguments in the test method .
<dependency>
<groupId>[Link]</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>${[Link]}</version>
<scope>test</scope>
</dependency>

public class Junit5_Parameterized_Test {

// This test will run sequentially 5 times with 1 argument each time
@ParameterizedTest
@ValueSource(ints = {8,4,2,6,10})
void test_int_arrays(int arg) {
[Link]("arg => "+arg);
assertTrue(arg % 2 == 0);
}
}

1.2. Customizing Display Names in Parameterized tests


By default, the display name of a parameterized test invocation contains the
invocation index and the String representation of all arguments for that specific
invocation. The following placeholders are supported within custom display names.

Placeholder Description
{displayName} placeholder for the display name of the method.
{index} placeholder for the current invocation index (starts from 1).
{arguments} placeholder for the complete, comma-separated arguments list.
{0}, {1}, �? placeholder for an individual argument.
public class Junit5_CustomDisplayNames_Test {

@ParameterizedTest(name="#{index}- Test with Argument={arguments}")


@ValueSource(ints = {8,4,2,6,10})
void test_int_arrays(int arg) {
[Link]("arg => "+arg);
assertTrue(arg % 2 == 0);
}

@ParameterizedTest(name="#{index} - Test with Argument={0}")


@ValueSource(strings = {"Peter King", "Arthur King", "Martin King"})
void test_string_arrays(String arg) {
String searchKey = "King";

[Link]("arg => "+arg);


assertTrue([Link](searchKey));
}

@ParameterizedTest(name="Test with argument - {arguments}")


@NullSource
void test_null_source(String arg) {

[Link]("arg => "+arg);


assertTrue(arg == null);
}
}
[Link]
examples/#:~:text=1.1.&text=Following%20are%20the%20steps%20to,arguments%20in%20the
%20test%20method%20.

Add maven-surefire-report-plugin to [Link] reporting element

<reporting>
<plugins>
<plugin>
<groupId>[Link]</groupId>
<artifactId>maven-surefire-report-plugin</artifactId>
<version>2.22.0</version>
</plugin>
</plugins>
</reporting>

> mvn site

Run mvn site command from the terminal. It will generate HTML reports in
target/site directory.

Open the [Link] file in the browser.

site surefire-report:report

Common questions

Powered by AI

Parameterized tests in JUnit 5 improve test coverage by allowing the same test to be executed multiple times with different inputs, thereby validating multiple scenarios without the need for duplicate test code. Customizing display names is achieved through placeholders like `{displayName}`, `{index}`, `{arguments}`, and individual argument placeholders `{0}, {1}, ...`, which allow detailed and informative test logs and reports .

JUnit 5 uses assumptions to conditionally execute tests based on certain prerequisites using methods like `assertTrue()` and `assertFalse()`. This allows test logic to bypass execution when conditions aren't met, aligning tests with specific criteria or states. Assumptions prevent irrelevant failures due to unmet preconditions and enhance test relevance when specific environmental conditions or states are prescribed .

Nested tests in JUnit 5 offer the advantage of logically grouping test cases, which can lead to more organized and readable test code. This structure is particularly beneficial when testing classes with deep collaboration or intricate workflows, as it allows for a hierarchical organization that mirrors class relationships and enhances comprehension of test structures relative to program logic .

JUnit 5 introduces lifecycle annotations such as `@BeforeEach`, `@AfterEach`, `@BeforeAll`, and `@AfterAll`, which contribute to efficient test setups by enabling precise configuration and execution of initialization and cleanup methods around test cases. They reduce redundancy and improve maintainability by clearly defining resource setup and teardown procedures, thereby ensuring each test cycle is executed in a controlled environment .

JUnit 5 provides backward compatibility for older versions of JUnit through the JUnit Vintage component. This component supports the execution of tests written in JUnit 3 and JUnit 4 on the new JUnit Platform. It allows integration and interaction with older test methods by using the `JUnit Vintage` engine, thereby ensuring a smooth transition for legacy test suites to the new platform .

Customization of test names in parameterized tests affects reporting and maintenance by providing descriptive and specific execution data. Custom names enhance reports by clearly displaying argument values and invocation details, which facilitates easier understanding of failures and achievements in automated reports. This clarity aids maintenance by allowing quick assessment and minimal misinterpretation of test results .

JUnit 5's conditional execution features, such as `@EnableOnOS`, `@DisabledOnOS`, `@EnableOnJre`, and others, optimize test performance and reliability by allowing tests to run only in designated environments. This is particularly useful for integration tests or tests with specific environment dependencies, reducing the risk of failures due to non-conforming conditions, hence improving both test reliability and performance by avoiding unnecessary test executions .

JUnit 5 offers flexible method ordering through the `MethodOrderer` interface, which allows tests to be executed in different orders. The `Alphanumeric` order sorts tests based on alphanumeric naming, `OrderAnnotation` uses explicit `@Order` annotations, and `Random` order can execute tests in a random sequence. This flexibility enhances test execution by allowing developers to determine the optimal order of test runs, which can help identify interdependencies among tests and ensure test isolation .

The `maven-surefire-plugin` is crucial in JUnit testing for managing test execution. It allows configuration to include or exclude test groups using tags, facilitating tailored test runs to match development needs or ignore unwanted tests (`mvn -Dgroups="..."` for required groups and `mvn -DexcludedGroups="..."` for exclusion). This customization supports complex testing strategies by streamlining test execution based on specified criteria, improving test management efficiency .

JUnit 5 supports running specific categories of tests through annotations like `@SelectPackages`, `@IncludePackages`, and `@IncludeTags`. By categorizing tests, developers can selectively execute subsets of tests, which is beneficial in a complex environment by allowing focus on relevant tests only, enhancing efficiency, and enabling thorough analysis of specific test categories without running the entire suite .

You might also like