gpt4 book ai didi

junit4 - 使用相同的测试测试多个接口(interface)实现 - JUnit4

转载 作者:行者123 更新时间:2023-12-03 15:02:11 25 4
gpt4 key购买 nike

我想为不同的接口(interface)实现运行相同的 JUnit 测试。我使用 @Parameter 选项找到了一个不错的解决方案:

public class InterfaceTest{

MyInterface interface;

public InterfaceTest(MyInterface interface) {
this.interface = interface;
}

@Parameters
public static Collection<Object[]> getParameters()
{
return Arrays.asList(new Object[][] {
{ new GoodInterfaceImpl() },
{ new AnotherInterfaceImpl() }
});
}
}

该测试将运行两次,首先使用 GoodInterfaceImpl 然后使用 AnotherInterfaceImpl 类。但问题是大多数测试用例都需要一个新对象。一个简化的例子:
@Test
public void isEmptyTest(){
assertTrue(interface.isEmpty());
}

@Test
public void insertTest(){
interface.insert(new Object());
assertFalse(interface.isEmpty());
}

如果 isEmptyTest insertTest 之后运行,则会失败。

是否可以选择使用新的实现实例自动运行每个测试用例?

顺便说一句:为接口(interface)实现 clear() 或 reset() 方法并不是一个真正的选择,因为我在生产代码中不需要它。

最佳答案

这是模板方法模式的另一种方法:

面向接口(interface)的测试进入基类:

public abstract class MyInterfaceTest {

private MyInterface myInterface;

protected abstract MyInterface makeContractSubject();

@Before
public void setUp() {
myInterface = makeContractSubject();
}

@Test
public void isEmptyTest(){
assertTrue(myInterface.isEmpty());
}

@Test
public void insertTest(){
myInterface.insert(new Object());
assertFalse(myInterface.isEmpty());
}
}

对于每个具体类,定义一个具体的测试类:
public class GoodInterfaceImplTest extends MyInterfaceTest {

@Override
protected MyInterface makeContractSubject() {
// initialize new GoodInterfaceImpl
// insert proper stubs
return ...;
}

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

与@Parameter 相比的一个轻微优势是,您可以在测试失败时获得报告的具体测试类的名称,因此您可以立即知道哪个实现失败了。

顺便说一句,为了让这种方法完全起作用,接口(interface)的设计方式必须只允许通过接口(interface)方法进行测试。这意味着基于状态的测试——您无法在基础测试类中验证模拟。如果您需要在特定于实现的测试中验证模拟,这些测试必须进入具体的测试类。

关于junit4 - 使用相同的测试测试多个接口(interface)实现 - JUnit4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11080168/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com