-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

2
  • In the same way that you did inside myMethod, you will want to catch it. Commented Feb 9, 2018 at 16:26
  • I'll need to catch? Commented Feb 9, 2018 at 16:57

1 Answer 1

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 !

Sign up to request clarification or add additional context in comments.

2 Comments

See the linked duplicate answer for why this isn't always effective.
It's working. What if you want to access the exception object and read the message that was sent?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.