0

I have an object with no interface (I can't change this), I was able to mock it using

Mock mockedClass = mock(ObjectExample.class, "returnObject",
            new Class[ ]{java.lang.Integer, java.lang.Integer},
            new Object[ ]{1,9001});

This object is successfully mocked, and on debugging I can see the parameters are being successfully set, my question is how can I then use this mocked object; for example how would I return the object returnOnject to use later on in the code, and to mock out calls to this object?

Edit: I am using JMock with CGLIB

Matt C
  • 137
  • 1
  • 3
  • 15

1 Answers1

0

If I were you, I would not use jMock outside a unit test but use a proxy framework such as cglib or javassist directly. You can create a proxy of ObjectExample which basically represents a subclass of this mocked class. You can then use this subclass object by the type of ObjectExample.

Here is an example of how you can create a proxy with cglib:

@Test
public void testMethodInterceptor() throws Exception {
  Enhancer enhancer = new Enhancer();
  enhancer.setSuperclass(ObjectExample.class);
  enhancer.setCallback(new MethodInterceptor() {
    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy)
        throws Throwable {
      if(method.getName().equals("returnObject")) {
        // Add your proxy logic here.
      } else {
        proxy.invokeSuper(obj, args);
      }
    }
  });
  ObjectExample proxy = (ObjectExample) enhancer.create();
}
Rafael Winterhalter
  • 42,759
  • 13
  • 108
  • 192