簡體   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