在测试方法中模拟一个类

时间:2015-03-06 09:31:55

标签: java unit-testing mocking mockito powermock

我遇到了一个我必须要模拟的课程的问题。

测试方法如下所示:

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

//这个上下文真的很重要,它只是为了运行方法而被嘲笑。

//这里是主要问题,我不知道如何使用这个模拟的ComponentsFetcher,而它在INSED中使用了testsMethod

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

但它根本不起作用......

1 个答案:

答案 0 :(得分:2)

你不能使用mockito来模拟静态方法。如果你想继续使用mockito,请尝试重新设计你的类,使方法不是静态的,然后模拟对象的实际实例。

为了单元测试,总是首选避免全局单例(由于你遇到的问题),而是依赖于dependency injection。这意味着您将在代码中的其他位置创建ComponentsFetcher并将其传递给您正在测试的类,可能是在构建时。这将允许您在准备单元测试时注入模拟的测试,并在生产时使用真实测试

相关问题