问题描述
如何编写基于Mockito的JUnit方法来测试此方法adduser()
?我尝试编写一个,但是失败并显示一条错误消息,指出未处理异常.错误针对以下内容显示:
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");
假设业务类中的addUser()
方法从不捕获任何异常,并且重新抛出也没有完成.
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;
}
}
测试案例方法:
在测试类中,我正在模拟具有@Mock
属性的服务层类并将其注入.
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.
推荐答案
在测试方法中声明异常.
Declare the exception in the test method.
public void testAddUser() throws ServiceException{
...
}
这篇关于使用Mockito测试引发未捕获的自定义异常的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!