2017-09-14 179 views
1
public async Task<HttpResponseMessage> UpdateUserProfile(HttpPostedFile postedFile) 
{ 
    //update operations 
} 

我有哪里我更新使用HttpPostedFile一个人的图像的方法UpdateUserProfile。它从Postman/Swagger工作正常。现在我正在写UnitTestCases。我有下面的代码模拟HttpPostedFile在单元测试

public void UpdateUserProfile_WithValidData() 
{ 
    HttpPostedFile httpPostedFile; 
    //httpPostedFile =?? 

    var returnObject = UpdateUserProfile(httpPostedFile); 

    //Assert code here 
} 

现在我已经从手工代码,我试图做的,但不能给映像文件HttpPostedFile对象。请建议我如何在单元测试中进一步进行模拟图像。

+0

这已经得到解决? – Nkosi

+0

都能跟得上@Nkosi我的应用程序专门使用HttpPostedFile,所以没有把它改成HttpPostedFileBase – thecrusader

回答

0

HttpPostedFile被密封并且具有内部构造。这很难嘲笑你的单元测试。

我建议改变你的代码中使用抽象HttpPostedFileBase

public async Task<HttpResponseMessage> UpdateUserProfile(HttpPostedFileBase postedFile) 
    //update operations 
} 

因为它是一个抽象类,这将允许你通过继承直接或通过嘲弄框架创建嘲弄。

例如(使用MOQ)

[TestMethod] 
public async Task UpdateUserProfile_WithValidData() { 
    //Arrange 
    HttpPostedFileBase httpPostedFile = Mock.Of<HttpPostedFileBase>(); 
    var mock = Mock.Get(httpPostedFile); 
    mock.Setup(_ => _.FileName).Returns("fakeFileName.extension"); 
    var memoryStream = new MemoryStream(); 
    //...populate fake stream 
    //setup mock to return stream 
    mock.Setup(_ => _.InputStream).Returns(memoryStream); 

    //...setup other desired behavior 

    //Act 
    var returnObject = await UpdateUserProfile(httpPostedFile); 

    //Assert 
    //...Assert code here 
}