为接口的多种实现编写单个单元测试 [英] Writing a single unit test for multiple implementations of an interface

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

问题描述

我有一个接口List,其实现包括单链接列表,双精度,循环等.我为单精度编写的单元测试应该对大多数双精度以及环形以及接口的任何其他新实现都有利.因此,JUnit不会为每个实现重复执行单元测试,而是提供一些内置的功能,让我进行一个JUnit测试并针对不同的实现运行它吗?

I have an interface List whose implementations include Singly Linked List, Doubly, Circular etc. The unit tests I wrote for Singly should do good for most of Doubly as well as Circular and any other new implementation of the interface. So instead of repeating the unit tests for every implementation, does JUnit offer something inbuilt which would let me have one JUnit test and run it against different implementations?

使用JUnit参数化测试,我可以提供不同的实现,例如单,双,循环等,但是对于每个实现,都使用相同的对象执行类中的所有测试.

Using JUnit parameterized tests I can supply different implementations like Singly, doubly, circular etc but for each implementation the same object is used to execute all the tests in the class.

推荐答案

在JUnit 4.0+中,您可以使用

With JUnit 4.0+ you can use parameterized tests:

  • 在测试装置中添加@RunWith(value = Parameterized.class)批注
  • 创建一个返回Collectionpublic static方法,并用@Parameters进行注释,然后将SinglyLinkedList.classDoublyLinkedList.classCircularList.class等放入该集合中
  • 向您的测试治具中添加一个采用Class:public MyListTest(Class cl)的构造函数,并将Class存储在实例变量listClass
  • setUp方法或@Before中,使用List testList = (List)listClass.newInstance();
  • Add @RunWith(value = Parameterized.class) annotation to your test fixture
  • Create a public static method returning Collection, annotate it with @Parameters, and put SinglyLinkedList.class, DoublyLinkedList.class, CircularList.class, etc. into that collection
  • Add a constructor to your test fixture that takes Class: public MyListTest(Class cl), and store the Class in an instance variable listClass
  • In the setUp method or @Before, use List testList = (List)listClass.newInstance();

在完成上述设置后,参数化的运行器将为您在@Parameters方法中提供的每个子类创建测试夹具MyListTest的新实例,从而使您可以为所使用的每个子类行使相同的测试逻辑需要测试.

With the above setup in place, the parameterized runner will make a new instance of your test fixture MyListTest for each subclass that you provide in the @Parameters method, letting you exercise the same test logic for every subclass that you need to test.

这篇关于为接口的多种实现编写单个单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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