bea*_*u13 5 java junit assertj
我想测试一个特定的方法是否可以毫无例外地处理一堆字符串。因此,我想使用 AssertJ 的软断言,例如:
SoftAssertion softly = new SoftAssertion();
for (String s : strings) {
Foo foo = new Foo();
try {
foo.bar(s);
// Mark soft assertion passed.
} catch (IOException e) {
// Mark soft assertion failed.
}
}
softly.assertAll();
Run Code Online (Sandbox Code Playgroud)
不幸的是,我必须分别使用 AssertJ 1.x 和 Java 6,所以我无法利用这一点:
assertThatCode(() -> {
// code that should throw an exception
...
}).doesNotThrowAnyException();
Run Code Online (Sandbox Code Playgroud)
有没有办法用 AssertJ(或 JUnit)做到这一点?
我会说在测试代码中使用循环不是一个好习惯。
如果您在测试中运行的代码引发异常 - 则测试失败。我的建议是为 JUnit 使用参数化运行器(随库一起提供)。
来自官方 JUnit 4 文档的示例:
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class FibonacciTest {
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{ 0, 0 }, { 1, 1 }, { 2, 1 }, { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 }
});
}
private int fInput;
private int fExpected;
public FibonacciTest(int input, int expected) {
fInput= input;
fExpected= expected;
}
@Test
public void test() {
// Basically any code can be executed here
assertEquals(fExpected, Fibonacci.compute(fInput));
}
}
public class Fibonacci {
public static int compute(int n) {
int result = 0;
if (n <= 1) {
result = n;
} else {
result = compute(n - 1) + compute(n - 2);
}
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3356 次 |
| 最近记录: |