【问题标题】:Issues in writing test case for a private method为私有方法编写测试用例的问题
【发布时间】:2015-06-16 08:22:04
【问题描述】:

我正在尝试为下面的类中的 params 方法编写一个测试用例。

编写 JUnit 测试用例时的问题:

问题在于该方法是私有的,并且在它调用超类方法的方法内部。我尝试使用 EasyMock 来抑制对超类构造函数的调用

CustomListener customListenerMock=createMock(CustomListener.class);
    expect(customListenerMock.getParam("CHECK_INTEGRITY")).andReturn(null);
    expect(customListenerMock.getParam("WRITE_ANSWER")).andReturn(null);    

文档说我将能够在调用这些方法时抑制它们,并且可以给出指定的输出,即在这种情况下为 null。

现在我的问题是如何调用私有方法进行测试?我尝试使用反射 API,但它没有按预期工作。

代码:

 Method InitialiseSecurityConfiguration = Listener .class.getDeclaredMethod(methodToTest, null);
    InitialiseSecurityConfiguration.setAccessible(true);
    InitialiseSecurityConfiguration.invoke(fileListenerObj);

当我使用反射 API 调用时,这些方法就像那样被调用,并且超级类方法不会按需要被抑制。

注意:我使用的是旧版应用程序,并且不允许更改我的方法的可见性。

class Listener extends CustomListener{

 /*
      Some More methods
 */

private boolean params()
      {
        String integrity = "";
        String sWAnswer = "";
        try
        {
          try
          {
            integrity = super.getParam("CHECK_INTEGRITY");
            sWAnswer = super.getParam("WRITE_ANSWER");


            **Some Business Logic** 

          super.info("Request Directory  : " + sRequestPath);
          super.info("Response Directory : " + sResponsePath);
          super.info("Error Directory    : " + sErrorPath);
          }
        }
        catch (Exception ex)
        {
          bCheck = false;
        }
        return bCheck;

              }//closing the method params
}//Closing Listener class     

【问题讨论】:

    标签: junit mockito powermock easymock powermockito


    【解决方案1】:

    我会为调用您感兴趣的私有方法的公共方法编写测试。

    作为一般规则,针对类的公共 API 编写单元测试是一种很好的做法,这样就可以在不更改测试的情况下更改实现(即私有方法)。

    公共 API 是该类的使用方式,因此应该进行测试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-06
      • 1970-01-01
      • 2020-05-29
      • 2017-09-02
      • 2023-03-08
      • 1970-01-01
      相关资源
      最近更新 更多