我想創建存根的集合,以便在我調用getId()方法時返回0,第二個Item.getId()返回1等等。 getId()方法的值必須等於元素的索引。我嘗試這個用mockito創建存根的集合
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private List<Item> items;
@Before
public void setUp() throws Exception {
initMocks(this);
}
@Test
public void mockCollection() throws Exception {
when(items.get(0).getId()).thenReturn(0);
when(items.get(1).getId()).thenReturn(1);
...
}
但我得到這個異常:
java.lang.ClassCastException: org.mockito.internal.creation.jmock.ClassImposterizer$ClassWithSuperclassToWorkAroundCglibBug$$EnhancerByMockitoWithCGLIB$$42aa7d0b cannot be cast to com.gubin.designpatterns.behavioural.observer.Item
如何,我可以做這個任務?
很抱歉,爲什麼RETURNS_DEEP_STUBS在這種情況下無法工作?我認爲它必須模擬get(int)方法,然後模擬getId()方法,否則我無法正確理解RETURNS_DEEP_STUBS。 – user3610700
無論您發送哪個參數,RETURNS_DEEP_STUBS可以做的是返回相同的對象。因此,您需要一種方法來指定您希望根據參數返回不同的對象。 – alayor
感謝您的細化 – user3610700