在使用Mockito模拟方法抛出异常时,可以使用Mockito的doThrow()
方法来模拟方法抛出异常。下面是一个简单的示例:
假设有一个UserService类,其中有一个方法getUserById(),当传入的id为null时会抛出NullPointerException异常:
public class UserService { public User getUserById(String id) { if (id == null) { throw new NullPointerException("id cannot be null"); } // 其他逻辑 } }
现在我们想要使用Mockito来模拟getUserById()方法抛出异常,可以这样做:
import static org.mockito.Mockito.*; public class UserServiceTest { @Test public void testGetUserById() { UserService userService = mock(UserService.class); // 模拟方法抛出异常 doThrow(new NullPointerException("id cannot be null")) .when(userService) .getUserById(isNull()); // 调用被测试方法 User result = userService.getUserById(null); // 断言抛出异常 assertNotNull(result); } }
在上面的示例中,我们使用doThrow()
方法模拟了getUserById()方法在传入null时抛出NullPointerException异常。然后我们调用被测试方法并断言是否抛出了异常。
通过这种方法,我们可以很方便地使用Mockito来模拟方法抛出异常,从而进行异常处理的单元测试。