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