【问题标题】:Adding junit for a static method call为静态方法调用添加junit
【发布时间】:2022-11-11 04:13:05
【问题描述】:

以下是我的类,其中 Display 类有一个静态方法 resultDisplay()。显示类来自 jar 文件。我想为 testCode() 方法编写 junit。我对 Display.resultdisplay() 调用不感兴趣。我只想验证junit中list的内容。

public class Summation {

    private static final List<Integer> list = new ArrayList<>();
    
    public int testCode(int... a) {
        for(int aa : a)
            list.add(aa);
        return Display.resultDisplay(list);
    }
}

【问题讨论】:

  • 所以......你想为那个不测试那个单元的单元编写一个单元测试?
  • 我在实际代码中有不同的逻辑,我不能在这里分享。我想在特定静态方法之前测试所有行。
  • 该列表有吸气剂吗?如果没有,祝你好运。你会花更多的时间试图解决这个问题,而不是值得。否则,如果 Display.resultDisplay (.. ) 不改变 List 的内容,它应该很简单。
  • 将您的静态方法包装在实例方法中并模拟该类。

标签: java mockito powermockito


【解决方案1】:

模拟静态访问和全局变量很棘手。幸运的是,每个问题都可以通过另一层间接来解决:

interface DisplayWrapper {
  int resultDisplay(List<Integer> list);
}
class DisplayWrapperImpl implements DisplayWrapper {
  @Override int resultDisplay(final List<Integer> list) {
    return Display.resultDisplay(list);
  }
}
public class Summation {
    private static final List<Integer> list = new ArrayList<>();

    private final DisplayWrapper display;
    
    public Summation(final DisplayWrapper display) {
      this.display = display;
    }

    public int testCode(int... a) {
        Collections.addAll(list, a);
        return display.resultDisplay(list);
    }
}

现在您的课程可以轻松测试。

生产代码:new Summation(new DisplayWrapperImpl())

测试代码:

final DisplayWrapper display = mock(DisplayWrapper.class);
final Summation summation = new Summation(display);
// ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-20
    • 2014-03-17
    • 2019-07-13
    相关资源
    最近更新 更多