Skip to content

Instantly share code, notes, and snippets.

@andrewrlee
Created April 3, 2015 08:14
Show Gist options
  • Select an option

  • Save andrewrlee/4763b5950f6b002af7dd to your computer and use it in GitHub Desktop.

Select an option

Save andrewrlee/4763b5950f6b002af7dd to your computer and use it in GitHub Desktop.
Mockito Spys
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.mockito.Mockito.*;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class MockitoSpyTest {
@Test
public void verifyMethodIsCalledWithoutCallingRealImpl() {
TestObject1 spy = spy(new TestObject1());
doNothing().when(spy).print();
spy.doIt();
verify(spy).doIt();
verify(spy).print();
}
@Test
public void verifyDecoratingAnObjectWithoutActuallyCallingConstructor() {
TestObject2 spy = spy(new TestObject2());
TestObject2 decorated = mock(TestObject2.class);
doReturn(decorated).when(spy).wrapIt(spy);
spy.wrap();
verify(spy).wrapIt(spy);
verify(decorated).print();
}
public static class TestObject1 {
public void doIt() {
print();
}
void print() {
throw new RuntimeException("PRINT: OH NO!");
}
}
public static class TestObject2 {
public void wrap() {
wrapIt(this).print();
}
public TestObject2 wrapIt(TestObject2 user) {
return new DecoratedTestObject2(user);
}
void print() {
throw new RuntimeException("PRINT: OH NO!");
}
public static class DecoratedTestObject2 extends TestObject2 {
public DecoratedTestObject2(TestObject2 user) {
throw new RuntimeException("DECORATOR CONSTRUCTOR: OH NO!");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment