I want to make constructor.newInstance(...)
throw an exception in a unit test. I'd like to check if the else-branch is reached in the following (dummy-)code:
public <T extends IInterface> instantiate(final Constructor<IInterface> constructor) {
try {
return constructor.newInstance(arg);
} catch (Exception e) {
return null;
}
}
I'd like to reach the null
case. Can I mock that without using (Power)Mockito?
I could theoretically do
class TestImplementation implements IInterface {
public TestImplementation(Arg.class) {
throw new InstantiationException("just for your test case");
}
}
But I'm curious whether or not I can achieve this with mocking.
The class java.lang.Constructor
is final, so mocking is hard by default. The latest versions of Mockito support mocking final classes, EasyMock does not to my knowledge.
Thus, your choices are probably:
- Mockito (latest versions, with the new experimental "mocking of final" enabled)
- PowerMock(ito)
- JMockit
And for the record: passing in a Class instance of some "dummy" class, like you suggest within the question is way better than using a mocking framework.
You have to understand: you don't use mocking because you can. You only use it when you have to! In your case, there is a simple, straight forward non-mocking solution to test your production code.
So: use TestImplementation.class
and forget about using a mocking framework here.