Search code examples
javaweblogicjmockit

jmockit class cast exception


I'm trying to mock some webogic classes and interfaces to test a method that does this:

void init(oracle.wsm.policy.model.IAssertion assertion,....) {
...    
oracle.wsm.policy.model.IAssertionBindings bindings = ((oracle.wsm.policy.model.impl.SimpleAssertion) assertion).getBindings();
...
}

And my test code looks like this:

  @Test
  public final void testInit() {


  IAssertion assertionMock = new MockUp<IAssertion>() {
      @Mock
      QName getQName() {
        return new QName("qname");
      }
   }.getMockInstance();


   CustomAuditPolicy custom = new CustomAuditPolicy();
   custom.init(assertionMock);

And I'm getting:

java.lang.ClassCastException: $Impl_IAssertion cannot be cast to oracle.wsm.policy.model.impl.SimpleAssertion
    at xxx.CustomAuditPolicy.init(CustomAuditPolicy.java:82)
    at xxx.CustomAuditPolicyTest.testGetAssertionName(CustomAuditPolicyTest.java:190)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

The SimpleAssertion class implements IAssertion so I've been trying to mock the SimpleAssertion class as well but still getting the same error.

Can someone explain me how to use jmockit in such scenario?


Solution

  • You would need to mock the SimpleAssertion implementation class in this case, because that's what the method under test expects. Using MockUp<IAssertion> on the interface will simply get you a dynamic proxy class which is not SimpleAssertion, therefore the ClassCastException.