![](/img/trans.png)
[英]How to test different implementations for an interface in Junit5 without duplicating the code
[英]Junit5 test multiple implementations of the same interface
我在 IAdder.java 中有以下代碼:
public interface IAdder {
int add(int a, int b);
}
然后是以下實現(一個在 SimpleAdder.java 中,另一個在 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);
}
}
現在我想用 Junit5 進行測試,所以我開始在 SimpleAddertest.java 中編寫以下內容:
import org.junit.jupiter.api.Test;
進口 static org.junit.jupiter.api.Assertions.*;
class SimpleAdderTest {
IAdder ia = new SimpleAdder();
@Test
void add() {
assertEquals(10, ia.add(7, 3));
}
}
為了測試 AbsAdder,我可以添加以下測試 class AbsAdderTest:
import org.junit.jupiter.api.Test;
進口 static org.junit.jupiter.api.Assertions.*;
class AbsAdderTest {
IAdder ia = new AbsAdder();
@Test
void add() {
assertEquals(10, ia.add(7, 3));
}
}
在 Junit5 中避免這種代碼重復的最佳方法是什么? 我在 SO 上看過其他帖子,但沒有人以簡單的方式回答這個簡單的問題。
您可以使用@ParameterizedTest
,您可以在其中傳遞實現和測試用例,例如
@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)
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.