Francesco Dassisis
Francesco Dassisis

Reputation: 142

Junit5 test multiple implementations of the same interface

I've got following code in IAdder.java:

public interface IAdder {

int add(int a, int b);

}

Then the following implementations (one in SimpleAdder.java and another in AbsAdder.java):

public class SimpleAdder implements IAdder {

@Override
public int add(int a, int b) {
    return a+b;
}

}

public class AbsAdder implements IAdder {

@Override
public int add(int a, int b) {
    return Math.abs(a) + Math.abs(b);
}

}

Now I want to test with Junit5 so I start writing the following in SimpleAddertest.java:

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

class SimpleAdderTest {

IAdder ia = new SimpleAdder();

@Test
void add() {
    assertEquals(10, ia.add(7, 3));
}

}

To test AbsAdder I could add the following test class AbsAdderTest:

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

class AbsAdderTest {

IAdder ia = new AbsAdder();

@Test
void add() {
    assertEquals(10, ia.add(7, 3));
}

}

What's the best way to avoid this code repetition in Junit5? I ve seen other posts on SO but no one answered this simple question in a simple way.

Upvotes: 2

Views: 980

Answers (1)

Silviu Burcea
Silviu Burcea

Reputation: 5348

You can use a @ParameterizedTest, where you can pass the implementation and the test cases, e.g.

@ParameterizedTest
@MethodSource("sourceMethod")
public void test(IAdder add, int a, int b, int expected) {
    assertEquals(expected, add.add(a, b));
}

public static Stream<Arguments> sourceMethod() {
    final SimpleAdder simpleAdder = new SimpleAdder();
    final AbsAdder absAdder = new AbsAdder();
    return Stream.of(
            Arguments.of(simpleAdder, 2, 3, 5),
            // add more test cases for SimpleAdder, e.g. 
            Arguments.of(simpleAdder, 2, 0, 2),
            Arguments.of(simpleAdder, 0, 4, 4),
            Arguments.of(absAdder, -2, -5, 7),
            // add more test cases for AbsAdder, e.g. 
            Arguments.of(absAdder, -2, 0, 2),
            Arguments.of(absAdder, 0, -9, 9)
    );
}

Upvotes: 2

Related Questions