How mockito instantiates a mock object

When I create an object layout from the Employee class. It does not call the constructor of the Employee object. I know that inside Mockito uses CGLIb and reflection, creates a proxy class that extends the class to make fun of. If it does not call the employee constructor, how is a boilerplate instance of the employee class created?

+7
java constructor testing mockito
source share
2 answers

Mockito uses CGLib to generate a class object. However, to create an instance of this class, the object uses Objenesis http://objenesis.org/tutorial.html

Objenesis is able to instantiate an object without constructors using various methods (i.e. calling ObjectStream.readObject, etc.).

+6
source share

Mockito uses reflection and CGLib to extend the Employee class to a dynamically created superclass. As part of this, it starts with all Employee public constructors - including the default constructor, which is still around, but private if you declared a constructor that accepts parameters.

public <T> T imposterise(final MethodInterceptor interceptor, Class<T> mockedType, Class<?>... ancillaryTypes) { try { setConstructorsAccessible(mockedType, true); Class<?> proxyClass = createProxyClass(mockedType, ancillaryTypes); return mockedType.cast(createProxy(proxyClass, interceptor)); } finally { setConstructorsAccessible(mockedType, false); } } private void setConstructorsAccessible(Class<?> mockedType, boolean accessible) { for (Constructor<?> constructor : mockedType.getDeclaredConstructors()) { constructor.setAccessible(accessible); } } 

I assume that it calls the default constructor when creating the superclass, although I have not tested it. You can test it yourself by declaring the private constructor Employee () and putting several protocols into it.

+1
source share

All Articles