一个模拟返回函数,包含模拟函数的Mokito崩溃?

时间:2016-10-03 03:57:17

标签: java android unit-testing mockito

在下面创建测试时

@Test
public void myTest() {
    MyRepo myRepo = Mockito.mock(MyRepo.class);
    when(myRepo.getMyItemList()).thenReturn(createMyItemList(3));
    // More Test verification
}

private List<MyItem> createMyItemList(int count) {

    List<MyItem> myItemList = new ArrayList<>();
    while (count > 0) {
        myItemList.add(createMyItem());
        count--;
    }
    return myItemList;
}

private MyItem createMyItem() {
    MyItemDetail myItemDetail = new MyItemDetail();
    ItemDetailGen itemDetailGen = Mockito.mock(ItemDetailGen.class);
    when(itemDetailGen.getItem()).thenReturn(myItemDetail);

    return new MyItem(itemDetailGen);
}

我在运行它时when(itemDetailGen...行出错了

org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:
-> at ...

E.g. thenReturn() may be missing.
Examples of correct stubbing:
    when(mock.isOk()).thenReturn(true);
    when(mock.isOk()).thenThrow(exception);
    doThrow(exception).when(mock).someVoidMethod();
Hints:
 1. missing thenReturn()
 2. you are trying to stub a final method, you naughty developer!

如果我调试它,则会在when(myRepo.getMyItemList...上发生崩溃。

为什么会出现这个问题?

似乎是一个模拟函数的返回(即createMyItemList),不应该包含另一个模拟。我的临时修复方法是删除私有函数mock,为MyItem创建一个新的构造函数,直接接受MyItemDetail对象,如下所示,这是不理想的,因为实际的代码并没有使用它。

private MyItem createMyItem() {
   MyItemDetail myItemDetail = new MyItemDetail();
   return new MyItem(myItemDetail);
}

已更新 为了更清楚,我展示了所有类(简化)内容。

class MyRepo {
    List<MyItem> myItemsList;
    List<MyItem> getMyItemList() {
        return myItemsList;
    }
    void addMyItemList(List<MyItem> myItemsList) {
        this.myItemsList = myItemsList;
    }
}

class MyItem {
    private MyItemDetail myItemDetail;
    public MyItem(ItemDetailGen itemDetailGen) {
        this.myItemDetail = itemDetailGen.getItem();
    }
    public MyItem(MyItemDetail myItemDetail) {
        this.myItemDetail = myItemDetail;
    }
}

class MyItemDetail {
}

class ItemDetailGen {
    MyItemDetail getItem() {
        return new MyItemDetail();
    }
}

结合类代码和测试代码,可以运行整个测试以清楚地演示问题。

0 个答案:

没有答案