我知道有一种方法是:
@Test
public void foo() {
try {
// execute code that you expect not to throw Exceptions.
} catch(Exception e) {
fail("Should not have thrown any exception");
}
}
还有更干净的方法吗?(可能使用了Junit的@Rule?)
我知道有一种方法是:
@Test
public void foo() {
try {
// execute code that you expect not to throw Exceptions.
} catch(Exception e) {
fail("Should not have thrown any exception");
}
}
还有更干净的方法吗?(可能使用了Junit的@Rule?)
当前回答
我偶然发现这一点是因为SonarQube的规则“squid:S2699”:“向这个测试用例添加至少一个断言。”
我有一个简单的测试,它的唯一目标是不抛出异常。
考虑这段简单的代码:
public class Printer {
public static void printLine(final String line) {
System.out.println(line);
}
}
可以添加什么样的断言来测试这个方法? 当然,您可以尝试捕获它,但这只是代码膨胀。
解决方案来自JUnit本身。
如果没有抛出异常,并且你想显式地说明这种行为,只需添加预期,如下例所示:
@Test(expected = Test.None.class /* no exception expected */)
public void test_printLine() {
Printer.printLine("line");
}
Test.None.class是预期值的默认值。
如果您导入org.junit.Test。没有,你可以这样写:
@Test(expected = None.class)
你可能会觉得更有可读性。
其他回答
如果您不幸捕获了代码中的所有错误。 你可以愚蠢地做
class DumpTest {
Exception ex;
@Test
public void testWhatEver() {
try {
thisShouldThrowError();
} catch (Exception e) {
ex = e;
}
assertEquals(null,ex);
}
}
如果您想测试您的测试目标是否使用异常。只需要将测试保留为(使用jMock2的模拟合作者):
@Test
public void consumesAndLogsExceptions() throws Exception {
context.checking(new Expectations() {
{
oneOf(collaborator).doSth();
will(throwException(new NullPointerException()));
}
});
target.doSth();
}
如果您的目标确实使用抛出的异常,则测试将通过,否则测试将失败。
如果您想测试异常使用逻辑,事情会变得更加复杂。我建议将消费委托给一个可能被嘲笑的合作者。因此,测试可以是:
@Test
public void consumesAndLogsExceptions() throws Exception {
Exception e = new NullPointerException();
context.checking(new Expectations() {
{
allowing(collaborator).doSth();
will(throwException(e));
oneOf(consumer).consume(e);
}
});
target.doSth();
}
但如果你只是想记录它,有时它就设计过度了。在这种情况下,如果您坚持使用tdd,本文(http://java.dzone.com/articles/monitoring-declarative-transac, http://blog.novoj.net/2008/09/20/testing-aspect-pointcuts-is-there-an-easy-way/)可能会有所帮助。
这可能不是最好的方法,但它肯定能确保不会从正在测试的代码块抛出异常。
import org.assertj.core.api.Assertions;
import org.junit.Test;
public class AssertionExample {
@Test
public void testNoException(){
assertNoException();
}
private void assertException(){
Assertions.assertThatThrownBy(this::doNotThrowException).isInstanceOf(Exception.class);
}
private void assertNoException(){
Assertions.assertThatThrownBy(() -> assertException()).isInstanceOf(AssertionError.class);
}
private void doNotThrowException(){
//This method will never throw exception
}
}
用void方法来测试场景
void testMeWell() throws SomeException {..}
不抛出异常:
Junit5
assertDoesNotThrow(() -> {
testMeWell();
});
JUnit5为此添加了assertAll()方法。
assertAll( () -> foo() )
来源:JUnit 5 API