Skip to content
Advertisement

Run same Junit Test with multiple objects derived from same interface

I am trying to improve my knowledge about testing I’m trying to achieve running the same JUnit test class with different objects derived from the same interface.

so we can assume the following:

interface Base {
    void sort();
}

class  A implements Base {
    @Override
    public void sort() {
        //sort naively
    }
}

class  B implements Base {
    @Override
    public void sort() {
        //sort using another better approach
    }
}

class  C implements Base {
    @Override
    public void sort() {
        //sort using optimized approach
    }
}
class Test {
    @Test
    void test1() {

        Base obj = new A();
        obj.sort();
        obj.otherStuff();
    }
}
class SecondTest {
//trying to avoid making multiple test classes that has only one line in difference
@Test
void test1() {
    var obj = new B();
    obj.sort();
    obj.otherStuff();
}

So my question is how to run the test class with the objects from A,B,C without falling into the trap of duplicate code and redundancy?

Please note that I wrote this example just to illustrate my point, and the sort() doStuff() methods are just placeholders but when you have over ~70 line of code duplication in each test class it starts to look ugly and redundant.

*I have looked at @beforeEach, @Before, @After and I don’t think I see a way where those might help me.

Advertisement

Answer

You can write a parameterized test with a MethodSource.

@ParameterizedTest
@MethodSource("bases")
void test1(Base obj) {
  obj.sort();
  obj.otherStuff();
}

static Stream<String> bases() {
  return Stream.of(new A(), new B(), new C());
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement