Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle Exception with Mockito

Tags:

java

mockito

I'm using Mockito in my unit testing. I have a method

public Status getResponse(Request requset) throws DataException{
}

DataException is my own defined one which inherited from Exception class.

In my test case

static{
when(process.getResponse(any(Request.class))).
                thenReturn(new Status("Success"));
}

It gives an error, Unhandled Exception:DataException

Is there any way in Mockito to handle this issue without adding try/catch ?

like image 408
Shashika Avatar asked Apr 22 '14 07:04

Shashika


People also ask

How do I ignore an exception in Mockito?

If you want to ignore a test method, use @Ignore along with @Test annotation. If you want to ignore all the tests of class, use @Ignore annotation at the class level.

How do you throw a mock exception?

To specify that the framework throws an exception when a mock object method is invoked or when a mock object property is set or accessed, use the ThrowException class. You can use this action to inject error conditions into the system under test.

How do I test exceptions in JUnit 5?

In JUnit 5, to write the test code that is expected to throw an exception, we should use Assertions. assertThrows(). In the given test, the test code is expected to throw an exception of type ApplicationException or its subtype. Note that in JUnit 4, we needed to use @Test(expected = NullPointerException.


2 Answers

Don't use a static block. Use a method tagged with @Before instead, and tack throws Exception onto its declaration.

like image 175
Dawood ibn Kareem Avatar answered Oct 24 '22 16:10

Dawood ibn Kareem


add this to your test method:

@Test(expected=DataException.class)

or use this :

then(caughtException()).isInstanceOf(DataException.class);

for a static-block there is no way other than try-catch.

Another way is to change DataException to a RuntimeException.

like image 29
Taher Khorshidi Avatar answered Oct 24 '22 15:10

Taher Khorshidi