Explain Codes LogoExplain Codes Logo

How to verify a method of a non-mock object is called?

java
mockito
testing
dependency-injection
Nikita BarsukovbyNikita Barsukov·Feb 22, 2025
TLDR

For capturing calls on real objects, use Mockito.spy. Create a spy of your instance, implement the method, and finally, verify the call.

YourClass realObject = new YourClass(); YourClass spy = Mockito.spy(realObject); spy.methodToVerify(); Mockito.verify(spy).methodToVerify(); // Spy, don't pry

To test whether a method is called on a real object, spying is the goto guy. It's different from mocks; spies encapsulate real objects and delegate calls to them. This method allows you to use the real object's behavior while monitoring its interaction.

Spies: Aligning Forces with the Real Object

The @Spy annotation comes in handy to declare spies in your test:

@Spy YourClass mySpy; // Inside the testing method Mockito.verify(mySpy).methodToVerify(); // Spy is the new judge in town

Here, we use the @Spy annotation, which saves us from creating a spy manually. This method proves to be fruitful in contexts like Spring, where dependency injection is supported.

Behavioral Testing: Turn the Spy Mode On

Spies jump into action when you need to perform behavioral testing on real objects. Instead of swapping functional behavior with a mock, you can assure that the class under examination interacts as expected with complex legacy code or third-party libraries.

Sinkholes Along the Way

While using spies, you might stumble upon the following issues:

  • Spies can lead to flaky tests if the underlying behavior isn't stable.
  • Overuse of spies may lead to unfocused, overly verbose tests.
  • Employ spies wisely in your tests. Some operations might still use real objects if spies aren't properly injected.

Spy Agencies Best Practices

  • Recruit spies to wrap critical dependencies, don't try to spy the entire world.
  • Senior spies should verify integration points to confirm if they are being utilized as expected.
  • Remember, dependency injection can easily give a real object a spy makeover.