Skip to content

Instantly share code, notes, and snippets.

@MichalAdorno
Created January 3, 2019 14:04
Show Gist options
  • Save MichalAdorno/d51b19ae8f380f1e0d9e66b692c6c140 to your computer and use it in GitHub Desktop.
Save MichalAdorno/d51b19ae8f380f1e0d9e66b692c6c140 to your computer and use it in GitHub Desktop.
@SpyBean vs @MockBean /spies vs mocks in programmatic testing
/*
@MockBean //or Mockito's @Mock
- it mocks the object and all its methods with do nothing and their result value will be null,
- use for example: when(...) methods to create mocked method behaviour
- use when you want to completely get rid of the object's normal behaviour
- caution: unmocked methods won't work -> can result in a RuntimeException during tests (@SpyBean is a remedy here apart from wider mocking)
@SpyBean //or Mockito's @Spy
- an object will behave like an @Autowired object
- all its methods will actually works, but we can define some custom behavior for its methods
- use doReturn(...) / doNothing(...) to add custom (mocked) method behaviour
- use if you want to provide your mock behaviour but not dismiss entirely its normal behaviour
*/
@Mock
private List<String> mockList;
@Spy
private List<String> spyList = new ArrayList();
@Test
public void testMockList() {
//by default, calling the methods of mock object will do nothing
mockList.add("test");
assertNull(mockList.get(0));
}
@Test
public void testSpyList() {
//spy object will call the real method when not stub
spyList.add("test");
assertEquals("test", spyList.get(0));
}
@Test
public void testMockWithStub() {
//try stubbing a method
String expected = "Mock 100";
when(mockList.get(100)).thenReturn(expected);
assertEquals(expected, mockList.get(100));
}
@Test
public void testSpyWithStub() {
//stubbing a spy method will result the same as the mock object
String expected = "Spy 100";
//take note of using doReturn instead of when
doReturn(expected).when(spyList).get(100);
assertEquals(expected, spyList.get(100));
}
//source: https://javapointers.com/tutorial/difference-between-spy-and-mock-in-mockito/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment