Imposteriser produces ClassCastException when JUnit tests are run with Ant.
Imposteriser produces ClassCastException when JUnit tests are run with Ant.
Hi All, just wasted a day on this.
I am mocking Concrete classes using the standard Imposteriser.INSTANCE.
The tests run fine under the Eclipse IDE.
However when the same tests are run using the Ant JUnit task they fail with a ClassCastException.
The condition required to reproduce this bug is to mock a concrete class (or its subclass) more than
once over several test classes. Typically the first use of the Mock class succeeds, but subsequent
Test classes using the same mocked concrete class fail. Commenting out the first usage
will allow the second usage (which failed) to succeed.
Debugging into the code seems to show CGLIBed instances of the expected class.
The failure is in:
public <T> T imposterise(final Invokable mockObject, Class<T> mockedType, Class<?>... ancilliaryTypes) {
if (!mockedType.isInterface() && toStringMethodIsFinal(mockedType)) {
throw new IllegalArgumentException(mockedType.getName() + " has a final toString method");
}
try {
setConstructorsAccessible(mockedType, true);
Class<?> proxyClass = createProxyClass(mockedType, ancilliaryTypes);
return mockedType.cast(createProxy(proxyClass, mockObject));
}
finally {
setConstructorsAccessible(mockedType, false);
}
}
On this line:
return mockedType.cast(createProxy(proxyClass, mockObject));
I have converted my own classes to use interfaces and removed imposteriser (using just interfaces with the imposteriser also fails).
However I am now stuck because I am also mocking 3rd part classes.
Any workarounds appreciated.
P.S. I have upgraded from 2.5.1 to 2.6.o without improvement.