繁体   English   中英

伪HttpContext.Current.Server.MapPath用于单元测试

[英]Fake HttpContext.Current.Server.MapPath for unit test

我的测试在此行上失败。 我发现这是因为我的GetProofOfPurchase方法中的HttpContext 这是我失败的那一行:

var image = Image.GetInstance(HttpContext.Current.Server.MapPath(GlobalConfig.HeaderLogo));

这是我的测试:

 [Test]
    public void GetProofOfPurchase_Should_Call_Get_On_ProofOfPurchaseRepository()
    {
        string customerNumber = "12345";
        string orderNumber = "12345";
        string publicItemNumber = "12345";

    var result = new ProofOfPurchase();
    this.proofOfPurchaseRepository.Expect(p => p.Get(new KeyValuePair<string,string>[0])).IgnoreArguments().Return(result);
    this.promotionTrackerService.GetProofOfPurchase(customerNumber, orderNumber, publicItemNumber);
    this.promotionTrackerRepository.VerifyAllExpectations();
}

测试在promotionTrackerService.GetProofOfPurchase行上失败。 在这种情况下如何伪造HttpContext 我已经在Stack Overflow上搜索了类似的问题,但是无法正常工作。

我尝试这样做:

var image = Image.GetInstance(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, GlobalConfig.HeaderLogo));

但是它没有说:

System.Net.WebException:找不到路径“ C:\\ Images \\ HeaderLogo.png”的一部分。

根据我对Stack Overflow的了解,如果我打算对其进行单元测试,则不应该使用HttpContext.Current ,这就是为什么我尝试使用Path.Combine ,但是我无法使其正常工作。

有人可以为我需要做一些指导以使此单元测试生效吗?

谢谢!

在编写涉及非纯函数的代码的测试时,我更愿意将它们隐藏在简单的情况下,即普通的旧Func<string, string>

class PromotionTrackerService
{
    private readonly Func<string, string> imageMapper;

    public PromotionTrackerService(Func<string, string> imageMapper)
    {
        this.imageMapper = imageMapper ?? HttpContext.Current.Server.MapPath;
    }

    public void GetProofOfPurchase()
    {
        var image = Image.GetInstance(imageMapper(GlobalConfig.HeaderLogo));
    }
}

现在,您的测试看起来不像是单元测试,它更像是一个集成测试,具有所有文件访问权限和所有功能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM