我知道有一种方法是:
@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?)
当前回答
您可以期望通过创建规则不会抛出异常。
@Rule
public ExpectedException expectedException = ExpectedException.none();
其他回答
JUnit 5 (Jupiter)提供了三个函数来检查异常是否存在:
● 断言全部()
断言所有提供的可执行文件 不要抛出异常。
● assertDoesNotThrow()
类的执行 提供可执行/供应商 不抛出任何类型的异常。
此函数可用 JUnit 5.2.0以来(2018年4月29日)。
●assertThrows ()
断言所提供的可执行文件的执行 抛出expectedType的异常 并返回异常。
例子
package test.mycompany.myapp.mymodule;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class MyClassTest {
@Test
void when_string_has_been_constructed_then_myFunction_does_not_throw() {
String myString = "this string has been constructed";
assertAll(() -> MyClass.myFunction(myString));
}
@Test
void when_string_has_been_constructed_then_myFunction_does_not_throw__junit_v520() {
String myString = "this string has been constructed";
assertDoesNotThrow(() -> MyClass.myFunction(myString));
}
@Test
void when_string_is_null_then_myFunction_throws_IllegalArgumentException() {
String myString = null;
assertThrows(
IllegalArgumentException.class,
() -> MyClass.myFunction(myString));
}
}
在这个问题上遇到了麻烦,因为我创建了一些泛型方法
@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)
}
我最后是这样做的
@Test
fun `Should not throw`() {
whenever(authService.isAdmin()).thenReturn(true)
assertDoesNotThrow {
service.throwIfNotAllowed("client")
}
}
虽然这篇文章已经发布6年了,但是Junit世界已经发生了很多变化。现在可以使用Junit5
org.junit.jupiter.api.Assertions.assertDoesNotThrow()
Ex:
public void thisMethodDoesNotThrowException(){
System.out.println("Hello There");
}
@Test
public void test_thisMethodDoesNotThrowException(){
org.junit.jupiter.api.Assertions.assertDoesNotThrow(
()-> thisMethodDoesNotThrowException()
);
}
希望它能帮助那些正在使用Junit5新版本的人
我偶然发现这一点是因为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)
你可能会觉得更有可读性。