gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 11:20:46 25 4
gpt4 key购买 nike

在我的程序中,我抛出一个自定义异常对象MyCustomException,如下所示:

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

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

通过 Spring Boot Starter Test,我可以使用许多测试库。

  • 断言J
  • JUnit4
  • 莫基托
  • 汉克雷斯特

目前我主要使用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);

关于java - 使用 Spring Boot Starter Test 在单元测试中获取异常对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49936268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com