模拟 java 异常

Mock in java exception

我有这个 catch 语句:

catch (NotFoundException ex) {
      ex.getError().setTitle(NOT_FOUND);
      throw new NotFoundException(resource, id, ex.getError());
}

如何模拟这个异常?我试过这个

    when(service
        .filter(eq(any()), eq(any()), eq(any())))
        .thenThrow(new NotFoundException(anyString(), anyString()));`

但由于这一行,它给了我一个空异常错误:

ex.getError().setTitle(NOT_FOUND);

构造函数是:

  public NotFoundException(String resource, String id, Error error) {
    this.resource = resource;
    this.ids = Collections.singletonList(id);
    this.error = error;
  }

而且我无法获取异常变量来设置标题,也无法找到模拟它的方法。

感谢您的帮助!

.thenThrow(new NotFoundException(anyString(), anyString()));

这是不允许的:anyString()只能直接代表whenverify中的调用。在您对过滤器的调用中,只需使用 any() 而不是 eq(any()),否则您将在正确的位置使用匹配器。

此外,您的被测系统似乎假定 ex.getError() 不为空;您可能需要将有用的 Error 实例作为构造函数参数传递到您创建的 NotFoundException 中。

.thenThrow(new NotFoundException("foo", "bar", new Error(/* ... */)))

当然,如果您的错误难以创建或使用,您可以使用 mock(Error.class)