标签:itoa moc row assert port private col random 返回
如果没有返回值,
下面这种写法是错误的:
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("异常")); } }
换成下面的写法即可:
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()); } } }
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
标签:itoa moc row assert port private col random 返回
原文地址:https://www.cnblogs.com/cainiao-Shun666/p/14806344.html