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

这是我的班级结构


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 类型的对象。请发表评论或回答,如果有人对解决方案有想法。


精慕HU
浏览 174回答 1
1回答

萧十郎

我认为你可以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"))    )));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java