我想用一种方法的一种参数化测试来测试所有不同的异常。因此,这意味着Exception1.class,Exception2.class应该是参数。如何参数化它们?
假设您的测试方法根据场景返回不同的异常,则应该同时对夹具(对于场景)和预期参数(对于异常)进行参数化。
用如下Foo.foo(String input)
方法进行测试:
import java.io.FileNotFoundException;
public class Foo {
public void foo(String input) throws FileNotFoundException {
if ("a bad bar".equals(input)){
throw new IllegalArgumentException("bar value is incorrect");
}
if ("inexisting-bar-file".equals(input)){
throw new FileNotFoundException("bar file doesn't exit");
}
}
}
它可能看起来像:
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.api.Assertions;
public class FooTest {
@ParameterizedTest
@MethodSource("fooFixture")
void foo(String input, Class<Exception> expectedExceptionClass, String expectedExceptionMessage) {
Assertions.assertThrows(
expectedExceptionClass,
() -> new Foo().foo(input),
expectedExceptionMessage
);
}
private static Stream<Arguments> fooFixture() {
return Stream.of(
Arguments.of("a bad bar", IllegalArgumentException.class, "bar value is incorrect"), Arguments.of("inexisting-bar-file", FileNotFoundException.class, "bar file doesn't exit"));
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句