Mockito (十四)
Mockito 使用 doThrow 让方法抛出异常
如果一个对象的方法的返回值是 void,那么不能用 when .. thenThrow 让该方法抛出异常
如果没有返回值,
下面这种写法是错误的:
import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.mockito.Mockito.when; public class MockitoDemo { static class ExampleService { public void hello() { System.out.println("Hello"); } } @Mock private ExampleService exampleService; @Test public void test() { MockitoAnnotations.initMocks(this); // 这句编译不通过,IDE 也会提示错误,原因很简单,when 的参数是非 void when(exampleService.hello()).thenThrow(new RuntimeException("异常")); } }
用 doThrow 可以让返回void的函数抛出异常
换成下面的写法即可:
import org.junit.Assert; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.mockito.Mockito.doThrow; public class MockitoDemo { static class ExampleService { public void hello() { System.out.println("Hello"); } } @Mock private ExampleService exampleService; @Test public void test() { MockitoAnnotations.initMocks(this); // 这种写法可以达到效果 doThrow(new RuntimeException("异常")).when(exampleService).hello(); try { exampleService.hello(); Assert.fail(); } catch (RuntimeException ex) { Assert.assertEquals("异常", ex.getMessage()); } } }
也可以用 doThrow 让返回非void的函数抛出异常
import org.junit.Assert; import org.junit.Test; import org.mockito.MockitoAnnotations; import java.util.Random; import static org.mockito.Mockito.*; public class MockitoDemo { @Test public void test() { MockitoAnnotations.initMocks(this); Random random = mock(Random.class); // 下面这句等同于 when(random.nextInt()).thenThrow(new RuntimeException("异常")); doThrow(new RuntimeException("异常")).when(random).nextInt(); try { random.nextInt(); Assert.fail(); } catch (RuntimeException ex) { Assert.assertEquals("异常", ex.getMessage()); } } }
转载:https://www.letianbiji.com/java-mockito/mockito-dothrow.html
带着疑问去思考,然后串联,进而归纳总结,不断追问自己,进行自我辩证,像侦查嫌疑案件一样看待技术问题,漆黑的街道,你我一起寻找线索,你就是技术界大侦探福尔摩斯