桩对象(一)

   外部依赖是指在系统中代码与其交互的对象,而且无法对其做人为控制。(如文件系统,线程,内存和时间等)

   桩对象是对系统中现有依赖项的一个替代品,可人为控制,通过使用桩对象,无需涉及依赖项,即可直接对代码进行测试。

   下面通过例子演示使用桩对象处理外部依赖问题。

1.抽取接口,以允许替换底层实现

    定义接口IExtensionManager

public interface IExtensionManager
{
    bool IsValid(string fileName);
}

   定义实现类FileExtensionManager 

public class FileExtensionManager : IExtensionManager
{
    public bool IsValid(string fileName)
    {
        if (string.IsNullOrEmpty(fileName))
            throw new ArgumentException("fileName is null");

        if (!fileName.ToLower().EndsWith(".log"))
        {
            return false;
        }
        return true;
    }
}

2.在被测类中注入桩对象

public class StubExtensionManager : IExtensionManager
{
    public bool ShouldExtensionBeValid;
    public bool IsValid(string fileName)
    {
        return ShouldExtensionBeValid;
    }
}

3.通过构造函数注入桩对象

public class LogAnalyzer
{
    private const int minFileNameLength = 6;
    private IExtensionManager manager;
    //生产环境中构造对象
    public LogAnalyzer()
    {
        manager = new FileExtensionManager();
    }
    //测试调用的构造函数
    public LogAnalyzer(IExtensionManager mgr)
    {
        manager = mgr;
    }
    //被测试方法
    //支持文件类型及文件名是否足够长
    public bool IsValidLogFileName(string fileName)
    {
        if (manager.IsValid(fileName) && Path.GetFileNameWithoutExtension(fileName).Length > minFileNameLength)
            return true;
        return false;
    }
}

4.测试代码

[TestFixture]
public class LogAnalyzerTests
{       
    [Test]
    public void IsValidLogFileName_NameShorterThan6charsButSupportedExtension_ReturnFalse()
    {
        //创建桩对象
        StubExtensionManager fakeManager = new StubExtensionManager();
        fakeManager.ShouldExtensionBeValid = true;

        //新建analyzer并注入桩对象
        LogAnalyzer analyzer = new LogAnalyzer(fakeManager);
        bool result = analyzer.IsValidLogFileName("s.log");
        Assert.IsFalse(result, "File name with less than 6 chars should have failed the method, even if the extension is supported.");
    }    
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值