Don’t let mockito confuse you

The new version of mockito comes with a new method: spy. Very useful feature but... bad name!

The mockito's "mock" method creates already a spy object. The "spy" method creates a "proxy" or "proxy spy" object. Totally confusing, isn't it?

The "mock" method is not really awful, because you can also use the double as a mock or just a stub, and it is common to use the name "mock" for all kind of doubles, although still confusing. The benefit from naming the double properly is that it helps programming by intention, which is a big part of Test Driven Development.

I would rename "mock" to "double" and "spy" to "proxy". Anyway, don't forget that, when using the mockito's "spy" method any single call that you don't explicitly stub, will reach the actual object. It is really useful to work with legacy code, in fact, we implemented it in pyDoubles, but using the method "proxy_spy".

Just make sure you understand what kind of test double you use and why. That is what matters in the end 🙂

Enjoyed reading this post?
Subscribe to the RSS feed and have all new posts delivered straight to you.
  • Luca Minudel

    If you are interested into differences between test doubles and their interactions with the design you probably like this: http://blogs.ugidotnet.org/luKa/archive/0001/01/01/tdd-with-mocks-or-spies.aspx

  • Niklas

    The Spy of Mockito is NOT a proxy, but a clone, proxying the method calls to the original object! If you have a member variable in the class that you create a Spy of and you change it after having created the Spy, than, when asking the Spy, you won’t get the changed value but the value that was cloned during the creation of the Spy!