以函数接口作为源值的java参数化JUnit5测试

lqfhib0f  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(301)

我可以用功能接口作为源值来参数化测试吗?
我正在以这种方式测试具有多个字段的记录:

@Test
void instantiateWithInvalidName() {
    thenThrowsIAE(() -> Sample.withName(""));
    thenThrowsIAE(() -> Sample.withName(BLANK_STRING));
    thenThrowsNPE(() -> Sample.withName(null));
}

@Test
void instantiateWithInvalidAddress() {
    thenThrowsIAE(() -> Sample.withAddress(""));
    thenThrowsIAE(() -> Sample.withAddress(BLANK_STRING));
    thenThrowsNPE(() -> Sample.withAddress(null));
}    
// ...
    private static NullPointerException thenThrowsNPE(Executable exec) {
    return assertThrows(NullPointerException.class, exec);
}

private static IllegalArgumentException thenThrowsIAE(Executable exec) {
    return assertThrows(IllegalArgumentException.class, exec);
}

我想这样做:

@ParameterizedTest
@ValueSource(classes = { Sample::withName, Sample::withAddress }) 
void instantiateWithInvalidField() {
    thenThrowsIAE(() -> func.apply(""));
    thenThrowsIAE(() -> func.apply(BLANK_STRING));
    thenThrowsNPE(() -> func.apply(null));
}

我知道我可以通过参数:“”、空白字符串和null以另一种方式完成。但我想一场一场地做测试。我认为它更具可读性。

1rhkuytd

1rhkuytd1#

我想你可以试试这样的smth:

@ParameterizedTest
    @MethodSource("provideTestData")
    void instantiateWithInvalidField(Function<String, String> func) {
        thenThrowsIAE(() -> func.apply(""));
        thenThrowsIAE(() -> func.apply(" "));
        thenThrowsNPE(() -> func.apply(null));
    }

    private static Stream<Function<String, String>> provideTestData() {
        return Stream.of(Sample::withAddress, Sample::withName);
    }

我不知道,你的 withAddresswithName 方法返回,我假设 String 因此我采取了 String 作为第二通用 Function<String, String> func .

相关问题