如何捕获此自定义 Java 异常?

How to catch this custom Java exception?

我有以下单元测试:

public class Update {

    @Rule
    public final ExpectedException exception = ExpectedException.none();

    private Update update;

    @Before
    public void setUp(){
        this.update = new Update();
    }

    @Test
    public void validateThrowsExceptionIfMissingId() throws BadParameterException {
        this.update.setId(null);

        exception.expect(NotFoundException.class);
        exception.expectMessage("Error");
        this.categoryUpdateRequest.validate();
    }
}

这是期待我抛出的自定义 NotFoundException。问题是,即使我可以看到控制台中抛出了异常,我的测试也没有得到它:

com.project.api.exception.NotFoundException: Error.

有什么提示吗?

可以使用TestNG @Test注解参数expectedExceptions.

这是一个例子:

public class CategoryUpdateRequestTest 
{

    private CategoryUpdateRequest categoryUpdateRequest;

    @Before
    public void setUp(){
        this.categoryUpdateRequest = new CategoryUpdateRequest();
    }

    @Test(
        expectedExceptions = { NotFoundException.class },
        expectedExceptionsMessageRegExp = "Category object is missing Category id."
    )
    public void validateThrowsExceptionIfMissingCategoryId() throws Exception {
        this.categoryUpdateRequest.setId(null);
    }
}

您编写的 Junit 测试需要抛出异常。您的代码不会引发异常。它只是创建异常的实例并调用(某种)异常处理函数。

您可以看到 "exception" 因为您创建了一个异常实例并将其发送到记录器。但实际上对你的系统来说,它从来都不是真正的例外,因为你从来没有 throw 它。

JUnit 抱怨没有抛出异常是完全正确的。