2011-02-04 79 views
4

我希望EasyMock模擬能夠多次指望一個空列表,即使第一次返回的列表中添加了元素也是如此。如何讓EasyMock模擬多次返回一個空列表

這可能嗎?由於期望中創建的空列表在整個重播過程中一直存在,因此在調用之間保留添加到它的所有元素。

這裏是展示什麼,我試圖避免的代碼示例:

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); 
} 
} 

回答

8

您可以使用andStubReturn生成一個新的列表中的每個時間。

​​
+0

謝謝你的解決! – insano10 2011-02-07 09:39:50

相關問題