参数化测试 junit_JUnit参数化测试

参数化测试 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 setters
 
	public Book(String t) {
		this.title = t;
	}
	
	@Override
	public 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 RepositoryGitHub Repository上查看带有完整示例的JUnit示例项目。

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

参数化测试 junit

private static Stream<Arguments> productList(){

     return Stream.of(

                 arguments("{\"responseCode\":\"100"\,\"returnCode\":\"00"\,\"data\":"123"}","{\"responseCode\":\"100"\,\"returnCode\":\"00"\,\"data\":"456"}","{\"responseCode\":\"100"\,\"returnCode\":\"00"\,\"data\":"789"}"),

                arguments("{\"responseCode\":\"200"\,\"returnCode\":\"01"\,\"data\":"123"}","{\"responseCode\":\"200"\,\"returnCode\":\"01"\,\"data\":"456"}","{\"responseCode\":\"200"\,\"returnCode\":\"01"\,\"data\":"789"}"),

                arguments("{\"responseCode\":\"100"\,\"returnCode\":\"01"\,\"data\":"123"}","{\"responseCode\":\"100"\,\"returnCode\":\"01"\,\"data\":"456"}","{\"responseCode\":\"100"\,\"returnCode\":\"01"\,\"data\":"789"}"),

    )

}

@ParameterizedTest

@MethodSource("productList")

void getAllLanguageProductList(String enUsProductList,String zhHkProductList,String zhCnProductList){

}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值