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;

public class MockSpyExample {

 private List mockList;

 private List spyList = new ArrayList();

 public void mockListTest() {
  // without stubing, by default, calling the methods of mock object will
  // do nothing

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

 public void mockWithStubTest() {
  // try stubbing a method
  String expected = "Mock call on 100";

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

 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

  assertEquals(expected, spyList.get(100));

No comments:

Post a Comment