43

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.

user1438038
  • 5,821
  • 6
  • 60
  • 94
Sekhar
  • 961
  • 5
  • 15
  • 27
  • 2
    Are you aware that all that you're testing is that the method returns something not null. I think you ought to assert that it returns "apache", because you really need to check that `service.addUser()` has actually been called. – Dawood ibn Kareem Feb 11 '12 at 08:22

1 Answers1

70

Declare the exception in the test method.

public void testAddUser() throws ServiceException {
...
}
J.Olufsen
  • 13,415
  • 44
  • 120
  • 185
Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
  • 1
    I have a method which can throw 11 different exceptions (it's an 3rd party dependency), so the list of thrown exceptions get ridiculously long. Any way to avoid that? – Olov May 11 '21 at 11:56
  • 1
    I have got into the habit of just writing `throws Exception` on all my JUnit methods. There is literally no reason not to, as the JUnit framework catches and reports on anything that you don't catch. @Olov – Dawood ibn Kareem May 11 '21 at 22:41