Search code examples
javajunitjunit5junit-jupiter

How to conditionally run parameterized tests in JUnit5?


Exactly I mean tag @EnabledIfSystemProperty using with @ParameterizedTest tag.

When I use @EnabledIfSystemProperty with @Test, the test method is being disabled and after tests run it is grayed out on the list (as I expect):

@Test
@EnabledIfSystemProperty(named = "env", matches = "test")
public void test() {
    System.out.println("Only for TEST env");
}

Whereas I use @EnabledIfSystemProperty with @ParameterizedTest, the test is green on the list after tests run but it is not actually executed:

@ParameterizedTest
@EnabledIfSystemProperty(named = "env", matches = "test")
@ValueSource(strings = {"testData.json", "testData2.json"})
public void test(String s) {
    System.out.println("Only for TEST env");
}

I execute tests from IntelliJ IDEA.
I need the test to be grayed out on the list. Any ideas? Thanks...


Solution

  • You could move the parameterized test to a @Nested test and apply the condition to it:

    @Nested
    @EnabledIfSystemProperty(named = "env", matches = "test")
    class Inner {
        @ParameterizedTest
        @ValueSource(strings = {"testData.json", "testData2.json"})
        public void test(String s) {
            System.out.println("Only for TEST env: " + s);
        }
    }