2 回答

TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超6個(gè)贊
如果另一個(gè)類擴(kuò)展了該類并重寫了 method1 和 method2,則開發(fā)該類的人員有責(zé)任測試更改。
您可以模擬 method1 和 method2,但隨后會將類的結(jié)構(gòu)與測試用例耦合起來,從而使以后更難進(jìn)行更改。
你在這里有責(zé)任測試你班級的行為。我看到有問題的方法被稱為isUpdateNeeded. 那么讓我們測試一下。我將按照我的想象填寫課程。
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 .....
}
請注意此測試如何在給定輸入的情況下斷言更新程序的行為,而不是它與某些其他方法的存在的關(guān)系。
如果您希望測試演示重寫方法時(shí)會發(fā)生什么,請?jiān)跍y試中子類化 Updater 并進(jìn)行適當(dāng)?shù)母摹?/p>

TA貢獻(xiàn)2016條經(jīng)驗(yàn) 獲得超9個(gè)贊
所以,例如你有課:
public class BooleanBusiness {
public boolean mainMethod(){
return (firstBoolean() && secondBoolean());
}
public boolean firstBoolean(){
return true;
}
public boolean secondBoolean() {
return false;
}
}
然后你可以編寫這樣的測試:
import static org.junit.Assert.*;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.mockito.Mockito;
public class BooleanBusinessTest {
@Test
public void testFirstOption() {
BooleanBusiness booleanBusiness = Mockito.spy(BooleanBusiness.class);
when(booleanBusiness.firstBoolean()).thenReturn(true);
when(booleanBusiness.secondBoolean()).thenReturn(true);
assertTrue(booleanBusiness.mainMethod());
}
@Test
public void testSecondOption() {
BooleanBusiness booleanBusiness = Mockito.spy(BooleanBusiness.class);
when(booleanBusiness.firstBoolean()).thenReturn(true);
when(booleanBusiness.secondBoolean()).thenReturn(false);
assertFalse(booleanBusiness.mainMethod());
}
}
添加回答
舉報(bào)