32

Using EasyMock I want to be able to say that I expect a specific method called on my mock, but I do not care about the parameter which are used to call the mock.

SomeInterface mock = EasyMock.createMock(SomeInterface.class);
mock.send(/*anything*/);
replay(mock);

/* Perform actions that will eventually invoke mock */

verify(mock);

Is this possible, and how?

Additionally if I want to accept any object that derives from a specific base class, how do I specify that?

Bjarke Freund-Hansen
  • 28,728
  • 25
  • 92
  • 135

2 Answers2

38

To accept any object as parameter:

mock.send(anyObject());

(You may need to cast the expression to the desired type.)

In addition, to accept any object of a specific type, use:

mock.send(isA(SomeObject.class));
Zoltán
  • 21,321
  • 14
  • 93
  • 134
Péter Török
  • 114,404
  • 31
  • 268
  • 329
  • 1
    What is the difference between anyObject(clazz.class) and isA(clazz.class) ? – bschandramohan Jun 19 '13 at 17:44
  • 1
    @ChandraMohan as far as I can see, there is no `anyObject(clazz.class)`, only `anyObject()`, which returns an instance of `Object`, and `isA(clazz.class)` returns an instance of type `clazz`, which is exactly the difference between them. – Zoltán Mar 27 '14 at 09:50
  • PS: the `anyObject()` is a static method from EasyMock. So, you can use `EasyMock.anyObject()`. – Dherik Apr 24 '16 at 21:26
2

Additionally if I want to accept any object that derives from a specific base class, how do I specify that?

mock.send(anyObject(Myclass.class));
jbleduigou
  • 139
  • 7
  • 7
    No! This does not work! This is the first I tried, however it will verify with success even if the actual object does not derive from `Myclass`. This notation is only to avoid having to cast the result from `anyObject()` to what `mock.send()` expects. It does *not* verify that the method is called with a class that derives from `Myclass`. You have to use `isA()` as shown in Péter Töröks answers. – Bjarke Freund-Hansen Aug 29 '11 at 11:39
  • Interesting. Thanks for sharing :) – jbleduigou Sep 07 '11 at 14:35