Search code examples
javaunit-testingjunitannotations

How to check custom run time exception attribute using annotation related params in java


This is my class structure

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..."))
}

I want to test this exception and MeError type object (name and description) with Junit. I wrote this

public class MyTest {

 @Rule
 public ExpectedException thrown = ExpectedException.none();


@Test(expectedExceptions = OrderRuntimeException.class, expectedExceptionsMessageRegExp = "Invalid Order")
  public void testSetRequestTime_invalidRequestDTOImplType()
  {

    thrown.expect(......);

  }

}

I used @Rule .. for getting thrown.expect() functionality. But I couldn't get the MyError type object from this test. Please put a comment or answer, If anyone has an idea about the solution.


Solution

  • I think you can use org.hamcrest.Matchers to make this type of assertions.

    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"))
        )));