【问题标题】:JUnit - Share Tests Of Different Implementations [closed]JUnit - 共享不同实现的测试 [关闭]
【发布时间】:2018-09-18 16:00:04
【问题描述】:
【问题讨论】:
标签:
java
unit-testing
junit
junit4
junit5
【解决方案1】:
对测试进行参数化似乎仍然是此类用例的教科书解决方案。不过,JUnit Jupiter's syntax 确实让它更优雅一点。 API 非常清晰,恕我直言(测试有参数,注释显示它们来自哪里):
public class ListTest {
public static Stream<List<String>> lists() {
return Stream.of(new ArrayList<>(), new LinkedList<>());
}
@ParameterizedTest
@MethodSource("lists")
public void testAdd(List<String> list) {
list.add("xyz");
assertEquals(1, list.size());
assertFalse(list.isEmpty());
assertEquals("xyz", list.get(0));
}
}
【解决方案2】:
可能不是最类似于 Java 的,但您可以遵循表驱动的测试格式。使用本地类,以保持测试的可读性,并使上下文尽可能接近真实测试。
注意:这与@RunWith(Parameterized.class) 的底层高级方法非常相似
// Assuming Animal interface has a `public boolean canDance()`
@Test
public void TestAnimalCanDance() {
class Tester {
String errMsgFmt = "%s failed the test";
boolean expected;
Animal animal;
public Tester(boolean expected, Animal animal) {
this.expected = expected;
this.animal = animal;
}
}
Tester dog = new Tester(true, new Dog());
Tester cat = new Tester(false, new Cat());
Tester monkey = new Tester(false, new Monkey());
Tester[] tests = Arrays.asList(dog, cat, monkey);
for (Tester t: tests) {
boolean actual = t.canDance();
assertTrue(actual == t.expected);
}
}