如何使用junit和mockito编写私有void方法的测试用例

时间:2017-04-07 08:33:23

标签: java junit mockito

我们可以为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";
 }
}

3 个答案:

答案 0 :(得分:1)

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

然后如果你想为它编写测试用例,那么使用:

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

此处Deencapsulation来自mockit.Deencapsulation

你可以Download jar from here

答案 1 :(得分:0)

如果你真的必须使用反射。请参阅示例:http://onjavahell.blogspot.nl/2009/05/testing-private-methods-using.html

但也阅读了评论!我强烈建议不要这样做。如果您无法测试代码,那么通常是设计糟糕的迹象。

答案 2 :(得分:0)

如上所述,您不应该测试私有方法。总是测试你的合同而不是实施。否则,如果您的类的实现被更改,您将得到假阴性测试结果。我的意思是,类的行为与预期的一样,但测试将失败。

在这种情况下,如果你在private方法中有复杂的逻辑,你应该考虑将它提取到单独的类中。 此类可以是package-private,您也可以重复使用提取的代码。

相关问题