Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using mockito to test methods which throw uncaught custom exceptions

How do I write a Mockito-based JUnit method to test this method adduser()? I tried writing one, but it's failing with an error message saying exception is not handled. The error is displayed for:

when(service.addUser("nginx")).thenReturn("apache"); 

Assume addUser() method in business class never catches any exception and rethrowing is not done.

class Business {     public User addUser() throws ServiceException{         User user = service.addUser("nginx");         return user;     } } 

TEST CASE METHOD :

Here in the test class I am mocking the service layer class with @Mock attribute and injecting it.

@Mock Service service;     @InjectMocks Business business = new Business();  @Test public void testAddUser() {     when(service.addUser("nginx")).thenReturn("apache");         User user = business.addUser("nginx");     assertNotNull(user); } 

Please tell me how to handle the exception scenario in the test case.

like image 283
Sekhar Avatar asked Feb 11 '12 07:02

Sekhar


People also ask

Which Mockito methods are used to handle the exception in case of test methods?

Mockito provides the capability to a mock to throw exceptions, so exception handling can be tested. Take a look at the following code snippet. //add the behavior to throw exception doThrow(new Runtime Exception("divide operation not implemented")) .

Can Mockito throw exceptions on void methods?

Mockito provides following methods that can be used to mock void methods. doAnswer() : We can use this to perform some operations when a mocked object method is called that is returning void. doThrow() : We can use doThrow() when we want to stub a void method that throws exception.

Can Mockito test private methods?

For Mockito, there is no direct support to mock private and static methods. In order to test private methods, you will need to refactor the code to change the access to protected (or package) and you will have to avoid static/final methods.


1 Answers

Declare the exception in the test method.

public void testAddUser() throws ServiceException { ... } 
like image 147
Dawood ibn Kareem Avatar answered Sep 17 '22 20:09

Dawood ibn Kareem