我知道有一种方法是:
@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?)
当前回答
我遇到了同样的情况,我需要检查异常是否在应该抛出的时候抛出,并且仅在应该抛出的时候抛出。 最终使用异常处理程序对我的好处如下代码:
try {
functionThatMightThrowException()
}catch (Exception e){
Assert.fail("should not throw exception");
}
RestOfAssertions();
对我来说,主要的好处是它非常直截了当,并且在相同的结构中检查“如果且仅当”的另一种方式非常容易
其他回答
对于5之前的JUnit版本:
使用AssertJ fluent断言3.7.0:
Assertions.assertThatCode(() -> toTest.method())
.doesNotThrowAnyException();
更新:
JUnit 5引入了assertDoesNotThrow()断言,所以我更喜欢使用它,而不是向项目添加额外的依赖项。详情请看这个答案。
我遇到了同样的情况,我需要检查异常是否在应该抛出的时候抛出,并且仅在应该抛出的时候抛出。 最终使用异常处理程序对我的好处如下代码:
try {
functionThatMightThrowException()
}catch (Exception e){
Assert.fail("should not throw exception");
}
RestOfAssertions();
对我来说,主要的好处是它非常直截了当,并且在相同的结构中检查“如果且仅当”的另一种方式非常容易
如果您不幸捕获了代码中的所有错误。 你可以愚蠢地做
class DumpTest {
Exception ex;
@Test
public void testWhatEver() {
try {
thisShouldThrowError();
} catch (Exception e) {
ex = e;
}
assertEquals(null,ex);
}
}
在这个问题上遇到了麻烦,因为我创建了一些泛型方法
@Test
void testSomething() {
checkGeneric(anComplexObect)
}
在https://newbedev.com/sonarqube-issue-add-at-least-one-assertion-to-this-test-case-for-unit-test-with-assertions中提出了一些注释的东西。
解决方案要简单得多。将“checkGeneric”方法重命名为“assertGeneric”就足够了。
@Test
void testSomething() {
assertGeneric(anComplexObect)
}
AssertJ可以处理这种情况:
assertThatNoException().isThrownBy(() -> System.out.println("OK"));
查看文档了解更多信息https://assertj.github.io/doc/#assertj-core-exception-assertions-no-exception