单元测试的新手,正在寻找一种方法来对 boolean 方法进行单元测试,该方法由其他两种方法结果验证。
protected boolean isUpdateNeeded(){
return (method1() && method2());
}
对于这个例子,其他方法看起来像这样。
protected boolean method1() {
return false;
}
protected boolean method2() {
return true;
}
但是如果需要,这两个方法是/可以被覆盖。不知道现在这是否真的很重要
所以我的测试背后的想法是这样的。找到一种方法将 true/false 传递给 method1 或 method2 以满足所需的可能结果。
@Test
public void testCheckToSeeIfUpdateIsNeeded(){
assertTrue('how to check here');
asserFalse('how to check here');
assertIsNull('was null passed?');
}
最佳答案
如果另一个类扩展了它并覆盖了 method1 和 method2,则开发该类的人员有责任测试更改。
您可以模拟 method1 和 method2,但是您随后将类的结构与测试用例耦合,使得以后更难进行更改。
你的责任是测试你类(class)的行为。我看到有问题的方法称为 isUpdateNeeded
。所以让我们测试一下。我会按照我的想象填写类(class)。
class Updater {
Updater(String shouldUpdate, String reallyShouldUpdate) {...}
boolean method1() { return shouldUpdate.equals("yes"); }
boolean method2() { return reallyShouldUpdate.equals("yes!"); }
boolean isUpdateNeeded() { ...}
}
class UpdaterTest {
@Test
void testUpdateIsNeededIfShouldUpdateAndReallyShouldUpdate() {
String shouldUpdate = "yes";
String reallyShouldUpdate = "yes!"
assertTrue(new Updater(shouldUpdate, reallyShouldUpdate).isUpdateNeeded());
}
.... more test cases .....
}
请注意此测试如何断言给定输入的更新程序的行为,而不是它与某些其他方法的存在的关系。
如果您希望测试演示如果您重写这些方法会发生什么,请在测试中子类化 Updater 并进行适当的更改。
关于java - 基于其他方法返回类型的单元测试 boolean 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57999782/