在此我们又一次看到了针对接口编程的重要性了,因为被测试的代码只会通过接口来引用对象,所以它完全可以不知道它引用的究竟是真实的对象还是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;
}
}
文章来源于领测软件测试网 https://www.ltesting.net/