Linux 拨号vps windows公众号手机端

java mockito模拟抛出异常怎么解决

lewis 9年前 (2016-10-25) 阅读数 8 #程序编程
文章标签 Java

在使用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来模拟方法抛出异常,从而进行异常处理的单元测试。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门