利用Stub來打破關連性 (4)
Source: The art of unit testing with examples in .NET, Roy Osherove
http://www.amazon.com/Art-Unit-Testing-Examples-Net/dp/1933988274/ref=sr_1_1?ie=UTF8&s=books&qid=1267086529&sr=1-1
Chapter 3 Using stubs to break dependencies
最後一種方式, 作者是用factory method來處理.
老實說, 第一次看的時候, 覺得有點複雜. 不知道大家覺得如何.
// 受測程式
public class LogAnalyzer {
public bool IsValidLogFileName(string fileName) {
// 呼叫factory method 來產生所要的file extension manager
return GetManager().IsValid(fileName);
}
// 新增一個virtual function,
// 讓繼承的測試程式可以修改成他們想要作的事情
protected virtual IExtensionManager GetManager() {
return new FileExtensionManager();
}
}
// 繼承LogAnalyzer, 然後設定成測試要用ExtensionManager
// 所以它是一種可測試的LogAnalyzer
class TestableLogAnalyzer : LogAnalyzer {
public IExtensionManager Manager;
// override 受測程式(LogAnalyzer)的virtual function
// 在這裡, 測試程式會要傳回測試用的Extension Manager
protected override IExtensionManager GetManager() {
return Manager;
}
}
[TestFixture]
public class LogAnnalyzerTests {
[Test]
public void IsValidFileName_NameShorterThan6() {
// 設定stub的內容
StubExtensionManager myFakeManager =
new StubExtensionManager();
myFakeManager.ShouldExtensionBeValid = true;
// 建立一個可測試的LogAnalyzer ==> TestableLogAnalyzer
TestableLogAnalyzer testlog = new LogAnalyzer();
// 將Extension Manager的stub,設定進去
testlog.Manager = stub;
// 進行測試
bool result = log.IsValidLogFileName( "short.ext" );
// 檢查測試結果
Assert.IsFalse( result, "File name with less than 5 chars should have failed the method." );
}
}
class StubExtensionManager : IExtensionManager {
public bool ShouldExtensionBeValid;
public bool IsValid(string fileName) {
//實作僅供測試使用的功能
return ShouldExtensionBeValid;
}
}