【问题标题】:Mock list size not incresae after adding mock object添加模拟对象后模拟列表大小不会增加
【发布时间】:2015-10-25 15:10:27
【问题描述】:

我正在开发测试用例。在这里,我使用模拟列表并在其中添加模拟对象。但是assetEquals 总是失败并出现错误:

java.lang.AssertionError: 
Expected :0
Actual   :2

这是我开发的测试用例:

@Test
    public void Test() {
        MyClass ModelMock = mock(MyClass.class);
        final List<HashMap<String, Object>> listModelMock = mock(List.class);
        final Page currentPage = getMockedCurrentPage();
        final Page childPage1 = mock(Page.class);
        final Page childPage2 = mock(Page.class);
        Iterator<Page> mockIterator = mock(Iterator.class);
        HashMap<String, Object> object1HashMap = new HashMap<>();
        HashMap<String, Object> object2HashMap = new HashMap<>();
        when(currentPage.listChildren()).thenReturn(mockIterator);
        when(mockIterator.hasNext()).thenReturn(true);
        when(mockIterator.next()).thenReturn(childPage1);
        when(mockIterator.next()).thenReturn(childPage2);

        when(childPage1.getPath()).thenReturn("Test");
        when(childPage1.getTitle()).thenReturn("Title of Page1");
        object1HashMap.put("title", childPage1.getTitle());
        object1HashMap.put("src", childPage1.getPath());
        //Fail
        assertEquals(object1HashMap.get(0), "Title of Page1");

        when(childPage2.getPath()).thenReturn("Test");
        when(childPage2.getTitle()).thenReturn("Title of Page2");
        object2HashMap.put("title", childPage2.getTitle());
        object2HashMap.put("src", childPage2.getPath());

        listModelMock.add(object1HashMap);
        listModelMock.add(object2HashMap);
      // Fail   
        assertEquals(listModelMock.get(0).size(), 2);
    }

【问题讨论】:

  • 不确定,即使 object1HashMap.get(0) 为空,实际是 Page1 的标题

标签: java unit-testing junit mocking


【解决方案1】:

您的 listModelMock 是列表的 mock。你没有告诉你的模拟框架(从我所看到的推测为 Mockito)在add 上做什么。所以add 什么都不做。

根据我对您的代码的理解,我认为您并不想真正模拟该列表。我认为真正的ArrayList 可以在这里解决问题。

坦率地说,您要测试的课程是什么?您的代码中的每个对象似乎都是一个模拟对象。以这种方式测试模拟框架是没有意义的......

Nitpick:对于断言,期望值是第一位的。所以assertEquals(2, listModelMock.get(0).size(),2);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-29
    • 1970-01-01
    • 2019-10-15
    • 2019-10-11
    • 1970-01-01
    • 2017-04-20
    • 2017-12-14
    • 2018-11-12
    相关资源
    最近更新 更多