Spring Boot Starter Test单元测试中获取自定义异常对象
如何用AssertJ捕获并验证自定义MyCustomException
嘿,我来帮你搞定这个问题!既然你主要用AssertJ,那咱们就用它最优雅的方式来捕获自定义异常,还能轻松拿到里面的MyCustomExceptionObject和对应的code值。
核心方案:用AssertJ的catchThrowable方法
AssertJ的catchThrowable可以直接捕获lambda执行时抛出的异常,之后你就能对异常做各种断言,包括取出内部的自定义对象。
假设你要测试的服务方法是yourService.processInvalidParam(),调用它会抛出MyCustomException,测试代码可以这么写:
import org.assertj.core.api.Assertions; import org.junit.Test; public class YourServiceTest { @Test public void whenInvalidParamIsPassed_shouldThrowCustomExceptionWithExpectedCode() { // 初始化你要测试的服务 YourService yourService = new YourService(); // 捕获执行方法时抛出的异常 Throwable thrown = Assertions.catchThrowable(() -> yourService.processInvalidParam()); // 第一步:断言抛出的是我们的自定义异常 Assertions.assertThat(thrown) .isInstanceOf(MyCustomException.class); // 第二步:转换为自定义异常,取出内部对象并验证code MyCustomException customException = (MyCustomException) thrown; Assertions.assertThat(customException.getMyCustomExceptionObject().getCode()) .isEqualTo(400); // 替换成你预期的错误码 } }
额外补充:JUnit 4的兼容写法(如果需要)
如果你偶尔会用到JUnit 4的@Test(expected)注解,也可以这么写,但这种方式不如AssertJ灵活,更推荐上面的方案:
@Test(expected = MyCustomException.class) public void testInvalidParamWithJUnit4() throws MyCustomException { YourService yourService = new YourService(); try { yourService.processInvalidParam(); } catch (MyCustomException e) { // 在这里验证code值 Assertions.assertThat(e.getMyCustomExceptionObject().getCode()).isEqualTo(400); // 必须重新抛出异常,让JUnit的expected断言生效 throw e; } }
注意事项
- 确保你的
MyCustomException类有getMyCustomExceptionObject()这个getter方法,MyCustomExceptionObject类有getCode()方法,不然没法获取到对应的值哦。 - AssertJ的链式断言非常直观,你还可以添加更多断言,比如异常消息(如果有的话),让测试更全面。
内容的提问来源于stack exchange,提问作者janssen-dev
相关产品推荐
相关产品推荐

