21

I've seen a few questions out there regarding this but I can't seem to make sense of any of the answers for my particular problem.

I have a mock object, lets call "object1", which I send to some method for testing, lets call testMethod(). So I end up calling

testMethod(object1);

for testing. Now somewhere in this testMethod, there will be a part where it calls a method

object1.toggleDisplay();

which is a void method. If the method were like

object1.getDisplay()

where it actually returns something, I usually do

EasyMock.expect(object1.getDisplay()).andReturn(whatever);

However, this is a void method, and I would like to just test that this has been indeed been called for a certain amount of times. What is the easiest way to do this?

Thanks

KWJ2104
  • 1,959
  • 6
  • 38
  • 53

2 Answers2

23

If things haven't changed in the last few years, you use expectLastCall when setting up your expectations.

object1.toggleDisplay();
object.expectLastCall();
hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
  • 1
    Wait so I have to put object.expectLastCall() inside my actual method? I have my Unit test classes and my actual program classes separated, and would prefer not to have unit test code inside my actual program. – KWJ2104 Jul 30 '12 at 05:01
  • No, you put the method call and `expectLastCall().times(NUM_TIMES)` inside your unit test where you would have previously have used `EasyMock.expect(object1.getDisplay()).andReturn(whatever)` – DoctorRuss Jul 30 '12 at 08:37
  • Is there any way I can do this to target specific methods? Like for example I have methods toggleOn() and toggleOff() – KWJ2104 Jul 30 '12 at 17:17
  • Yes: just add `expectLastCall()` after each method expectation. It applies to the definition of the last (most recent) call :-) If in doubt, try it out! – DoctorRuss Jul 31 '12 at 08:18
10
object1.toggleDisplay();
EasyMock.expectLastCall().times(5);

or if you import statically the EasyMock methods:

import static org.easymock.EasyMock.*;

[...]

object1.toggleDisplay();
expectLastCall().times(5);
palacsint
  • 28,416
  • 10
  • 82
  • 109