Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为单元测试伪造HttpContext.Current.Server.MapPath_C#_Unit Testing_Httpcontext - Fatal编程技术网

C# 为单元测试伪造HttpContext.Current.Server.MapPath

C# 为单元测试伪造HttpContext.Current.Server.MapPath,c#,unit-testing,httpcontext,C#,Unit Testing,Httpcontext,我有一个测试在这条线上失败了。我发现这是由于我的getproofpurchase方法中的HttpContext造成的。以下是我失败的一句话: var image = Image.GetInstance(HttpContext.Current.Server.MapPath(GlobalConfig.HeaderLogo)); 这是我的测试: [Test] public void GetProofOfPurchase_Should_Call_Get_On_ProofOfPurchaseR

我有一个测试在这条线上失败了。我发现这是由于我的
getproofpurchase
方法中的
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();
}
但它没有说:

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

从我对堆栈溢出的了解来看,如果我计划对其进行单元测试,我不应该使用
HttpContext.Current
,这就是为什么我尝试使用
Path.Combine
,但我无法使其正常工作

有人能为我提供一些指导吗?我需要做什么才能让这个单元测试正常工作


谢谢大家!

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

class PromotionTrackerService
{
专用只读Func图像映射器;
公共促销跟踪服务(Func imageMapper)
{
this.imageMapper=imageMapper??HttpContext.Current.Server.MapPath;
}
公共采购证明文件()
{
var image=image.GetInstance(imageMapper(GlobalConfig.HeaderLogo));
}
}
现在,您的测试看起来不像是一个单元测试——它更像是一个集成测试,具有所有的文件访问和其他功能

var image = Image.GetInstance(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, GlobalConfig.HeaderLogo));
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));
    }
}