如何在公共方法依赖私有方法时进行测试

huangapple go评论75阅读模式
英文:

How to testing public methods when they have private methods dependency

问题

如何在公有方法依赖私有方法时对其进行测试

示例:

类 Person {
    private String name;

    public void getFancyname(String name){
        generateName();
    }

    private generateName(){ ... }
}
英文:

How to test public methods when they have private methods dependency

Example:

Class Person {
    private String name;

    public void getFancyname(String name){
        generateName();
    }

    private generateName(){ ... }

答案1

得分: 1

私有方法是公共方法的实现细节。

它们不应该被模拟/桩测试等(只有在某些复杂的遗留代码的情况下除外)。

如果您的公共方法使用了许多私有方法,您可能需要考虑将私有方法中包含的一些逻辑提取到单独的类中,并在隔离环境中测试该逻辑。这称为“新芽方法”(Sprout Method)。这将降低公共方法本身的复杂性,并使其更易于测试。

英文:

Private methods are an implementation detail of a public method.

They should never be mocked/stubbed etc. (only with the exception of some complex legacy code).

If your public method is using a lot of them you might think about extracting some of the logic contained in the private methods into a separate class and test that logic in isolation. This is called the Sprout Method. You would reduce the complexity of the public method itself and allow it to be more easily tested

huangapple
  • 本文由 发表于 2020年3月16日 19:05:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/60704791.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定