我可以用功能接口作为源值来参数化测试吗?
我正在以这种方式测试具有多个字段的记录:
@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以另一种方式完成。但我想一场一场地做测试。我认为它更具可读性。
1条答案
按热度按时间1rhkuytd1#
我想你可以试试这样的smth:
我不知道,你的
withAddress
及withName
方法返回,我假设String
因此我采取了String
作为第二通用Function<String, String> func
.