For example, I have the following code:
SomeClass stub = Mockito.mock(SomeClass.class);
After that, stub is a normal implementation o开发者_如何学Pythonf 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.
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.
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.
精彩评论