我知道有一种方法是:
@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?)
当前回答
JUnit5为此添加了assertAll()方法。
assertAll( () -> foo() )
来源:JUnit 5 API
其他回答
我偶然发现这一点是因为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);
}
}
你可以基于junit的断言创建你自己的任何类型的断言,因为这些断言是专门为创建用户定义的断言而设计的,其工作方式与junit的断言完全一样:
static void assertDoesNotThrow(Executable executable) {
assertDoesNotThrow(executable, "must not throw");
}
static void assertDoesNotThrow(Executable executable, String message) {
try {
executable.execute();
} catch (Throwable err) {
fail(message);
}
}
现在测试所谓的场景methodMustNotThrow,并以junit风格记录所有失败:
//test and log with default and custom messages
//the following will succeed
assertDoesNotThrow(()->methodMustNotThrow(1));
assertDoesNotThrow(()->methodMustNotThrow(1), "custom facepalm");
//the following will fail
assertDoesNotThrow(()->methodMustNotThrow(2));
assertDoesNotThrow(()-> {throw new Exception("Hello world");}, "message");
//See implementation of methodMustNotThrow below
一般来说,在任何场景中,只要调用fail(someMessage)是有意义的,就有可能立即使测试中的任何内容失败,而fail(someMessage)正是为此目的而设计的。例如,在try/catch块中使用它,如果在测试用例中抛出任何东西,就会失败:
try{methodMustNotThrow(1);}catch(Throwable e){fail("must not throw");}
try{methodMustNotThrow(1);}catch(Throwable e){Assertions.fail("must not throw");}
这是我们测试的方法的样本,假设我们有这样一个方法,在特定的情况下一定不会失败,但它可以失败:
void methodMustNotThrow(int x) throws Exception {
if (x == 1) return;
throw new Exception();
}
上述方法是一个简单的示例。但这适用于复杂的情况,在这种情况下,失败不是那么明显。 这里有进口:
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import static org.junit.jupiter.api.Assertions.*;
你可以使用@Rule,然后调用方法reportMissingExceptionWithMessage,如下所示: 这是Scala代码。
我最后是这样做的
@Test
fun `Should not throw`() {
whenever(authService.isAdmin()).thenReturn(true)
assertDoesNotThrow {
service.throwIfNotAllowed("client")
}
}