【问题标题】:How to write test cases for private void methods using junit and mockito [duplicate]如何使用junit和mockito为私有void方法编写测试用例[重复]
【发布时间】:2017-09-02 13:26:29
【问题描述】:

我们可以为 setAddr() 方法编写测试用例,因为它是私有的 void 方法,请帮助我吗?

class WCfg  {

private void setAddr(Cfg cfg, String... arg)
         throws Exception {
try {

} catch (Exception e) {
  throw new Exception("Invalid IP address.", e);
}
}

public String process(String... arg) throws Exception {
  MCfg mCfg = new MCfg();

  try {
    setAddr(mCfg, arg);

  } catch (Exception e) {
    return "Wrong argument format.";
  }
  cfg.write();

  return "success";
 }
}

【问题讨论】:

  • 你不应该为你的私有方法写测试。
  • 可以使用reflection访问方法,也可以使用PowerMock
  • 提示:下次试试你最喜欢的搜索引擎 ;-)

标签: java junit mockito


【解决方案1】:

每个私有方法总是直接或直接在某些公共或可访问方法中调用。 所以,无需为他们写案例。

如果您想为此编写测试用例,请使用:

Deencapsulation.invoke(SomeClassWherePrivateMethod.class, "methodName", argument1, argument2, argument3);

这里Deencapsulation 来自mockit.Deencapsulation

你可以Download jar from here

【讨论】:

    【解决方案2】:

    如果你真的需要,你可以使用反射。参见示例:http://onjavahell.blogspot.nl/2009/05/testing-private-methods-using.html

    还要阅读 cmets!我强烈建议不要这样做。如果您无法测试您的代码,这通常是糟糕设计的标志。

    【讨论】:

      【解决方案3】:

      如上所述,您不应该测试私有方法。始终测试您班级的合同而不是实施。否则,如果你的类的实现被改变,你会得到假阴性测试结果。我的意思是类的行为符合预期,但测试会失败。

      如果您在private 方法中有复杂的逻辑,您应该考虑将其提取到单独的类中。 这个类可以是package-private,也可以复用提取出来的代码。

      【讨论】:

        猜你喜欢
        • 2021-11-17
        • 2023-02-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多