1 minute read

Mockito spy usage

Spy is another variation of Mock from mockito. This post is not about usage of Spy or Mock vs Spy rather showcase one of the quirks I encountered.

Below is my class that is under test

public interface SomeService {
    void findUser() throws Exception;
}
public Class ServiceImpl implements SomeService {
  
  @Override
  public void findUser() throws Exception{
      ExternalReference externalRef=
SomeStatic.getExternalRefernce();
  }
}

when I am writing a mock test, since the external reference is invoked within a public method and it being a static reference, it is hard to mock such type of class.

Using TestDrivenMethodology (TDD) starting with unit tests helped me identify this and able to avert it by moving the reference as separate public method.

public Class ServiceImpl implements SomeService {
public ExternalReference getExternalReference(){
      return SomeStatic.getExternalReference();
  }  
  
  @Override
  public void findUser() throws Exception{
      ExternalReference externalRef = getExternalReference();
  }
}

with above change, I am one step closer.

Since I am writing my mock for my interface, here my public method getting the reference is not part of my interface, so using Mock annotation is not going to help me. Here our Spy comes handy.

public class ServiceTest {
    // reason we are using spy here is since the method getExternalReference is public method in the concrete implementations but not defined in interface.
    private ServiceImpl serviceImpl = spy(new ServiceImpl());
@Mock
private SomeExternalReference externalRef;
@Before
public void init() throws Exception {
        MockitoAnnotations.initMocks(this);
         // when used spy, below is the syntax that need to be used otherwise real method will get invoked.
        Mockito.doReturn(externalRef).when(serviceImpl).getExternalReference();
    }
}

I am going to use Spy here and use doReturn instead of regular when construct.

Summary

May be there might be a better way of doing references as injected beans, if that is not the case Mockito provides features that can be helpful.