When i create a mock object of say class Employee. It doesnt call the constructor of Employee object. I know internally Mockito uses CGLIb and reflection, creates a proxy class that extends the class to mock. If it doesnt call the constructor of employee how is the mock instance of employee class created ?
-
1I think your best bet would be to look at the souce code. To my understanding it seems the mock class creation happens in the method "imposterise" in the class ClassImposterizer. Here is the link to above mentioned class: http://mockito.googlecode.com/svn/trunk/src/org/mockito/internal/creation/jmock/ClassImposterizer.java – sateesh Jun 29 '10 at 06:24
2 Answers
Mockito uses CGLib to generate class object. However to instantiate this class object it uses Objenesis http://objenesis.org/tutorial.html
Objenesis is able to instantiate object without constructor using various techniques (i.e. calling ObjectStream.readObject and similar).

- 4,254
- 29
- 35
-
-
3Apparently they moved to new domain and project is now on github. I fixed the link – Tibor Blenessy Jul 01 '15 at 14:09
Mockito is using reflection and CGLib to extend the Employee class with a dynamically created superclass. As part of this, it starts by making all the constructors of Employee public - including the default constructor, which is still around but private if you declared a constructor which takes 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 presume that it calls the default constructor when the superclass is created, though I haven't tested that. You could test it yourself by declaring the private default constructor Employee() and putting some logging in it.

- 17,277
- 4
- 47
- 92
-
1
-
-
Mockito calls the constructor of the generated class (presumably to avoid side effects of calling the constructor of the target type) – iwein Oct 02 '10 at 03:52