使用 Spring Boot Starter Test 在单元测试中获取异常对象

Get Exception object in Unit Test with Spring Boot Starter Test

在我的程序中,我抛出了一个自定义异常对象 MyCustomException,它看起来像这样:

public class MyCustomException
{
    private MyCustomExceptionObject myCustomExceptionObject;
    // Getters, Setters, Constructors...
}

public class MyCustomExceptionObject
{
    int code;
    // Getters, Setters, Constructors...
}

通过 Spring 启动启动器测试,我有很多测试库可供使用。

目前我主要使用AssertJ。我的一项测试为方法提供了无效参数并期望出现异常。

@Test
public void test()
{
    org.assertj.core.api.Assertions.assertThatThrownBy(() -> someMethod(-1)).isExactlyInstanceOf(MyCustomException.class);
}

public void someMethod(int number)
{
    if (number < 0)
    {
        throw new MyCustomException(new MyCustomExceptionObject(12345));
    }
    //else do something useful
}

这很好用,但我想更具体地测试异常,测试 code 是否符合预期。像这样的东西会起作用:

try
{
    someMethod(-1);
}
catch (MyCustomException e)
{
    if (e.getCode() == 12345)
    {
        return;
    }
}

org.assertj.core.api.Assertions.fail("Exception not thrown");

但我更愿意寻找像这样的单线:

org.assertj.core.api.Assertions.assertThatThrownBy(() -> someMethod(-1)).isExactlyInstanceOf(MyCustomException.class).exceptionIs((e) -> e.getCode() == 12345);

上面列出的任何测试库(首选 AssertJ)中是否存在类似的东西?

我会尝试 catchThrowableOfType,它允许您断言您的自定义异常数据,例如:

class CustomParseException extends Exception {
   int line;
   int column;

   public CustomParseException(String msg, int l, int c) {
     super(msg);
     line = l;
     column = c;
   }
 }

 CustomParseException e = catchThrowableOfType(
                            () -> { throw new CustomParseException("boom!", 1, 5); }, 
                            CustomParseException.class);
 // assertions succeed
 assertThat(e).hasMessageContaining("boom");
 assertThat(e.line).isEqualTo(1);
 assertThat(e.column).isEqualTo(5);