如何验证使用精确参数调用静态方法?

时间:2015-03-12 09:44:45

标签: java unit-testing mockito powermock

我有以下测试方法:

public static Map<String, CrxEntity> getCrxEntitiesByMixin(Session readSession, String rootPath, SupportedLocale locale, String mixin, String idPropertyName, Set<String> propertyNamesToStore) throws RepositoryException {
        return getCrxEntitiesByMixin(readSession, rootPath, locale, mixin, idPropertyName, propertyNamesToStore, null, false);
    }

以下方法调用另一个公共方法,因此我应该仅测试正确传递的参数。

我写了以下代码:

    @Test
    public void getCrxEntitiesByMixinTest() throws RepositoryException {
        PowerMockito.mockStatic(StaticUtils.class);

        when(StaticUtils.getCrxEntitiesByMixin(any(Session.class),anyString(),any(SupportedLocale.class),anyString(),anyString(),anySet(),anyList(),anyBoolean())).thenReturn(null);

        StaticUtils.getCrxEntitiesByMixin(sessionMock, "rootPath", SupportedLocale.EN, "mixin", "idPropName", Sets.<String>newHashSet());

        verify(StaticUtils.getCrxEntitiesByMixin(eq(sessionMock), eq("rootPath"), eq(SupportedLocale.EN), eq("mixin"), eq("idPropName"), eq(Sets.<String>newHashSet()), eq(Lists.<String>newArrayList()), eq(false)));
    }

我看到以下错误:

org.mockito.exceptions.misusing.NullInsteadOfMockException: 
Argument passed to verify() should be a mock but is null!
Examples of correct verifications:
    verify(mock).someMethod();
    verify(mock, times(10)).someMethod();
    verify(mock, atLeastOnce()).someMethod();
Also, if you use @Mock annotation don't miss initMocks()

如何解决我的问题?

1 个答案:

答案 0 :(得分:0)

我找到了答案。 Powermockito对此有非常混乱的语法:

PowerMockito.verifyStatic();
StaticUtils.getCrxEntitiesByMixin(eq(sessionMock), eq("rootPath"), eq(SupportedLocale.EN), eq("mixin"), eq("idPropName"), eq(Sets.<String>newHashSet()), eq((List<String>)null), eq(false));

完整示例: https://gist.github.com/ThoMo/3916072