public Stubber doThrow(Class<? extends Throwable> toBeThrown) { answers.add(new ThrowsExceptionClass(toBeThrown)); return this; }
private OngoingStubbing<T> thenThrow(Class<? extends Throwable> throwableClass) { return thenAnswer(new ThrowsExceptionClass(throwableClass)); }
/** * Use <code>doThrow()</code> when you want to stub the void method to throw exception of specified class. * <p> * A new exception instance will be created for each method invocation. * <p> * Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler does not like void methods inside brackets... * <p> * Example: * * <pre class="code"><code class="java"> * doThrow(RuntimeException.class).when(mock).someVoidMethod(); * </code></pre> * * @param toBeThrown to be thrown when the stubbed method is called * @return stubber - to select a method for stubbing * @since 1.9.0 */ public static Stubber doThrow(Class<? extends Throwable> toBeThrown) { return MOCKITO_CORE.doAnswer(new ThrowsExceptionClass(toBeThrown)); }
Foo myMock = Mockito.mock(Foo.class,new ThrowsExceptionClass(IllegalArgumentException.class)); Mockito.when(myMock.doSomething(Matchers.eq("1"))).thenReturn("1");
Iterator themock = mock(Iterator.class, new ThrowsExceptionClass(UnsupportedOperationException.class)); doReturn(false).when(themock).hasNext(); assertFalse(themock.hasNext());
public Stubber doThrow(Class<? extends Throwable> toBeThrown) { answers.add(new ThrowsExceptionClass(toBeThrown)); return this; }
private OngoingStubbing<T> thenThrow(Class<? extends Throwable> throwableClass) { return thenAnswer(new ThrowsExceptionClass(throwableClass)); }
/** * Use doThrow() when you want to stub the void method to throw exception of specified class. * <p> * A new exception instance will be created for each method invocation. * <p> * Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler does not like void methods inside brackets... * <p> * Example: * * <pre> * doThrow(RuntimeException.class).when(mock).someVoidMethod(); * </pre> * * @param toBeThrown to be thrown when the stubbed method is called * @return stubber - to select a method for stubbing */ public static Stubber doThrow(Class<? extends Throwable> toBeThrown) { return MOCKITO_CORE.doAnswer(new ThrowsExceptionClass(toBeThrown)); }