参数化测试 junit

JUnit Parameterized Tests allow us to run a test method multiple times with different arguments. JUnit 5 provides a lot of ways to pass parameters to a test method.

JUnit参数化测试允许我们使用不同的参数多次运行测试方法。 JUnit 5提供了许多将参数传递给测试方法的方法。

JUnit参数化测试 (JUnit Parameterized Tests)

We need following additional dependency to use parameterized tests in our test cases.

我们需要遵循其他依赖关系才能在测试案例中使用参数化测试。

<dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-params</artifactId><version>5.2.0</version><scope>test</scope>
</dependency>

We have to use @ParameterizedTest with the test method instead of generic @Test annotation.

我们必须将@ParameterizedTest与测试方法一起使用,而不是常规的@Test批注。

We also have to provide a source that will generate the arguments for the method. There are many types of sources we can define and use in our parameterized test methods.

我们还必须提供一个将为该方法生成参数的源。 我们可以在参数化测试方法中定义和使用多种类型的源。

使用@ValueSource的JUnit参数化测试 (JUnit Parameterized Test with @ValueSource)

This is the simplest form of parameterized test, we can use @ValueSource to pass the arguments array. We can pass primitive data types array, string array or class array using ValueSource annotation.

这是参数化测试的最简单形式,我们可以使用@ValueSource传递arguments数组。 我们可以使用ValueSource批注传递基本数据类型数组,字符串数组或类数组。

@ParameterizedTest
@ValueSource(ints = { 1, 2, 3 })
void test_ValueSource(int i) {System.out.println(i);
}@ParameterizedTest
@ValueSource(strings = { "1", "2", "3" })
void test_ValueSource_String(String s) {assertTrue(Integer.parseInt(s) < 5);
}

JUnit @ParameterizedTest与@EnumSource (JUnit @ParameterizedTest with @EnumSource)

@EnumSource allows us to pass Enums to our test methods.

@EnumSource允许我们将枚举传递给我们的测试方法。

@ParameterizedTest
@EnumSource(ElementType.class)
void test_EnumSource(ElementType et) {System.out.println(et);
}

If we want only specific values from the Enum, we can do that using EnumSource name parameter.

如果只需要Enum中的特定值,则可以使用EnumSource name参数来实现。

@ParameterizedTest
@EnumSource(value = ElementType.class, names = { "TYPE", "METHOD", "FIELD" })
void test_EnumSource_Extended(ElementType et) {assertTrue(EnumSet.of(ElementType.FIELD, ElementType.TYPE, ElementType.METHOD).contains(et));
}

使用@MethodSource的JUnit @ParameterizedTest (JUnit @ParameterizedTest with @MethodSource)

We can use @MethodSource to specify a factory method for test arguments. This method can be present in the same class or any other class too. The factory method should be static and return Strem, Iterator, Iterable or array of elements.

我们可以使用@MethodSource为测试参数指定工厂方法。 此方法可以存在于同一类或任何其他类中。 工厂方法应该是静态的,并返回Strem,Iterator,Iterable或元素数组。

@ParameterizedTest
@MethodSource("ms")
void test_MethodSource(String s) {assertNotNull(s);
}static Stream<String> ms() {return Stream.of("A", "B");
}

We can also use MethodSource to pass multiple parameters to the test method. In this case, we will have to use Arguments API. Let’s define a separate class with factory method source.

我们还可以使用MethodSource将多个参数传递给测试方法。 在这种情况下,我们将不得不使用Arguments API。 让我们用工厂方法源定义一个单独的类。

package com.journaldev.parameterizedtests;import java.util.stream.Stream;import org.junit.jupiter.params.provider.Arguments;public class MethodSources {public static Stream<Arguments> msMP() {return Stream.of(Arguments.of(1, "A"), Arguments.of(2, "B"), Arguments.of(3, "C"));}
}

Corresponding JUnit parameterized test method would be defined as:

相应的JUnit参数化测试方法将定义为:

@ParameterizedTest
@MethodSource("com.journaldev.parameterizedtests.MethodSources#msMP")
void test_MethodSource_MultipleParams(int i, String s) {assertTrue(4 > i);assertTrue(Arrays.asList("A", "B", "C").contains(s));
}

JUnit MethodSource is very similar to TestNG DataProvider annotation.

JUnit MethodSource与TestNG DataProvider批注非常相似。

JUnit @ParameterizedTest与@CsvSource (JUnit @ParameterizedTest with @CsvSource)

We can also pass CSV values to the test method. We can specify the delimiter for multiple arguments in the test method.

我们还可以将CSV值传递给测试方法。 我们可以在测试方法中为多个参数指定分隔符。

@ParameterizedTest
@CsvSource(delimiter='|', value= {"1|'A'","2|B"})
void test_CsvSource(int i, String s) {assertTrue(3 > i);assertTrue(Arrays.asList("A", "B", "C").contains(s));
}

带有CSV文件的JUnit参数化测试 (JUnit Parameterized Test with CSV File)

We can use @CsvFileSource annotation to pass CSV data from a file to the parameterized test method. We can skip the header rows and define our custom delimiter too.

我们可以使用@CsvFileSource批注将CSV数据从文件传递到参数化的测试方法。 我们可以跳过标题行,也可以定义我们的自定义定界符。

Let’s say we have country_code.csv file defined as:

假设我们将country_code.csv文件定义为:

Country,TelephoneCode
USA,1
India,91

Here is the test method where CSV file data will be used for arguments mapping.

这是将CSV文件数据用于参数映射的测试方法。

@ParameterizedTest
@CsvFileSource(resources = "/country_code.csv", numLinesToSkip = 1)
void test_CsvFileSource(String country, int code) {assertNotNull(country);assertTrue(0 < code);
}

带对象的JUnit参数化测试 (JUnit Parameterized Tests with Objects)

So far we have used primitives and strings in our examples, but in real life, we have to pass objects most of the times. We can use @MethodSource to achieve this functionality.

到目前为止,我们在示例中使用了基元和字符串,但是在现实生活中,大多数时候我们都必须传递对象。 我们可以使用@MethodSource来实现此功能。

Let’s say we have a Book class defined as:

假设我们有一个Book类定义为:

class Book {private String title;// standard getter setterspublic Book(String t) {this.title = t;}@Overridepublic String toString() {return title;}
}

Now we can pass Book object to our test methods using below factory method.

现在,我们可以使用以下工厂方法将Book对象传递给我们的测试方法。

static Book[] mpBooks() {return new Book[] {new Book("Harry Potter"), new Book("Five Point Someone")};
}@ParameterizedTest
@MethodSource("mpBooks")
void test_MethodSource_Objects(Book b) {assertNotNull(b.getTitle());
}

Notice that this time I am returning an array of Books, earlier I was returning Stream of elements.

请注意,这一次我返回的是Book数组,之前我返回的是元素流。

JUnit参数化测试参数验证 (JUnit Parameterized Tests Arguments Verification)

If you are running test cases through Eclipse, you can check method arguments to make sure correct values are being passed to the parameterized tests.

如果要通过Eclipse运行测试用例,则可以检查方法参数以确保将正确的值传递给参数化测试。

JUnit测试方法参数转换 (JUnit Test Methods Argument Conversion)

JUnit provides built-in support for many type converters. Some of them are int to long, string to boolean and vice versa, string to enum, date time objects. Below code will also work and JUnit will automatically call our Book class constructor to convert String values to Book object.

JUnit为许多类型转换器提供内置支持。 其中一些是int到long,字符串是boolean,反之亦然,字符串是enum,日期时间对象。 下面的代码也将起作用,并且JUnit将自动调用我们的Book类构造函数以将String值转换为Book对象。

@ParameterizedTest
@ValueSource(strings = {"Harry Potter", "Hamlet"})
void test_ValueSource_Objects(Book b) {assertNotNull(b.getTitle());
}

However, this could lead to errors when test cases are executed if our Book class constructor changes. It’s better to use MethodSource and provide our own mechanism for object creation.

但是,如果更改Book类的构造函数,则在执行测试用例时可能会导致错误。 最好使用MethodSource并提供我们自己的对象创建机制。

摘要 (Summary)

JUnit Parameterized Tests were a much-needed feature and it’s good to see so many options to provide arguments to our test methods.

JUnit参数化测试是急需的功能,很高兴看到这么多选项为我们的测试方法提供了参数。

GitHub Repository.GitHub Repository上查看带有完整示例的JUnit示例项目。

翻译自: https://www.journaldev.com/21639/junit-parameterized-tests

参数化测试 junit

参数化测试 junit_JUnit参数化测试相关推荐

  1. 参数化测试 junit_JUnit 5 –参数化测试

    参数化测试 junit JUnit 5令人印象深刻,尤其是当您深入研究扩展模型和体系结构时 . 但是从表面上讲,编写测试的地方,开发的过程比革命的过程更具进化性 – JUnit 4上没有杀手级功能吗? ...

  2. 【Java单元测试】如何进行单元测试、异常测试、参数化测试、超时测试、测试多线程

    Junit单元测试的步骤 (1)新建一个单元测试 (2)选择位置 (3)选择需要测试的方法 (4)是否将Junit 4添加到ClassPath中 (5)自动生成的测试类 (6) 然后就可以编写单元测试 ...

  3. Jmeter压力测试_token参数化

    Jmeter压力测试_token参数化 简单的压力测试大家基本都知道了,接下来我就讲下怎么做token参数化 一.查看登录成功后返回值. 正如下方图片所展示的,我这里的tokenMap就是token ...

  4. 11、pytest -- 测试的参数化

    目录 1. @pytest.mark.parametrize标记 1.1. empty_parameter_set_mark选项 1.2. 多个标记组合 1.3. 标记测试模块 2. pytest_g ...

  5. 软件测试参数化的作用,Pytest之测试的参数化

    在实际工作中,测试用例可能需要支持多种场景,我们可以把和场景强相关的部分抽象成参数,通过对参数的赋值来驱动用例的执行: 参数化的行为表现在不同的层级上: fixture的参数化:参考 4.fixtur ...

  6. 测试框架 如何测试私有方法_高效的企业测试–测试框架(5/6)

    测试框架 如何测试私有方法 本系列文章的这一部分将介绍测试框架以及我在何时以及是否应用它们方面的想法和经验. 关于测试框架的想法 我对大多数测试框架不太满意的原因是,按照我的观点,它们大多增加了语法上 ...

  7. 四款主流测试工具的测试流程

    主流测试工具的测试流程 WinRunner 1 启动时选择要加载的插件 2 进行一些设置(如录制模式等) 3 识别应用程序的GUI,即创建map(就是学习被测试软件的界面) 4 建立测试脚本(录制及编 ...

  8. 一年时间,从一个浑浑噩噩的测试小人物到测试主管的成长之路

    目录 关于自动化测试我的个人意见 一.测试基础 二.Linux必备知识 三.Shell脚本 四.互联网程序原理 五.MySQL数据库 六.抓包工具 七.接口测试工具 八.Web自动化测试Java&am ...

  9. 【高性能】Web性能压力测试JMeter、测试秒杀Red

    高性能问题 内容管理 JMeter web性能测试 JMeter配置原件 取样器 Sampler 配置原件 config Element 逻辑控制器 Logic Controller 前置处理器 Pr ...

最新文章

  1. 如何在空硬盘Linux系统,Linux系统如何新增一块硬盘
  2. chemdraw怎么画拐弯的箭头_性感皮衣皮裤的质感服装该怎么画?
  3. DL之DCGAN:基于keras框架利用深度卷积对抗网络DCGAN算法对MNIST数据集实现图像生成
  4. 小额贷款利息违法吗?
  5. STM32串口的使用(原理、结构体、库函数、串口发送字符(串)、重定向printf串口发送、串口中断接收控制灯)
  6. java行情一年比一年差_推动Java前进? 一个定义。 一年回顾。
  7. 开发第一个spring boot应用
  8. [下载地址] Subclipse 1.10.9(SVN) _附说明
  9. 共迎海量数据库管理挑战 中韩数据库专家对话北京
  10. python模块:数字处理
  11. C语言中获得本地日期
  12. 【车间调度】基于matlab GUI遗传算法求解车间调度问题【含Matlab源码 049期】
  13. python3安装M2Crypto模块
  14. 人工智能Java SDK: BIGGAN 图像自动生成
  15. python 期货策略_Python版商品期货跨期布林对冲策略.md
  16. 大厂纷纷押宝“元宇宙”“鸡肋”智能眼镜难成密钥
  17. 1.投骰子的随机游戏
  18. demo:猜数字小游戏
  19. 用c语言程序判断谁是小偷
  20. Excel也能调用HFSS?

热门文章

  1. ubuntu下安装beanstalkd
  2. Java程序练习-长整数加法运算
  3. [转载] Python中生成器和迭代器的区别
  4. [转载] Python中的numpy linalg模块
  5. [转载] Python 主成分分析PCA
  6. [转载] C语言C++指针与java中引用的一点对此
  7. MySQL之存储引擎,数据类型,约束条件
  8. Python:Django 项目中可用的各种装备和辅助
  9. python进程问题
  10. 简单解决 WIN10更新后 远程桌面提示 CredSSP加密Oracle修正的问题