-1

Let's say I have my method myMethod checking a series of scenarios then throws exception accordingly without handling those exceptions.

public MyResponse myMethod(MyRequest req)
{
    try
       {
          if(req.property1 == null || req.property1.isEmpty())
             throw new Exception("Property 1 is null of empty");

          if(req.property2 == null || req.property2.isEmpty())
             throw new Exception("Property 2 is null of empty");

          //if no problem is found then proceed ...
       }
       catch(Exception e)
       {
          //log error
          throw e;
       }

}

How do I test the exception being thrown or at least check the message that was sent with the exception?

@Test
public void aNullOrEmptyProperty1CausesExceptionTest() throws Exception {
    //..
    String property1 = "";
    req.setProperty1(property1);
    //...
    MyResponse response = target.myMethod(req);

    //How to check for the exception?
}

Thanks for helpin

Richard77
  • 20,343
  • 46
  • 150
  • 252

1 Answers1

3

I don't know if it's available in all versions of JUnit (I use junit 4.12). What I usely do is to add the expected exception after the Test annotation, for example:

@Test(expected = MySpecificException.class)

There are other ways to do, but that's a possibility. You can create a specific MySpecificException class (which extends Exception class), and you throw this specific exception in your code. Then you can check that it is thrown correctly with junit.

Have fun !

E. Bavoux
  • 535
  • 1
  • 4
  • 11