PowerMock私有方法依赖私有方法

时间:2017-05-12 15:18:23

标签: java unit-testing mockito powermockito

我想使用Powermock来测试私有方法(一个),但这个私有方法依赖于另一个私有方法(两个)。

所以我必须嘲笑另一个私有方法。但是当我调试它时,事实证明私有方法没有调用模拟的私有方法(两个),如果我运行而不是调试它会抛出异常:

  

1匹配者预计,2记录。

private int getCurrentLocaleID(WebIServerSession currentSession, String preferenceName) {
    String prefLocaleID = getUserPreference(currentSession, preferenceName);
    int lcid;

    if (HTTPHelper.isDefaultLocale(prefLocaleID)) {
        prefLocaleID = _appContext.getBrowserHeaderLocaleId();
    }
    try {
        lcid = Integer.parseInt(prefLocaleID);
    } catch (NumberFormatException nfe) {
        lcid = DEFAULT_LCID; // default behavior from old session manager
    }
    return lcid;
}

@Test
public void getCurrentLocaleID() throws Exception {
    PowerMockito.mockStatic(HTTPHelper.class);
    WebAppSessionManagerImpl webAppSessionMangerImpl2 = PowerMockito.spy(new WebAppSessionManagerImpl(appConext));
    given(HTTPHelper.isDefaultLocale("1")).willReturn(true);
    given(HTTPHelper.isDefaultLocale("0")).willReturn(false);
    given(appConext.getBrowserHeaderLocaleId()).willReturn("1");
    PowerMockito.doReturn("1").when(webAppSessionMangerImpl2, "getUserPreference", anyObject(), anyString());
    int result = Whitebox.invokeMethod(webAppSessionMangerImpl2, "getCurrentLocaleID", webIserverSession, "test");
    assertEquals(result, 1);
}

1 个答案:

答案 0 :(得分:1)

不要测试私有方法。如果必须的话,这意味着你的课程做得太多,而且不符合单一责任原则。

这是一个在专业类中重构和隔离逻辑的机会,如下所示:

new B()

现在讨论方法public和A a1 = new A(); a1 -> address_1 a1 = new B(); a1 -> address_2 address_1 is freed from memory if it isn't being pointed to/"used" anywhere else 标记为包级别,测试看起来像:

public class SpecializedClass{

    private Context context;

    public SpecializedClass(Context context){
         this.context = context;
    }

        public int getCurrentLocaleID(WebIServerSession currentSession, String preferenceName) {
        String prefLocaleID = getUserPreference(currentSession, preferenceName);
        int lcid;

        if (HTTPHelper.isDefaultLocale(prefLocaleID)) {
            prefLocaleID = _appContext.getBrowserHeaderLocaleId();
        }

        try {
            lcid = Integer.parseInt(prefLocaleID);
        } catch (NumberFormatException nfe) {
            lcid = DEFAULT_LCID; // default behavior from old session manager
        }
        return lcid;
    }

    String getUserPreference(Session session, String preferenceName){..}
}