我正在编写一个名为 Fibonacci 的类,其中包含三个静态方法,使用不同的方法(递归、内存等)实现斐波那契数列的三种不同实现。
然后我创建了一个测试包,并在其中包含一个简单的 junit 测试,该测试检查当将负数传递给斐波那契函数时是否引发异常:
@Test
void testIllegalArgumentException() {
Assertions.assertThrows(IllegalArgumentException.class,
() -> Fibonacci.fibonacci_recursive(-2));
}
我的问题是:是否可以编写一个以函数作为参数的测试?换句话说,我想避免编写以下内容:
@Test
void testIllegalArgumentException() {
Assertions.assertThrows(IllegalArgumentException.class,
() -> Fibonacci.fibonacci_recursive(-2));
}
@Test
void testIllegalArgumentException() {
Assertions.assertThrows(IllegalArgumentException.class,
() -> Fibonacci.fibonacci_second(-2));
}
@Test
void testIllegalArgumentException() {
Assertions.assertThrows(IllegalArgumentException.class,
() -> Fibonacci.fibonacci_third(-2));
}
最佳答案
Java 8 + Junit5 允许您创建@ParameterizedTest
。作为参数列表,您可以传递要测试的函数。以下测试将使用不同的输入功能运行 3 次。
测试示例:
@ParameterizedTest
@MethodSource("getSource")
void whenNegativeValue_thenThrowException(Function<Integer, Integer> function, Integer value) {
Assertions.assertThrows(IllegalArgumentException.class,
() -> function.apply(value));
}
private static Stream<Arguments> getSource() {
Function<Integer, Integer> first = Fib::first;
Function<Integer, Integer> second = Fib::second;
Function<Integer, Integer> third = Fib::third;
return Stream.of(
Arguments.of(first, -1),
Arguments.of(second, -2),
Arguments.of(third, -3)
);
}
类实现:
public class Fib {
public static int first(int i) {
System.out.println("first");
validate(i);
return i;
}
public static int second(int i) {
System.out.println("second");
validate(i);
return i;
}
public static int third(int i) {
System.out.println("third");
validate(i);
return i;
}
private static void validate(int i) {
if (i < 0) {
throw new IllegalArgumentException();
}
}
}
关于java - 如何将相同的单元测试应用于不同的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58983289/