import static org.mockito.Mockito.*; public class ExampleTest { @Test(expected = SomeException.class) public void testMethod() throws SomeException { // 创建模拟对象 SomeClass mock = mock(SomeClass.class); // 指定模拟
而不执行方法代码EN// GivenclassIWantToMock=mock(ClassIWantToMock.class);// WhendoThrow(newBadReq...
我有一个返回类型为 void 的方法。它还可以抛出许多异常,所以我想测试抛出的那些异常。由于相同的原因,所有尝试都失败了: Stubber 类型中的 when(T) 方法不适用于参数 (void) 有什么想法可以让方法抛出指定的异常吗? doThrow(new Exception()).when(mockedObject.methodReturningVoid(...)); 原文由 edwardm...
public void test() { MockitoAnnotations.initMocks(this); // 这种写法可以达到效果 doThrow(new RuntimeException("异常")).when(exampleService).hello(); try { exampleService.hello(); Assert.fail(); } catch (RuntimeException ex) { Assert.assertEquals("异常", ex.getMessage()); } } } 1. ...
最初接触 Mockito 还思考并尝试过如何用它来 mock 返回值为 void 的方法,然而 Google 查找到的一般都会说用doThrow()的办法 doThrow(new RuntimeException()).when(mockObject).methodWithVoidReturn(); 因为无法使用常规的when(mockObject.foo()).thenReturn(...)的方法。
@Test(expected = InvalidParamException.class) public void testUpdateNameThrowExceptionWhenIdNull() { doThrow(new InvalidParamException()) .when(mockedUserRepository).updateName(null,anyString(); userService.updateName(null,"FunTester"); } 使用doCallRealMethod()进行真实方法调用 有时有必要从模拟对...
doReturn(false).when(listMock).add(anyString()); boolean added = listMock.add(randomAlphabetic(6)); assertThat(added,is(false)); 3.when().thenThrow()模拟异常(方法返回类型非void) @Test(expected = IllegalStateException.class)publicvoid givenMethodIsConfiguredToThrowException_whenCallingMethod_then...
public void when_thenReturn(){ //mock一个Iterator类 Iterator iterator = mock(Iterator.class); //预设当iterator调用next()时第一次返回hello,第n次都返回world when(iterator.next()).thenReturn("hello").thenReturn("world"); /// //注意:!!!这边的模拟的方法中参数都必须要一致的,否则返回结果不是...
class}) public class MockPrivateMethodTest { @Spy private MockService mockService = new MockService(); @Test public void mock() throws Exception { String a = "1"; String b = "b"; PowerMockito.doReturn("re").when(mockService, "privateMethod", a); String s = mockService.publicMethod(...
我确实明白,当第一次调用 voidMehtod() 时什么都不返回,第二次它给出异常。 但是,如果我们删除 doNothing.doThrow(Exception.class).when(b).voidMethod(); ,测试是否仍然有效并且将测试我们想要测试的方法第二次抛出异常? 原文由 MIKE 发布,翻译遵循 CC BY-SA 4.0 许可协议 java...