为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用Java中的注释相关参数检查自定义运行时异常属性

如何使用Java中的注释相关参数检查自定义运行时异常属性

精慕HU 2021-11-03 14:28:52
这是我的班级结构public class OrderRuntimeException extends RuntimeException{  private final Field field;   public OrderManagementServiceRuntimeException(String messege, MyError myError)  {    super(messege);    this.field = field;  }}public Class MyError{    String name;    Sttring description;    public MyError(String name, String description){        this.name = name;        this.description = description;    } }public void getOrders(Order order){    .......    throw new  OrderRuntimeException("Invalid Order",new MyError("Illegale","this is an illegal..."))}我想用 Junit 测试这个异常和 MeError 类型的对象(名称和描述)。我写了这个public class MyTest { @Rule public ExpectedException thrown = ExpectedException.none();@Test(expectedExceptions = OrderRuntimeException.class, expectedExceptionsMessageRegExp = "Invalid Order")  public void testSetRequestTime_invalidRequestDTOImplType()  {    thrown.expect(......);  }}我使用 @Rule .. 来获取 throw.expect() 功能。但是我无法从这个测试中得到 MyError 类型的对象。请发表评论或回答,如果有人对解决方案有想法。
查看完整描述

1 回答

?
萧十郎

TA贡献1815条经验 获得超13个赞

我认为你可以org.hamcrest.Matchers用来做出这种类型的断言。


expectedException.expect(OrderRuntimeException.class);

    expectedException.expect(org.hamcrest.Matchers.hasProperty("myError", allOf(

            org.hamcrest.Matchers.hasProperty("name", is("exampleName")),

            org.hamcrest.Matchers.hasProperty("description", is("exampleDescription"))

    )));


查看完整回答
反对 回复 2021-11-03
  • 1 回答
  • 0 关注
  • 170 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信