views:

185

answers:

1

i have written a few junits with @Test annotation. If my test method throws a checked exception and if i want to assert the message along with the exception, is there a way to do so with JUNIT @Test annotation.AFAIK, Junit 4.7 doesnt provide this feature but does any future versions provide it. I know in .NET you can assert the message and the exception class. Looking for similar feature in the java world.

This is what i want

@Test (expected = RuntimeException.class, message = "Employee ID is null")

public void shouldThrowRuntimeExceptionWhenEmployeeIDisNull() { }

+1  A: 

Do you have to use @Test(expected..blah)? When we have to assert the actual message of the exception, this is what we do.

@Test
public void myTestMethod()
{
  try
  {
    final Integer employeeId = null;
    new Employee(employeeId);
    fail("Should have thrown SomeException but did not!");
  }
  catch( final SomeException e )
  {
    final String msg = "Employee ID is null";
    assertEquals(msg, e.getMessage());
  }
}
c_maker
I m aware of writing a catch block and using assert within that but for better code readability i want to do with annotations.
Cshah