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

标签 java junit5 functional-interface

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

相关文章:

java - 在gradle中为Heroku创建webapp-runner.jar

maven - 通过 Maven 执行测试时 @DisplayName 不起作用

java - @MockBean 返回空对象

java - 为什么 java.lang.ref.Reference<T> 不实现 Supplier<T>?

Java - 使用函数式接口(interface)和 lambda 表达式进行日志记录

java - java中在字符串的指定位置插入

java - hibernate 映射帮助!

java - Sonar 测试用例失败

java - 为什么 Comparable 在 jdk 1.8 中没有声明为 @FunctionalInterface 尽管它是 FunctionalInterface 之一?

java - 如何调用模拟类的方法的方法?