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.

mikej
  • 65,295
  • 17
  • 152
  • 131
Illarion Kovalchuk
  • 5,774
  • 8
  • 42
  • 54

2 Answers2

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.

Alistair A. Israel
  • 6,417
  • 1
  • 31
  • 40
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.

omnomnom
  • 8,911
  • 4
  • 41
  • 50
  • 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 '13 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 01 '13 at 10:23