JUnit 参数化测试

– Start
JUnit 还支持参数化测试。

package demo16;

import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.ArgumentsProvider;
import org.junit.jupiter.params.provider.ArgumentsSource;
import org.junit.jupiter.params.provider.CsvFileSource;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.EmptySource;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.NullAndEmptySource;
import org.junit.jupiter.params.provider.NullSource;
import org.junit.jupiter.params.provider.ValueSource;

class ParameterizedTestDemo {

	@ParameterizedTest
	@ValueSource(strings = { "a", "b", "c" })
	void testMethod1(String v) {
		System.out.println("testMethod1=" + v);
	}

	@ParameterizedTest
	@NullSource
	void testMethod2(String v) {
		System.out.println("testMethod2=" + v);
	}

	@ParameterizedTest
	@EmptySource
	void testMethod3(String v) {
		System.out.println("testMethod3=" + v);
	}

	@ParameterizedTest
	@NullAndEmptySource
	void testMethod4(String v) {
		System.out.println("testMethod4=" + v);
	}

	@ParameterizedTest
	@EnumSource(TimeUnit.class)
	void testMethod5(TimeUnit v) {
		System.out.println("testMethod5=" + v);
	}

	@ParameterizedTest
	@MethodSource("stringProvider")
	void testMethod6(String v) {
		System.out.println("testMethod6=" + v);
	}

	static Stream stringProvider() {
		return Stream.of("apple", "banana");
	}

	@ParameterizedTest
	@CsvSource({ "1,zhangsan", "2,lisi" })
	void testMethod7(Integer id, String name) {
		System.out.println("testMethod7=" + id + ", " + name);
	}

	@ParameterizedTest
	@CsvFileSource(resources = "People.csv", numLinesToSkip = 1)
	void testMethod8(Integer id, String name) {
		System.out.println("testMethod8=" + id + ", " + name);
	}

	@ParameterizedTest
	@ArgumentsSource(MyArgumentsProvider.class)
	void testMethod9(String v) {
		System.out.println("testMethod9=" + v);
	}

	static class MyArgumentsProvider implements ArgumentsProvider {
		public Stream provideArguments(ExtensionContext context) throws Exception {
			return Stream.of("apple", "banana").map(Arguments::of);
		}
	}

}

– 更多参见:JUnit 精萃
– 声 明:转载请注明出处
– Last Updated on 2019-08-12
– Written by ShangBo on 2019-08-12
– End

你可能感兴趣的:(JUnit)