gpt4 book ai didi

java - JUnit 断言抛出中的可执行文件会发生什么情况?

转载 作者:行者123 更新时间:2023-11-29 08:21:24 24 4
gpt4 key购买 nike

我了解 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com