Is it possible to create a mock object that implements several interfaces with EasyMock?
For example, interface Foo
and interface Closeable
?
In Rhino Mocks you can provide multiple interfaces when creating a mock object, but EasyMock's createMock()
method only takes one type.
Is it possbile to achieve this with EasyMock, without resorting to the fallback of creating a temporary interface that extends both Foo
and Closeable
, and then mocking that?
have you considered something like:
and then mock interface Bar?
An alternative of the most voted answer still based on Mockito but with annotations. You can set the
extraInterfaces
directly from theMock
annotation as next:NB:
extraInterfaces
is of typeClass<?>[]
so you can specify several interfaces if needed.If you need to mock method calls of the extra interfaces you will need to cast your mock. For example let's say that I want to throw an
IOException
when I callclose()
on my mockfoo
, the corresponding code would then be:To the best of my knowledge, the only mocking tool for Java that has explicit support for mocking multiple interfaces is JMockit. (My inspiration for adding this feature came from Moq and Rhino Mocks, which are .NET tools.)
An example (from the
mockit.ExpectationsUsingMockedTest
JUnit 4 test class):Dependency
andRunnable
are interfaces. ThedoSomething
method belongs to the first, andrun
to the second.Although I fundamentally agree with Nick Holt's answer, I thought I should point out that mockito allows to do what you ask with the following call :
Obviously you'll have to use the cast:
(Bar)mock
when you need to use the mock as aBar
but that cast will not throwClassCastException
Here is an example that is a bit more complete, albeit totally absurd:
EasyMock doesn't support this so you're stuck with fallback of the temporary interface.
As an aside, I smell a little bit of a code wiff - should a method really be treating an object as 2 different things, the
Foo
andCloseable
interface in this case?This implies to me that the method is performing multiple operations and while I suspect one of those operations is to 'close' the
Closeable
, wouldn't it make more sense for the calling code to decide whether or not the 'close' is required?Structuring the code this way keeps the 'open' and 'close' in the same
try ... finally
block and IMHO makes the code more readable not to mention the method more general and allows you to pass objects that only implementFoo
.Another way to solve this problem is to use a CGLib mixin:
Whether or not this is a good idea, it's something up to discussion...