concept spy in category java

appears as: spies, A spy, spy
Java Testing with Spock

This is an excerpt from Manning's book Java Testing with Spock.

I’m always baffled by questions in Stack Overflow and other forums and mailing lists indicating that people have difficulties with mocking because they try to mock the class under test instead of its collaborators. Some advanced unit tests need this (I’ll show you spies in chapter 8), but this technique is only for extreme corner cases of legacy code. In vanilla unit tests, the class under test is always a real class. Mocks are used for its collaborators only. Even then, not all collaborators need to be mocked.

  • Using spies as partial mocks (continuing fake objects from chapter 6)
  • Spies are a controversial feature (not just with Spock[1]), so make sure that you understand the implications of using them in your unit tests (and what that means for your Java production code). Use of spies implies that your Java code suffers from design problems, as you’ll see in the last section.

    1 Mockito’s official documentation also has a huge warning against the usage of spies.

    8.3.4. Replacement of spies with mock

    You use spies with the security utility because you can’t refactor the Java code first, as this would invalidate the digital signature of the binary. If that constraint didn’t hold, you’d instead modify the Java code to properly use dependency injection. An obvious decoupling of dependencies is shown in the following listing.

    Listing 8.25. Refactoring Java code to avoid spies