Using mockito to test methods which throw uncaught custom exceptions

爱⌒轻易说出口 提交于 2019-12-05 08:46:33

问题


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.


回答1:


Declare the exception in the test method.

public void testAddUser() throws ServiceException{
...
}


来源:https://stackoverflow.com/questions/9238702/using-mockito-to-test-methods-which-throw-uncaught-custom-exceptions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!