divinedragon
divinedragon

Reputation: 5336

Run specific JUnit tests multiple times, but exclude others from running multiple times

I am using Parameterized JUnit runner to run some of my tests multiple times. Here is the template of my test class

@RunWith(value = Parameterized.class)
public class TestClass {

    private String key;
    private boolean value;

    public TestClass(String key, boolean value) {
        this.key = key;
        this.value = value;
    }

    @Parameters
    public static Collection<Object[]> data() {
        Object[][] data = new Object[][] {
            {"key1", true},
            {"key2", true},
            {"key3", false}
        };
        return Arrays.asList(data);
    }

    @Test
    public void testKeys() {
        ...
    }

    @Test
    public void testValues() {
        ...
    }

    @Test
    public void testNotRelatedKeyValue() {
    }
}

Now, I want my test methods - testKeys(), testValues() to run with different parameter values which they are running.

However, I my last method - testNotRelatedKeyValue() is also executing that many times along with other parameterized tests.

I don't want testNotRelatedKeyValue() to run multiple times, but just once.

Is it possible in this class or would I need to create a new test class?

Upvotes: 0

Views: 557

Answers (1)

Stefan Birkner
Stefan Birkner

Reputation: 24510

You could structure your test with the Enclosed runner.

@RunWith(Enclosed.class)
public class TestClass {

    @RunWith(Parameterized.class)
    public static class TheParameterizedPart {
        @Parameter(0)
        public String key;

        @Parameter(1)
        private boolean value;

        @Parameters
        public static Object[][] data() {
            return new Object[][] {
                {"key1", true},
                {"key2", true},
                {"key3", false}
            };
        }

        @Test
        public void testKeys() {
            ...
        }

        @Test
        public void testValues() {
            ...
        }
    }

    public static class NotParameterizedPart {
        @Test
        public void testNotRelatedKeyValue() {
            ...
        }
    }
}

Upvotes: 2

Related Questions