Java 如何使用hemcrest参数化JUnit5中的异常?
我想用一个参数化测试测试所有不同的异常,使用hemcrest测试一个方法。这意味着Exception1.class,Exception2.class应该是参数。如何对它们进行参数化,并使用hemcrest进行参数化?假设您的测试方法根据场景返回不同的异常,您应该对fixture(场景)和expected(异常)进行参数化 使用Java 如何使用hemcrest参数化JUnit5中的异常?,java,exception,junit5,parametrized-testing,Java,Exception,Junit5,Parametrized Testing,我想用一个参数化测试测试所有不同的异常,使用hemcrest测试一个方法。这意味着Exception1.class,Exception2.class应该是参数。如何对它们进行参数化,并使用hemcrest进行参数化?假设您的测试方法根据场景返回不同的异常,您应该对fixture(场景)和expected(异常)进行参数化 使用Foo.Foo(字符串输入)方法进行测试,例如: import java.io.FileNotFoundException; public class Foo { p
Foo.Foo(字符串输入)
方法进行测试,例如:
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"));
}
}
import java.io.FileNotFoundException;
导入java.io.IOException;
导入java.util.stream.stream;
导入org.junit.jupiter.params.ParameterizeTest;
导入org.junit.jupiter.params.provider.Arguments;
导入org.junit.jupiter.params.provider.MethodSource;
导入org.junit.jupiter.api.Assertions;
公务舱{
@参数化测试
@MethodSource(“fooFixture”)
void foo(字符串输入,类expectedExceptionClass,字符串expectedExceptionMessage){
Assertions.assertThrows(
expectedExceptionClass,
()->new Foo().Foo(输入),
expectedExceptionMessage
);
}
私有静态流fooFixture(){
回流(
Arguments.of(“坏条”,IllegalArgumentException.class,“条值不正确”),Arguments.of(“不存在条文件”,FileNotFoundException.class,“条文件不退出”);
}
}
谢谢我完成了它,我不知道哪种类型是Exception.class,我缺少了那个类expectedExceptionClass