在此我們又一次看到了針對接口編程的重要性了,因為被測試的代碼只會通過接口來引用對象,所以它完全可以不知道它引用的究竟是真實的對象還是mock對象,下面看一個實際的例子:一個鬧鐘根據時間來進行提醒服務,如果過了下午5點鐘就播放音頻文件提醒大家下班了,如果我們要利用真實的對象來測試的話就只能苦苦等到下午五點,然后把耳朵放在音箱旁...我們可不想這么笨,我們應該利用mock對象來進行測試,這樣我們就可以模擬控制時間了,而不用苦苦等待時鐘轉到下午5點鐘了。下面是代碼:
public interface Environmental {
private boolean playedWav = false;
public long getTime();
public void playWavFile(String fileName);
public boolean wavWasPlayed();
public void resetWav();
}
真實的實現代碼:
public class SystemEnvironment implements Environmental {
public long getTime() {
return System.currentTimeMillis();
}
public void playWavFile(String fileName) {
playedWav = true;
}
public boolean wavWasPlayed() {
return playedWav;
}
public void resetWav() {
playedWav = false;
}
}
下面是mock對象:
public class MockSystemEnvironment implements Environmental {
private long currentTime;
public long getTime() {
return currentTime;
}
public void setTime(long currentTime) {
this.currentTime = currentTime;
}
public void playWavFile(String fileName) {
playedWav = true;
}
public boolean wavWasPlayed() {
return playedWav;
}
public void resetWav() {
playedWav = false;
}
}
文章來源于領測軟件測試網 http://www.kjueaiud.com/