使用相同的测试来测试多个接口实现-JUnit4 [英] Testing multiple interface implementations with same tests - JUnit4

查看:66
本文介绍了使用相同的测试来测试多个接口实现-JUnit4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to run the same JUnit tests for different interface implementations. I found a nice solution with the @Parameter option:

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 类.但是问题是我需要为大多数测试用例创建一个新对象.简化示例:

This test would be run twice, first with the GoodInterfaceImpl then with the AnotherInterfaceImpl class. But the problem is I need for most of the testcases a new object. A simplified example:

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

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

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

If the isEmptyTest is run after the insertTest it fails.

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

Is there an option to run automatically each testcase with a new instance of an implementation?

BTW:为接口实现 clear() reset()方法并不是真正的选择,因为在生产性代码中我不需要它.

BTW: Implementing a clear() or reset()-method for the interface is not really an options since I would not need it in productive code.

推荐答案

创建工厂接口和实现,如果在生产中不需要这样的东西,可能仅在测试层次结构中创建,并使getParameters()返回列表工厂.

Create a factory interface and implementations, possibly only in your test hierarchy if you don't need such a thing in production, and make getParameters() return a list of factories.

然后,您可以在@Before带注释的方法中调用工厂,以针对每次运行的测试方法获取要测试的实际类的新实例.

Then you can invoke the factory in a @Before annotated method to get a new instance of your actual class under test for each test method run.

这篇关于使用相同的测试来测试多个接口实现-JUnit4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆