Question

I thought Mockito mocked interfaces through the use of dynamic proxies.

But then I noticed the type of a Mockito-mocked intefaces whilst debugging:

MyInterface$$EnhancerByMockitoWithCGLIB$$9654c88

indicating that CGLIB is used instead of a dynamic proxy.

Can someone please:

  • Clarify my interrogation
  • Point me to the relevant source code location in Mockito
Was it helpful?

Solution

Mockito allows for interchangeable implementations of MockMaker, but by default the implementation is the CGLib-based CglibMockMaker.

There are a few discussions online ("The Power of Proxies in Java" or "What is the difference between JDK dynamic proxy and CGLib?") about the differences between CGLib and standard Proxy objects; when mocking interfaces it seems that Proxy would be perfectly fine, but using CGLib gives you access to mocking actual classes with implementations, and committing to CGLib even beyond when strictly necessary likely makes the code much easier to follow.

OTHER TIPS

In the source of the mockito-core module (I used version 1.9.5) if you follow the code from where MockMaker is used (of which the only implementation in the module is CglibMockMaker), you will see that you arrive at a class called ClassImposterizer. This class contains some Cglib magic (as the comment clearly states). Moreover you can clearly see the use of Cglib Enhancer in the private method createProxyClass

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top