How to test for exception in DrJava?

262 Views Asked by At

I am starting out in Java using DrJava. I am following TDD for learning. I created a method which is suppose to validate some data and on invalid data, the method is suppose to throw exception.

It is throwing exception as expected. But I am not sure, how to write a unit test to expect for exception.

In .net we have ExpectedException(typeof(exception)). Can someone point me to what is the equivalent in DrJava?

Thanks

2

There are 2 best solutions below

2
On BEST ANSWER

If you are using JUnit, you can do

@Test(expected = ExpectedException.class)
public void testMethod() {
   ...
}

Have a look at the API for more details.

0
On

If you simply want to test for the fact that a particular exception type was thrown somewhere within your test method, then the already shown @Test(expected = MyExpectedException.class) is fine.

For more advanced testing of exceptions, you can use an @Rule, in order to further refine where you expect that exception to be thrown, or to add further testing about the exception object that was thrown (i.e., the message string equals some expected value or contains some expected value:

class MyTest {

   @Rule ExpectedException expected = ExpectedException.none();
   // above says that for the majority of tests, you *don't* expect an exception

   @Test
   public testSomeMethod() {
   myInstance.doSomePreparationStuff();
   ...
   // all exceptions thrown up to this point will cause the test to fail

   expected.expect(MyExpectedClass.class);
   // above changes the expectation from default of no-exception to the provided exception

   expected.expectMessage("some expected value as substring of the exception's message");
   // furthermore, the message must contain the provided text

   myInstance.doMethodThatThrowsException();
   // if test exits without meeting the above expectations, then the test will fail with the appropriate message
   }

}