Wednesday, July 24, 2019

Mock Vs Spy In Mockito

Mock Vs Spy Example in Mockito.

@Mock:- This is used to mock an object and stub that. If we don't stub mock object method and call method on it then it will do noting and return null.
@Spy:- This is used while we want to use real object without stub i.e. spy object will call the real method when not stub. but if stubbing a spy method, it will result the same as the mock object. but we can define custom behavior for its methods (via doReturn())

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;

import java.util.ArrayList;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class MockSpyExample {

 @Mock
 private List mockList;

 @Spy
 private List spyList = new ArrayList();

 @Test
 public void mockListTest() {
  // without stubing, by default, calling the methods of mock object will
  // do nothing
  mockList.add("Abc");
  assertNull(mockList.get(0));
 }

 @Test
 public void spyListTest() {
  // spy object will call the real method when not stub
  spyList.add("test");
  assertEquals("test", spyList.get(0));
 }

 @Test
 public void mockWithStubTest() {
  // try stubbing a method
  String expected = "Mock call on 100";
  when(mockList.get(100)).thenReturn(expected);

  assertEquals(expected, mockList.get(100));
 }

 @Test
 public void spyWithStubTest() {
  // 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));
 }
}

No comments:

Post a Comment