verifyPrivate在Android单元测试中不起作用

时间:2019-06-16 11:21:40

标签: android mockito junit4 powermock powermockito

我一直在努力验证我的Android代码中私有方法的调用次数。下面列出了我正在使用的单元测试。我正在测试的私有方法的签名是

private void updateUI(boolean ok)

问题在于,无论“ verifyPrivate”中的“次数”是多少,测试始终会通过。看来我称之为“ MemberModifier.suppress”的行无法正常工作,因此PoweMockito无法跟踪类/方法。任何建议都将受到高度赞赏。

    @Test
    public void test_authenticated() throws Exception {
        when(mockedContext.getApplicationContext()).thenReturn(mockedApplicationContext);

        mockStatic(PreferenceManager.class);
        PowerMockito.when(PreferenceManager.getDefaultSharedPreferences(any(Context.class))).thenReturn(mockedSharedPreferences);
        PowerMockito.when(mockedSharedPreferences.getString("id", null)).thenReturn("id");
        PowerMockito.when(mockedSharedPreferences.getString("pass", null)).thenReturn("pass");

        zinkConnection = new ZinkConnection(mockedContext);
        spyZinkConnection = PowerMockito.spy(zinkConnection);

        MemberModifier.suppress(MemberMatcher.method(ZinkConnection.class, "updateUI")); // <--- Here I prepare the private method

        Connection mockedConnection = mock(Connection.class);

        spyZinkConnection.authenticated(mockedConnection, true);
        assertEquals(ZinkConnection.ConnectionState.CONNECTED, ZinkConnectionService.getState());

        spyZinkConnection.authenticated(mockedConnection, false);
        assertEquals(ZinkConnection.ConnectionState.CONNECTED, ZinkConnectionService.getState());

        verify(spyZinkConnection, times(1)).authenticated(mockedConnection, true);
        verify(spyZinkConnection, times(1)).authenticated(mockedConnection, false);
        PowerMockito.verifyPrivate(spyZinkConnection, times(1)).invoke("updateUI", true); // <--- Here I would like to verify number of calls
    }

0 个答案:

没有答案