利用Stub來打破關連性 (2)
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
之前用constructor的方法來傳入stub object, 這樣的作法有什麼問題嗎?
有經驗的人一定會想到, 若是有多個stub object, 或是可能之後要動態增加stub時, 這樣的作法不就要常常改constructor, 因此作者提出另外一個作法: 利用property來設定stub.
方法 2.
public class LogAnalyzer {
private IExtensionManager manager;
// 設定指向真的File Extension Manager
public LogAnalyzer() {
manager = new FileExtensionManager();
}
// 隨時可以更改 Extension Manager 的內容
public IExtensionManager ExtendsionManager {
get { return manager; }
set { manager = value;}
}
public bool IsValidLogFileName(string fileName) {
return manager.IsValid(fileName);
}
}
[TestFixture]
public class LogAnnalyzerTests {
[Test]
public void IsValidFileName_NameShorterThan6() {
// 設定stub的內容
StubExtensionManager myFakeManager =
new StubExtensionManager();
myFakeManager.ShouldExtensionBeValid = true;
LogAnalyzer log = new LogAnalyzer();
// 將stub object傳給受測的object
log.ExtensionManager = myFakeManager;
// 進行測試
bool result = log.IsValidLogFileName( "short.ext" );
// 檢查測試結果
Assert.IsFalse( result, "File name with less than 5 chars should have failed the method." );
}
// File Extension Manager的stub
internal class StubExtensionManager : IExtensionManager {
public bool ShouldExtensionBeValid;
public bool IsValid(string fileName) {
//實作僅供測試使用的功能
return ShouldExtensionBeValid;
}
}
}
留言列表