2024年4月15日发(作者:)

JUnit4中的参数化测试

文章分类:Java编程

为了保证单元测试的严谨性,我们模拟了不同的测试数据来测试方法的处理能力,为

此我们编写了大量的单元测试方法。这些测试方法都是大同小异:代码结构都是相同的,

不同的仅仅是测试数据和期望值。为了解决这个问题,Junit4提供了参数化测试。

1)为准备使用参数化测试的测试类指定特殊的运行器,

terized

2)为测试声明几个变量,非别用于存放期望值和测试所用数据。

3)为测试了类声明一个使用注解ters修饰

的,返回值为tion的公共静态方法,并在此方法中初始化所有需要的测试

的参数对。

4)为测试类声明一个带有参数的公共构成函数,并在其中为第二个环节中声明的几个

变量赋值。

下面是一个测试加法的参数化测试,测试通过程序计算 1+2=3? 0+0=0? -1-3=-4?

Java代码

1. package 4;

2. import static Equals;

3. import ;

4. import tion;

5. import ;

6. import h;

7. import terized;

8. import ters;

9. /**

10. * 参数化设置

11. *

12. * 1 测试类必须由parameterized测试运行器修饰

13. * 2 准备数据,数据的准备需要在一个方法中进行,该方法需要满足一定的要求

14. * 1)该方法必须有parameters注解修饰

15. * 2)该方法必须为public static的

16. * 3)该方法必须返回Collection类型

17. * 4)该方法的名字不作要求

18. * 5)该方法没有参数

19. *

20. * == !=

21. */

22. // 测试运行器

23. @RunWith()

24. public class ParameterTest {

25. private int expeted;

26. private int input1;

27. private int input2;

28.

29. @Parameters

30. @SuppressWarnings("unchecked")

31. public static Collection perpareData() {

32. Object[][] objects = { {3,1,2}, {0,0,0}, {-4,-1,-3} };

33.

34. return (objects);

35. }

36.

37. public ParameterTest(int expected, int input1, int input2){

38. d = expected;

39. 1 = input1;

40. 2 = input2;

41. }

42.

43. @Test public void testAdd() {

44. Calculator cal = new Calculator();

45. assertEquals(expeted, (input1, input2));

46. }

47. }