开发者社区 问答 正文

如何在Mockito中模拟方法调用时抛出异常?

如何在Mockito中模拟方法调用时抛出异常?

展开
收起
花开富贵111 2024-06-20 15:52:02 83 分享 版权
1 条回答
写回答
取消 提交回答
  • 北京阿里云ACE会长
    public interface SomeService {
        void doSomethingImportant();
    }
    

    定义一个接口和它的方法:

    
    import static org.mockito.Mockito.*;
    
    public class SomeServiceTest {
    
        @Test
        public void testServiceException() {
            // 创建SomeService的模拟对象
            SomeService service = mock(SomeService.class);
    
            // 模拟doSomethingImportant方法抛出一个异常
            doThrow(new RuntimeException("Something went wrong"))
                  .when(service)
                  .doSomethingImportant();
    
            // 编写测试逻辑,比如断言是否抛出了预期的异常
            try {
                service.doSomethingImportant();
                fail("Expected an exception to be thrown");
            } catch (RuntimeException e) {
                assertEquals("Something went wrong", e.getMessage());
            }
        }
    }
    

    使
    用Mockito来模拟SomeService接口:

    2024-06-21 10:24:20
    赞同 2 展开评论
问答地址: