2

For example, I have the following code:

SomeClass stub = Mockito.mock(SomeClass.class);

After that, stub is a normal implementation of SomeClass, but with its own behavior (default is to just throw some exception, but that's ok)

How can I do the same thing for my library? I would like to be able to wrap some classes, or even better instances with some wrap() method, to mix-in my behavior there.

2 Answers 2

4

Both jmock and Mockito (which uses jmock code) use cglib internally to create their stubs/proxies. See ClassImposterizer.

For simple cases, you can use Java's Proxy mechanism to create dynamic proxies (really just invocation handlers) of interfaces you want to stub or mock.

0
0

It's a proxy design pattern. Proxy implements mocked interface / extends mocked class, so it can be casted to the mocked type. It can also delegate responsibility to the 'real implementation' if required. Usually, such proxy stub is created with a little mix of reflection.

2
  • not an actual answer - question was what to use - as in what framework/library etc, not how it works as a concept or what design pattern it is
    – Stef
    Feb 28, 2013 at 23:57
  • The question was "How can I do the same thing for my library?" not "what particular class I need to use". And my answer is - use proxies - how they are created it doesn't matter. It can be done in dozens of ways...
    – omnomnom
    Mar 1, 2013 at 10:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.