Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an EasyMock mock to return an empty list multiple times

I would like an EasyMock mock to be able to expect an empty list multiple times, even when the list that is returned the first time has elements added to it.

Is this possible? As the empty list created in the expectation persists for the whole replay and so retains any elements added to it in between calls.

Here is a code example showing what I'm trying to avoid:

public class FakeTest {

private interface Blah {

    public List<String> getStuff();
};

@Test
public void theTest(){

    Blah blah = EasyMock.createMock(Blah.class);

    //Whenever you call getStuff() an empty list should be returned
    EasyMock.expect(blah.getStuff()).andReturn(new ArrayList<String>()).anyTimes();

    EasyMock.replay(blah);

    //should be an empty list
    List<String> returnedList = blah.getStuff();
    System.out.println(returnedList);

    //add something to the list
    returnedList.add("SomeString");
    System.out.println(returnedList);

    //reinitialise the list with what we hope is an empty list
    returnedList = blah.getStuff();

    //it still contains the added element
    System.out.println(returnedList);

    EasyMock.verify(blah);
}
}
like image 786
insano10 Avatar asked Feb 26 '23 04:02

insano10


1 Answers

You can use andStubReturn to generate a new list each time.

//Whenever you call getStuff() an empty list should be returned
EasyMock.expect(blah.getStuff()).andStubAnswer(new IAnswer<List<String>>() {
        @Override
        public List<Object> answer() throws Throwable {
            return new ArrayList<String>();
        }
    }
like image 189
mkrussel Avatar answered Apr 30 '23 03:04

mkrussel