为每一个要注入的依赖增加get和set属性,然后,被测代码中需要它时,就使用这个依赖。
通过set/get实现依赖注入,与上文(通过构造函数实现依赖注入)很相似,但是代码可读性更强。
public class LogAnalyzer
{
private const int minFileNameLength = 6;
private IExtensionManager manager;
public LogAnalyzer()
{
manager = new FileExtensionManager();
}
public IExtensionManager ExtensionManager
{
get { return manager; }
set { manager = value; }
}
//支持文件类型及文件名是否足够长
public bool IsValidLogFileName(string fileName)
{
if (manager.IsValid(fileName) && Path.GetFileNameWithoutExtension(fileName).Length > minFileNameLength)
return true;
return false;
}
}
测试代码
[TestFixture]
public class LogAnalyzerTests
{
[Test]
public void IsValidLogFileName_NameShorterThan6charsButSupportedExtension_ReturnFalse()
{
//创建桩对象
StubExtensionManager fakeManager = new StubExtensionManager();
fakeManager.ShouldExtensionBeValid = true;
//新建analyzer并注入桩对象
LogAnalyzer analyzer = new LogAnalyzer();
analyzer.ExtensionManager = fakeManager;
bool result = analyzer.IsValidLogFileName("s.log");
Assert.IsFalse(result, "File name with less than 5 chars should have failed the method, even if the extension is supported.");
}
}