【问题标题】:Writing test case for switch statement inside private method在私有方法中为 switch 语句编写测试用例
【发布时间】:2014-09-26 17:55:28
【问题描述】:

我在私有方法中有一个 switch case 语句。 I don't think we need to do unit testing for the private method. 但我的代码覆盖率工具(EclEmma)显示“错过了 4 个分支中的 1 个”。在 switch 语句上带有黄色菱形。所以我的问题是:我如何为这种特殊情况编写测试?

代码片段

public void parentMethod() {
  ....
  childMethod(someList);
  ....
} 

private void childMethod(List<Integer> someList) {
  for(Integer var : someList) {
    switch(var){ ..... }
  }
}

【问题讨论】:

  • 公有方法的测试用例执行私有方法的所有代码路径。
  • 如何发送/设置作为 switch case 变量的 var?
  • var 根据某些逻辑设置在 childMethod() 中。

标签: java junit mockito eclemma


【解决方案1】:

所以,你可以尝试使用反射,像这样:

MyClass myClass = new MyClass();  
List<Integer> input = Arrays.asList(1, 2, 3);

Method method = MyClass.class.getDeclaredMethod("childMethod", List.class);
method.setAccessible(true);
method.invoke(myClass, input);
....

关于测试私有方法或一般不测试的方法的好链接:

http://saturnboy.com/2010/11/testing-private-methods-in-java/

http://www.artima.com/suiterunner/privateP.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    • 2017-09-02
    相关资源
    最近更新 更多