我了解 Junit5 Assertions.assertThrows
接受 Executable 类型对象。因此,举一个简单的例子,构造函数不能将空字符串作为名称参数:
public Company(String aName, Calendar aFoundingDate)
{
if (aName == null || aName.length() == 0 || aName.length() > 50) {
throw new IllegalArgumentException("Invalid name");
}
this.name = aName;
foundingDate = aFoundingDate;
}
我可以编写这样的测试:
// Company constructor test
@Test
void testCompanyConstructor() {
// Given
String emptyName = "aabbe";
Calendar validFoundingDate = Calendar.getInstance();
validFoundingDate.set(2000, 1, 1);
// Then
assertThrows(IllegalArgumentException.class, () -> new Company(emptyName, validFoundingDate));
}
我想知道的是,可执行文件(即 Lambda 表达式)会发生什么? JUnit 是否对 Lambda 表达式调用execute(),这样做时,会创建名称为空的匿名公司对象,异常为
附录: 这些版本是等效的:
// Company constructor test
@Test
void testCompanyConstructor() {
// Given
String emptyName = "";
Calendar validFoundingDate = Calendar.getInstance();
validFoundingDate.set(2000, 1, 1);
// Then
Executable executable = new Executable() {
public void execute() {
new Company(emptyName, validFoundingDate);
}
};
assertThrows(IllegalArgumentException.class, executable);
assertThrows(IllegalArgumentException.class, () -> new Company(emptyName, validFoundingDate));
}
最佳答案
当检查assertThrows
的代码时,我们可以看到在AssertThrows::assertThrows
深处有这样的代码:
try {
executable.execute();
}
catch (Throwable actualException)
if (expectedType.isInstance(actualException)) {
return (T) actualException;
}
else {
BlacklistedExceptions.rethrowIfBlacklisted(actualException);
String message = buildPrefix(nullSafeGet(messageOrSupplier))
+ format(expectedType, actualException.getClass(), "Unexpected exception type thrown");
throw new AssertionFailedError(message, actualException);
}
}
所以它基本上调用Executable
并捕获可能抛出的Throwable
并返回它。如果没有抛出异常或者异常类型与预期不同 - 断言失败。
关于java - JUnit 断言抛出中的可执行文件会发生什么情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57745723/