标题翻译
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
专注分享java语言的经验与见解,让所有开发者获益!
评论