-1

This is my first attempt at using EasyMock. So, I've been trying to mock a void method:

protected void onStop() {
    logger.info("Stopping ReporterService.");

    if (reporter != null) {
        reporter.stop();
        reporter = null;
    }
}

I followed a few tutorials online and I wrote this:

ReporterService reporterService1 = EasyMock.createMock(ReporterService.class);

reporterService1.onStop();
EasyMock.expectLastCall().once();
replay(reporterService1);

//EasyMock.replay(reporterService1);
assertNull(Whitebox.getInternalState(reporterService1, "reporter"));
EasyMock.verify(reporterService1);

But then I got this:

java.lang.AssertionError:
Expectation failure on verify:
ReporterService.onStop(): expected: 1, actual: 0

I searched online but I have no idea why it says that. Appreciate the help.

Also, just to for the sake of understanding, I tested this manually and it works, I just want to test it using Easymock:

ReporterService reporterService = new ReporterService();
Reporter reporter = new Reporter(null,null,null);

Whitebox.setInternalState(reporterService , "reporter", reporter);
assertNotNull(Whitebox.getInternalState(reporterService, "reporter"));

reporterService.onStop();
assertNull(Whitebox.getInternalState(reporterService, "reporter"));
Alex Bloomberg
  • 855
  • 1
  • 7
  • 14
  • 1
    It's unclear what you're actually trying to test. Are you testing that the reporter gets stopped? If so, you should be mocking the reporter instead. – chrylis -cautiouslyoptimistic- Nov 08 '16 at 19:02
  • 1
    On a first glance, your test code looks good. Thus the next thing to look into ... is the thing missing in your question: the code under test. Even when you are sure that Whitebox.getInternalState() ... should call onStop on its argument ... you better post that code here ( see http://stackoverflow.com/help/mcve ) . Without that we cant help! – GhostCat Nov 08 '16 at 20:08

1 Answers1

-1

I think this should fix your issue. 1.You should first set the reporter object using setInternelState 2.your method is expecting a call on reporter.stop() so your Test should expect that method.

Look at the below code. You can add your assertions at the End.

ReporterService reporterService1 = EasyMock.createMock(ReporterService.class);
Reporter reporter = EasyMock.createMock(Reporter.class);

Whitebox.setInternalState(reporterService , "reporter", reporter);
reporter.onStop();
PowerMock.expectLastCall();

EasyMock.replay(reporterService1,reporter);

reporterService1.onStop();

EasyMock.verify(reporterService1,reporter);
  • 1
    You do not need PowerMock to mock void methods. Also, you don't need `expectLastCall()` which do exist in EasyMock but is not mandatory. I also urge you to use static imports. You will get `reporter.onStop(); replay(reporterService1, reporter);` – Henri Nov 09 '16 at 08:52