Question

Suppose i have the following method :

public void runLoop(SomeIterator it){
    while(it.hasNext()){
        //do something
    }
}

Now i want to pass in a SomeIterator Mock object that would return Boolean.TRUE in order to go into the loop, but I also want it to return Boolean.FALSE at some point (say after 10 times for example), is there a way to make this happen with PowerMock/EasyMock?

Thanks in advance for your help.

Was it helpful?

Solution

Here's an excerpt from the EasyMock documentation:

Changing Behavior for the Same Method Call

It is also possible to specify a changing behavior for a method. The methods times, andReturn, and andThrow may be chained. As an example, we define voteForRemoval("Document") to

  • return 42 for the first three calls,
  • throw a RuntimeException for the next four calls,
  • return -42 once.
expect(mock.voteForRemoval("Document"))
    .andReturn((byte) 42).times(3)
    .andThrow(new RuntimeException(), 4)
    .andReturn((byte) -42);

OTHER TIPS

I don't know powermock that well, but with easymock the way to do that is .andAnswer() instead of .andReturn on your mock.

Pseudo code:

it.hasNext();
expectLastCall().anyTimes().andAnswer(
    new IAnswer<Boolean>(){ compute your return value }
);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top