5.1 @ParameterizedTest 註解
有時您只想使用不同的參數多次調用測試:不同的值、不同的輸入參數、不同的用戶名。JUnit 旨在讓您的生活更輕鬆,因此對於這種情況,它具有參數化測試這樣的東西。
要使用參數化測試,您需要再添加一個依賴項到您的pom.xml
:
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>5.8.2</version>
<scope>test</scope>
</dependency>
那麼我們可以考慮一個例子:
@ParameterizedTest
@ValueSource(ints = { 1, 2, 3 })
void testMethod(int argument) {
//test code
}
@ParameterizedTest
@ValueSource(ints = { 1, 2, 3 })
void testMethodWithAutoboxing(Integer argument) {
//test code
}
每個測試方法都會被調用3次,每次調用都會傳遞另一個參數給它。值是使用另一個註解 - @ValueSource設置的。但關於它還需要多說幾句。
5.2 @ValueSource 註解
@ValueSource註釋非常適合處理基元和文字。只需列出以逗號分隔的參數值,測試將為每個值調用一次。
@ParameterizedTest
@ValueSource(ints = { 1, 2, 3 })
void testMethodWithAutoboxing(Integer argument) {
//test code
}
但也有一個缺點——這個註解不支持 null,所以你需要為它使用一個特殊的拐杖—— @NullSource。它看起來像這樣:
@ParameterizedTest
@NullSource
void testMethodNullSource(Integer argument) {
assertTrue(argument == null);
}
5.3 @EnumSource 註解
還有一個特殊的註解@EnumSource,它將特定 Enum 的所有值傳遞給方法。它的應用程序如下所示:
enum Direction {
EAST, WEST, NORTH, SOUTH
}
@ParameterizedTest
@EnumSource(Direction.class)
void testWithEnumSource(Direction d) {
assertNotNull(d);
}
5.4 @MethodSource註解
但是如何將對像作為參數傳遞呢?特別是如果他們有復雜的構造算法。為此,您可以簡單地指定一個特殊的輔助方法,該方法將返回此類值的列表 (Stream)。
例子:
@ParameterizedTest
@MethodSource("argsProviderFactory")
void testWithMethodSource(String argument) {
assertNotNull(argument);
}
static Stream<String> argsProviderFactory() {
return Stream.of("one", "two", "three");
}
具有多個參數的參數化測試
當然,您已經想知道如果要將多個參數傳遞給該方法該怎麼辦。對此有一個非常酷的@CSVSource註釋。它允許您列出方法參數的值,簡單地用逗號分隔。
例子:
@ParameterizedTest
@CsvSource({
"alex, 30, Programmer, Working",
"brian, 35, Tester, Working",
"charles, 40, manager, kicks"
})
void testWithCsvSource(String name, int age, String occupation, String status) {
//method code
}
GO TO FULL VERSION