假设我的类有 3 个方法:
public void parent() throws Exception {}
public String child_1(String arg_1) throws IOException {}
public boolean child_2(String arg_1, String arg_2) throws SQLException {}
parent()
调用 child_1()
和 child_2()
,例如:
public void parent() throws Exception {
// Do some complicated stuff
child_1("str1");
// More stuff
child_2("str1", "str2");
// More stuff
}
现在,如果我已经测试了 child_1() 和 child_2() 并且我只想测试 parent(),是否可以覆盖 child_1() 和 child_2() 并仅测试 parent()? 像这样:
MyClass myClass = new MyClass() {
@Override
public String child_1(String arg_1) throws IOException {
return "expected_string_to continue_execution";
}
@Override
public boolean child_2(String arg_1, String arg_2) throws SQLException {
return true; // return expected boolean result to continueexecution;
}
};
myClass.parent();
通过这样做,我可以很容易地测试我的 parent() 并且因为 child_1() 和 child_2() 已经在这个类的其他单元测试中测试过,它不会做任何作弊(至少我是这么想的,请更正如果我错了我)。此外,在现实世界中,如果 chaild_1() 和 child_2() 正在做一些复杂的事情,这种方法使测试变得容易,我们不会冗余地检查耗时的代码。
我的问题是,这是否是一种正确的方法?如果不是,缺点是什么?最重要的是,正确的方法是什么?如果有人可以用上面的相同示例进行解释,那就太棒了。
非常感谢。
最佳答案
我会说重写方法是您通常应该避免的事情,因为它很可能违反了 Liskov substitution principle .测试代码没有什么特别之处:它应该遵循与生产代码相同的严格原则。我能想到的唯一异常(exception)是,如果您正在测试组件之间高度耦合的遗留代码,那么覆盖是唯一的选择。但是在编写新代码时,我看不出有任何理由。
我认为@samlewis 说到点子上了:如果您出于某种原因想要单独测试 parent()
,那么 child_1()
和 child_2()
可能应该在注入(inject)到 parent()
中的自己的类中。避免测试任何小于类的东西。如果您需要测试更小的东西,您可能有责任被提取出来 ( Single responsibility principle )。
child_1()
和 child_2()
实际上属于其他类的提示是它们是公共(public)的,公共(public)方法 parent()
调用它。公共(public)方法通常应该只调用非公共(public)方法(尽管可能有异常(exception))。
或者您是否将子方法公开以便您可以测试它们?如果是这样,请查看 this answer .
关于java - 覆盖您不想测试的类中的方法是否是一种好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17822613/