【问题标题】:Fake HttpContext.Current.Server.MapPath for unit test用于单元测试的假 HttpContext.Current.Server.MapPath
【发布时间】:2015-09-28 16:22:08
【问题描述】:

我有一个测试在这条线上失败了。我发现这是因为我的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 的原因,但我无法让它工作正确。

有人可以就我需要做些什么来让这个单元测试工作提供一些指导吗?

谢谢!

【问题讨论】:

    标签: c# unit-testing httpcontext


    【解决方案1】:

    在为涉及non-pure 函数的代码编写测试时,我更喜欢做的是将它们隐藏在最简单的情况下,即普通的旧Func&lt;string, string&gt;

    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));
        }
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-30
      • 2016-08-14
      • 2016-12-12
      • 1970-01-01
      • 2019-11-26
      • 2016-02-20
      • 1970-01-01
      • 2012-12-11
      相关资源
      最近更新 更多