Mockito - spy vs mock

杀马特。学长 韩版系。学妹 提交于 2019-11-26 12:54:19

问题


Mockito - I understand a spy calls the real methods on an object, while a mock calls methods on the double object. Also spies are to be avoided unless there is a code smell. However, how do spies work and when should i actually use them? How are they different from mocks?


回答1:


Technically speaking both "mocks" and "spies" are a special kind of "test doubles".

Mockito is unfortunately making the distinction weird.

A mock in mockito is a normal mock in other mocking frameworks (allows you to stub invocations; that is, return specific values out of method calls).

A spy in mockito is a partial mock in other mocking frameworks (part of the object will be mocked and part will use real method invocations).




回答2:


Both can be used to mock methods or fields. The difference is that in mock, you are creating a complete mock or fake object while in spy, there is the real object and you just spying or stubbing specific methods of it.

While in spy objects, of course, since it is a real method, when you are not stubbing the method, then it will call the real method behavior. If you want to change and mock the method, then you need to stub it.

Consider the example below as a comparison.

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 MockSpy {
 
    @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");

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

        Mockito.verify(spyList).add("test");
        assertEquals(1, spyList.size());
        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));
    }
}

When shoud you use mock or spy? If you want to be safe and avoid calling external services and just want to test the logic inside of the unit, then use mock. If you want to call external service and perform calling of real dependency, or simply say, you want to run the program as it is and just stub specific methods, then use spy. So that’s the difference between spy and mock in mockito.




回答3:


The best place to start is probably the docs for mockito.

On a general note the mockito mock allows you to create stubs.

You would create a stub method if, for example, that method does an expensive operation. Say, it gets a database connection, retrieves a value from the database and returns it to the caller. Getting the db connection might take 30 seconds, slowing your test execution to the point where you'll likely context switch (or stop running the test).

If the logic you are testing doesn't care about the database connection then you could replace that method with a stub which returns a hard coded value.

The mockito spy lets you check whether a method calls other methods. This can be very useful when trying to get legacy code under test.

It is usful if you are testing a method that works through side effects, then you would use a mockito spy. This delegates calls to the real object and allows you to verify method invocation, number of times invoked etc.




回答4:


TL;DR version,

With mock, it creates a bare-bone shell instance for you.

List<String> mockList = Mockito.mock(ArrayList.class);

With spy you can partially mock on an existing instance

List<String> spyList = Mockito.spy(new ArrayList<String>());

Typical use case for Spy: the class has a parameterized constructor, you want to create the object first.




回答5:


I have created a runable example here https://www.surasint.com/mockito-with-spy/

I copy some of it here.

If you have something like this code:

public void transfer( DepositMoneyService depositMoneyService, 
                      WithdrawMoneyService withdrawMoneyService, 
                      double amount, String fromAccount, String toAccount) {
    withdrawMoneyService.withdraw(fromAccount,amount);
    depositMoneyService.deposit(toAccount,amount);
}

You may don't need spy because you can just mock DepositMoneyService and WithdrawMoneyService.

But with some legacy code, dependency is in the code like this:

    public void transfer(String fromAccount, String toAccount, double amount) {
        this.depositeMoneyService = new DepositMoneyService();
        this.withdrawMoneyService = new WithdrawMoneyService();
        withdrawMoneyService.withdraw(fromAccount,amount);
        depositeMoneyService.deposit(toAccount,amount);
    }

Yes, you can change to the first code but then API is changed. If this method is being used by many places, you have to change all of them.

Alternative is that you can extract the dependency out like this:

    public void transfer(String fromAccount, String toAccount, double amount){
        this.depositeMoneyService = proxyDepositMoneyServiceCreator();
        this.withdrawMoneyService = proxyWithdrawMoneyServiceCreator();
        withdrawMoneyService.withdraw(fromAccount,amount);
        depositeMoneyService.deposit(toAccount,amount);
    }

    DepositMoneyService proxyDepositMoneyServiceCreator() {
        return new DepositMoneyService();
    }

    WithdrawMoneyService proxyWithdrawMoneyServiceCreator() {
        return new WithdrawMoneyService();
    }

Then you can use the spy the inject the dependency like this:

DepositMoneyService mockDepositMoneyService = mock(DepositMoneyService.class);
        WithdrawMoneyService mockWithdrawMoneyService = mock(WithdrawMoneyService.class);

    TransferMoneyService target = spy(new TransferMoneyService());

    doReturn(mockDepositMoneyService)
            .when(target)
            .proxyDepositMoneyServiceCreator();

    doReturn(mockWithdrawMoneyService)
            .when(target)
            .proxyWithdrawMoneyServiceCreator();

More detail in the link above.




回答6:


I like the simplicity of this recommendation:

  • If you want to be safe and avoid calling external services and just want to test the logic inside of the unit, then use mock.
  • If you want to call external service and perform calling of real dependencies, or simply say, you want to run the program as it is and just stub specific methods, then use spy.

Source: https://javapointers.com/tutorial/difference-between-spy-and-mock-in-mockito/

A common difference is:

  • If you want to directly stub the method(s) of a dependency, then Mock that dependency.
  • If you want to stub the data in a dependency so that all its methods return testing values that you need, then Spy that dependency.



回答7:


You can follow the below blog url where its compared with below points :

  1. Object declaration
  2. When the methods are not mocked
  3. When the method is mocked

https://onlyfullstack.blogspot.com/2019/02/mockito-mock-vs-spy.html Main tutorial url - https://onlyfullstack.blogspot.com/2019/02/mockito-tutorial.html



来源:https://stackoverflow.com/questions/28295625/mockito-spy-vs-mock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!