如何使用 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) in Assertions cannot be applied to (void)
与 assertThatExceptionOfType
.
相同
是否可以使用 AssertJ 测试静态方法实际上抛出未经检查的异常?我应该在测试中更改什么?
改为这种方式。您需要传递 lambda 以使用 assertj
进行测试
assertThatThrownBy(()->validatePostcode("","")).isInstanceOf(InvalidFieldException.class);
如编译错误所示,该方法需要一个抛出可调用对象。
@Test
public void testThrowsAnException()
{
assertThatThrownBy(() -> validatePostcode("", "")).isInstanceOf(InvalidFieldException.class);
}
当我尝试测试这个方法时
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) in Assertions cannot be applied to (void)
与 assertThatExceptionOfType
.
是否可以使用 AssertJ 测试静态方法实际上抛出未经检查的异常?我应该在测试中更改什么?
改为这种方式。您需要传递 lambda 以使用 assertj
进行测试assertThatThrownBy(()->validatePostcode("","")).isInstanceOf(InvalidFieldException.class);
如编译错误所示,该方法需要一个抛出可调用对象。
@Test
public void testThrowsAnException()
{
assertThatThrownBy(() -> validatePostcode("", "")).isInstanceOf(InvalidFieldException.class);
}