简体   繁体   English

如何使用AssertJ验证静态方法引发异常?

[英]How to verify that static method throws an exception using AssertJ?

When I try to test this method 当我尝试测试此方法时

    static void validatePostcode(final String postcode, final String addressLine)
    {
        if(! hasValidPostcode(postcode, addressLine)) {
            throw new InvalidFieldException("Postcode is null or empty ");
        }
    }

using the following test 使用以下测试

    @Test
    public void testThrowsAnException()
    {
        assertThatThrownBy(validatePostcode("", "")).isInstanceOf(InvalidFieldException.class);
    }

I get this error message in IntelliJ 我在IntelliJ中收到此错误消息

assertThatThrownBy (org.assertj.core.api.ThrowableAssert.ThrowingCallable) in Assertions cannot be applied to (void) 断言中的assertThatThrownBy(org.assertj.core.api.ThrowableAssert.ThrowingCallable)不能应用于(void)


Same thing with assertThatExceptionOfType . assertThatExceptionOfType相同。

Is it possible to test that static method actually throws an unchecked exception using AssertJ? 是否有可能使用AssertJ测试静态方法实际上抛出未经检查的异常? What should I change in my test? 我的考试应该改变什么?

As the compilation error demonstrates, that method expects a throwing callable. 正如编译错误所表明的那样,该方法期望抛出throwable。

@Test
public void testThrowsAnException()
{
    assertThatThrownBy(() -> validatePostcode("", "")).isInstanceOf(InvalidFieldException.class);
}

change to this way. 改为这种方式。 you need to pass lambda to test with assertj 您需要通过lambda来使用assertj进行测试

assertThatThrownBy(()->validatePostcode("","")).isInstanceOf(InvalidFieldException.class);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM