Search code examples
junit5parameterized

Abort/ignore parameterized test in JUnit 5


I have some parameterized tests

@ParameterizedTest
@CsvFileSource(resources = "testData.csv", numLinesToSkip = 1)
public void testExample(String parameter, String anotherParameter) {

    // testing here
}

In case one execution fails, I want to ignore all following executions.


Solution

  • AFAIK there is no built-in mechanism to do this. The following does work, but is a bit hackish:

    @TestInstance(Lifecycle.PER_CLASS)
    class Test {
    
        boolean skipRemaining = false;
        
        @ParameterizedTest
        @CsvFileSource(resources = "testData.csv", numLinesToSkip = 1)
        void test(String parameter, String anotherParameter) {
            Assumptions.assumeFalse(skipRemaining);
            try {
                // testing here
            } catch (AssertionError e) {
                skipRemaining = true;
                throw e;
            }
        }
    
    }
    

    In contrast to a failed assertion, which marks a test as failed, an assumption results in an abort of a test. In addition, the lifecycle is switched from per method to per class:

    When using this mode, a new test instance will be created once per test class. Thus, if your test methods rely on state stored in instance variables, you may need to reset that state in @BeforeEach or @AfterEach methods.

    Depending on how often you need that feature, I would rather go with a custom extension.