Mockito作为一款不错的单元测试mock工具,极大的提升单元测试效率,但是在使用该工具时需要注意Mockito打桩的方法参数一定不能是基础类型(boolean、int),否则使用any()的时候就会报空指针异常...: int save(DeviceType deviceType, boolean isCreate) --错误命名 Mockito.when(deviceTypeManager.save(any(),
执行的操作 * @param retryPolicy 重试策略 * @return 返回值 * @throws Exception 业务异常或者超过最大重试次数后的最后一次尝试抛出的异常...(new NullPointerException()).doReturn(1).when(callable).call(); Integer result = SimpleRetryUtil.executeWithRetry....abortCondition(Objects::nonNull) .build(); //前两次返回null 需要重试 Mockito.doReturn...(new NullPointerException()).doReturn(1).when(callable).call(); Integer result = SimpleRetryUtil.executeWithRetry....abortCondition(Objects::nonNull) .build(); //前两次返回null 需要重试 Mockito.doReturn
add("test2"); 测试用例 2 通过设值或者打桩的方式预设参数,如下所示,当执行 get(0) 操作时,我们通过 thenReturn()方法返回 hello,当执行 get(1)操作时我们抛出空指针异常.../设置值,通常被称为打桩 when(mockedList.get(0)).thenReturn("hello"); when(mockedList.get(1)).thenThrow(new NullPointerException...mockedList.get(1)); //验证有没有执行 get(0) 操作 verify(mockedList).get(0); } 可以看到当我们调用 get(0) 和 get(1) 的时候控制台成功的抛出了异常...@Test public void testDoReturn() throws Exception { Iterator mockedList = mock(Iterator.class); doReturn...("hello").when(mockedList).next(); Object next = mockedList.next(); System.out.println(next); doReturn
(false).when(syncInformHandler, "isLocked", Mockito.anyLong()); // or PowerMockito.doReturn(true).when...(list); // 以下会抛出IndexOutOfBoundsException异常 // PowerMockito.when(spy.get(0)).thenReturn("sss"); PowerMockito.doReturn...("sss").when(spy).get(0); Assert.assertEquals("sss", spy.get(0)); 以上代码,注释掉的不能用,会抛出IndexOutOfBoundsException...()区别在于Mockito无法监视对象的final方法,但是PowerMockito可以,其实PowerMockito是基于Mockito的基础上拓展开发的,所以功能更加强大,也兼容了Mockito的功能...(syncKeyManager, Mockito.never()).putServerSyncKey(Mockito.anyLong(), Mockito.anyLong()); // 验证private
Mockito.mock() vs @Mock vs @MockBean Mockito.mock ()方法允许我们创建类或接口的模拟对象。...Order orderInput = new Order(orderId, "Test", 1.0, "17 St Andrews Croft, Leeds ,LS17 7TP"); doReturn...(orderInput).when(orderRepository) .save(any()); doReturn(true).when(notificationService)...{ Order orderInput = new Order(null, "Test", 1.0, "17 St Andrews Croft, Leeds ,LS17 7TP"); doReturn...如果我们在单元测试示例中使用 @SpyBean ,则 当 调用NotificationService时,测试将失败并出现NullPointerException,因为OrderService需要模拟/间谍
与mock()方法不同的是,我们需要启用Mockito注解才能使用该注解。...; Order orderInput = new Order(orderId, "Test", 1.0, "17 St Andrews Croft, Leeds ,LS17 7TP"); doReturn...(orderInput).when(orderRepository) .save(any()); doReturn(true).when(notificationService)...() { Order orderInput = new Order(null, "Test", 1.0, "17 St Andrews Croft, Leeds ,LS17 7TP"); doReturn...如果我们在单元测试示例中使用 @SpyBean ,则 当 调用NotificationService时,测试将失败并出现NullPointerException,因为OrderService需要模拟/间谍
常见的打桩方法: 方法名 方法含义 doReturn(Object toBeReturned) 提前设置要返回的值 doThrow(Throwable… toBeThrown) 提前设置要抛出的异常 doAnswer...: when(mock.someMethod("some arg")) .thenThrow(new RuntimeException(), new NullPointerException(); 使用...IndexOutOfBoundsException()异常 when(spy.get(0)).thenReturn("foo"); //这时你应该使用doReturn()函数 doReturn("foo...因此,当使用监控对象时请考虑doReturn|Answer|Throw()函数族来进行打桩。...()来打桩 doReturn("foo").when(spy).get(0); 8.
import static org.mockito.Matchers.anyInt import static org.mockito.Mockito.* class Demo extends Specification...def iterator = new ArrayList() iterator.add("323") def list = spy(iterator) doReturn...("fun").when(list).get(3) doReturn(3).when(list).get(0) expect: list.contains...("323") "fun" == list.get(3) 3 == list.get(0) } def "这是一个测试,抛出异常的测试用例"() {...mock(ArrayList.class) when(object.get(1)).thenThrow(new IndexOutOfBoundsException("我是测试"))//只能抛出可能的抛出的异常
常用 API : verify() 校验方法是否被调用 doThrow() 模拟抛出异常 doThrow(new RuntimeException()).when(event).getName...(); 当调用 event.getName() 时抛出RuntimeException doAnswer() doAnswer(new Answer() { @Override...setName(anyString()); event.setName("name"); 当调用 event.setName("name") 只有参数是“name”时通过,其他值抛出异常...doReturn() List list = new ArrayList(); //Mockito.spy(Object) 用spy监控真实对象,设置真实对象行为 List spy...异常,因为真实List对象是空的 //所以需要doReturn doReturn("hello").when(spy).get(0); doCallRealMethod() Event mock = mock
使用 thenReturn、doReturn设置方法的返回值 thenReturn 用来指定特定函数和参数调用的返回值。thenReturn 中可以指定多个返回值,在调用时返回值依次出现。...{ MockitoAnnotations.initMocks(this); Random random = mock(Random.class); doReturn...相同,但使用方式不同: 使用 thenThrow、doThrow让方法抛出异常 thenThrow 用来让函数调用抛出异常。...若调用次数超过异常的数量,再次调用时抛出最后一个异常。...用 doThrow 可以让返回void的函数抛出异常。
一、 行为验证 一旦 mock 对象被创建了,mock 对象会记住所有的交互,然后你就可以选择性的验证你感兴趣的交互,验证不通过则抛出异常。...ArrayList mockList = mock(ArrayList.class);// 设置方法调用返回值when(mockList.add("test2")).thenReturn(true); doReturn...(true).when(mockList).add("test2"); System.out.println(mockList.add("test2")); //true// 设置方法调用抛出异常...为同一个函数调用的不同的返回值或异常做测试桩)when(mockList.get(4)).thenReturn("test2").thenThrow(new RuntimeException()); doReturn...对于部分模拟推荐使用doReturn语法。 // 注2:如果模拟是序列化反序列化,那么这个Answer将无法理解泛型的元数据。
并且对于Mockito来说,如果在执行过程中遇到了void方法,则默认就是执行doNothing。...不过它也有如下的两种测试场景: 1)验证程序的行为-该void方法是否被调用 2)在给定输入参数的情况下方法抛出某种类型的异常 譬如在之前的StockService中增加print方法,并申明为void...when(stockService.print(teslaStock)).thenThrow(new BizException(ep)); 因此,Mockito提供了doThrow的方式来解决,类似还要...doReturn和thenReturn等,在后续的章节中笔者会通过案例来介绍差异。...通过这个测试用例,就展示了如何针对void方法抛出异常的情况进行测试了。
; import org.mockito.Mockito; import org.mockito.internal.verification.Times; import org.powermock.api.mockito.PowerMockito.../ mock 每次调用返回条数(注意每次调用都是这2个) int eachReturnSize = 2; PowerMockito .doReturn...public void test_call_return_map_partition() { // mock 每次调用返回条数 // 注意: // 如果仅调用doReturn...一次,那么每次返回都是key相同的Map, // 如果需要不覆盖,则doReturn次数和 invocations 相同) int eachReturnSize = 3;...PowerMockito .doReturn(mockMap(eachReturnSize)) .doReturn(mockMap
orbit p2 mockito 4、使用Mockito API 4.1 静态引用 如果在代码中静态引用了org.mockito.Mockito....Todo todo = new Todo(5); assertEquals(todo ,c.compareTo(new Todo(1))); } 对于无返回值的函数,我们可以使用doReturn...例如我们想在调用某些无返回值函数的时候抛出异常,那么可以使用doThrow 方法。...List list = new LinkedList(); List spy = spy(list); // 可用 doReturn() 来打桩 doReturn("foo").when(spy).get...(0); // 下面代码不生效 // 真正的方法会被调用 // 将会抛出 IndexOutOfBoundsException 的异常,因为 List 为空 when(spy.get(0)).thenReturn
demo案例的测试用例如下 import static org.junit.Assert.assertEquals; import static org.powermock.api.mockito.PowerMockito.doReturn...; import static org.powermock.api.mockito.PowerMockito.mock; import java.io.BufferedReader; import java.io.FileInputStream...java.io.InputStreamReader; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito...withAnyArguments().thenReturn(inputStreamReaderMock); final String string = "key=value\n"; doReturn...(string).doReturn(null).when(bufferedReaderMock).readLine(); // read && Assert assertEquals
1.1 Mockito是什么?...Mockito是mocking框架,它让你用简洁的API做测试。而且Mockito简单易学,它可读性强和验证语法简洁。...资源 官网: http://mockito.org API文档:http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html 项目源码:https...doThrow(new IOException()).when(outputStream).close(); outputStream.close(); } 模拟方法体抛出异常 @Test...//when(spy.get(0)).thenReturn(3); //使用doReturn-when可以避免when-thenReturn调用真实对象api doReturn
mockito有两种API实现部分/内部方法mock,分别是spy与callRealMethod()。...one"); verify(spy).add("two"); 注意when(spy.size()).thenReturn(100);这个打桩方法会执行这段代码,如果程序不要执行这个方法,直接打桩,可以使用doReturn...list); //会执行spy.get(0)方法导致 throws IndexOutOfBoundsException when(spy.get(0)).thenReturn("foo"); //采用 doReturn...() 打桩 doReturn("foo").when(spy).get(0); doCallRealMethod 对于mock的对象,它的所有方法都会被打桩,不执行真实方法,除非使用doCallRealMethod
在Mockito中,可以使用Spy来实现。...但是,Mockito除了按照测试桩返回预期值之外,还调用了真实的hello()方法,也就是在终端打印出了“hello”。...换一种写法,使用doReturn.when的方式, @Test public void TestSayHello2() { doReturn("Ni hao r u").when(demo).hello...Mockito.reset 在测试过程中,如果在设置了测试桩之后,还想调用真实方法来执行,则可以使用Mockito.reset来重置spy。
1.1 Mockito是什么? ...Mockito是mocking框架,它让你用简洁的API做测试。而且Mockito简单易学,它可读性强和验证语法简洁。...://mockito.org API文档:http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html 项目源码:https://github.com...doThrow(new IOException()).when(outputStream).close(); outputStream.close(); } 模拟方法体抛出异常 @Test...//when(spy.get(0)).thenReturn(3); //使用doReturn-when可以避免when-thenReturn调用真实对象api doReturn
领取专属 10元无门槛券
手把手带您无忧上云