繁体   English   中英

在测试方法中模拟类

[英]Mocking a class inside the tested method

我必须模拟的课程有问题。

经过测试的方法如下所示:

testedMethod(Date from, Date to, Set set1, Set set2, SomeContext context) { method body };

现在在方法主体内部,使用了一个类。 用法如下所示:

List list = ComponentsFetcher.getComponent(String string1, context, from, to, String string2);

整个测试方法(略有简化)如下所示:

public static final long testedMethod(Date from, Date to, Set set1, Set set2, SomeContext context) {

    long returnedLong = 0;

    List list1 = ComponentsFetcher.getComponent(String string1, context, from, to, String string2);
    List list2 = ComponentsFetcher.getComponent(String string3, context, from, to, String string4);

    returnedLong = TestedMethodsClass.anotherMethod(from, to, set1, set2, list1, list2

    return returnedLong;

};

这个ComponentsFetcher.getComponent()方法正在做很多事情,但是我要做的只是获取此list ,我知道此列表的样子,我可以简单地创建它并稍后在经过测试的方法中使用它。

所以我想像这样模拟ComponentsFetcher.getComponent()

private void mockComponentsFetcher(Date from, Date to, ComponentsContext context, List list1, List list2) throws SomeBusinessException {
    Mockito.mock(ComponentsFetcher.class);
    Mockito.when(ComponentsFetcher.getComponent(string1, context, from, to, string2)).thenReturn(list1);
    Mockito.when(ComponentsFetcher.getComponent(string3, context, from, to, string4)).thenReturn(list2);
    }

最后,@ @Test方法:

@Test
    public void testTestedMethod() throws ParseException, SomeBusinessException {
        //given
        Date from = DateHelper.getDate(2011, 07, 03);
        Date to = DateHelper.getDate(2012, 07, 03);
        Set set1 = null; // can be null
        Set set2 = DateHelper.getDate(2011, 07, 03);
                Date day = DateHelper.getDate(2011, 07, 03);

        List list1 = getList(new Date[]{
                                // contents of the list
               });
        List list2 = getList(new Date[]{
                                // contents of the list
               });

        //mock
        ComponentsContext context = mockContext(day);

//此上下文确实无关紧要,只是为了使方法运行而对其进行了模拟。

//这是主要问题,我不知道如何在使用testedMethod的同时使用此模拟的ComponentsFetcher

        mockComponentsFetcher(from, to, context, list1, list2);
        //when
        long months = TestedMethodsClass.testedMethod(from, to, set1, set2, context);
        //then
        long awaited = 12;
        assertThat(months).isEqualTo(awaited);
    }

但这根本没有用...

您不能使用Mockito模拟静态方法。 如果您想保留模拟,请尝试重新设计类,以使方法不是静态的,然后模拟对象的实际实例。

为了进行单元测试,总是最好避免全局单例(由于确切的问题),而要依赖依赖注入 这意味着您可能会在构造时在代码中的其他位置创建ComponentsFetcher并将其传递给要测试的类。 这将允许您在准备单元测试时注入模拟对象,而在生产中使用真实的对象

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM