繁体   English   中英

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

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

当我尝试测试此方法时

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

使用以下测试

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

我在IntelliJ中收到此错误消息

断言中的assertThatThrownBy(org.assertj.core.api.ThrowableAssert.ThrowingCallable)不能应用于(void)


assertThatExceptionOfType相同。

是否有可能使用AssertJ测试静态方法实际上抛出未经检查的异常? 我的考试应该改变什么?

正如编译错误所表明的那样,该方法期望抛出throwable。

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

改为这种方式。 您需要通过lambda来使用assertj进行测试

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

暂无
暂无

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

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