Say I’ve got a mock setup like this:
JUnit4Mockery context = new JUnit4Mockery();
MyInterface mock = context.mock(MyInterface.class);
And later I want to examine my mock object to find out what class it’s mocking:
Class mockedClass = mock.??? //would return MyInterface.class
I didn’t see anything obvious in the JMock (2.5.1) javadocs about how to do this – the signature for the mock method is
<T> T mock (Class<T> typeToMock)
In previous versions (I looked at 1.2.0) you would create a Mock object directly, and one of its methods was
Class getMockedType()
What I’m trying to achieve is a unit testing framework for using DI inside my unit tests. (I’m using Guice 3.0.) Having DI in the tests is a restriction of the application server/platform I’m working with – the objects I’m testing are subclasses of a multiton that has its own Injector, which is what I’m trying to populate.
I’d prefer not to have to create an anonymous instance of AbstractModule in every test, so I’m trying to build something like this (this seems like it would have worked in 1.2):
public class MockModule extends AbstractModule {
private Iterable<Mock> mocks;
public MockModule(Iterable<Mock> mocks) {
this.mocks = mocks;
}
protected void configure() {
for (Mock mock : mocks) {
bind(mock.getMockedType()).toInstance(mock);
}
}
}
The only thing missing is the answer (if there is one) to this question.
RESPONSE TO ACCEPTED ANSWER
Here is what I ended up creating for this use case:
import java.lang.reflect.Proxy;
import com.google.common.collect.Lists;
import com.google.inject.AbstractModule;
@SuppressWarnings({ "rawtypes", "unchecked" })
public class MockModule extends AbstractModule {
private final Iterable mocks;
public MockModule(Object mock) {
mocks = Lists.newArrayList(mock);
}
public MockModule(Iterable mocks) {
this.mocks = mocks;
}
protected void configure() {
for (Object mock : mocks) {
Class superclass = mock.getClass().getSuperclass();
if (superclass != Object.class && superclass != Proxy.class) {
bind(superclass).toInstance(mock);
continue;
}
Class[] interfaces = mock.getClass().getInterfaces();
if (interfaces.length > 0) {
bind(interfaces[0]).toInstance(mock);
}
}
}
}
Will print:
There are possibly more robust ways to do it, but it gets the job done for this particular JMock version at least.