在单元测试中模拟HttpPostedFile

时间:2017-09-14 10:52:36

标签: c# unit-testing asp.net-web-api2 mstest

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

我有一个方法UpdateUserProfile,我正在使用HttpPostedFile更新一个人的图像。 Postman / Swagger的工作正常。现在我正在编写UnitTestCases。我有以下代码

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

  var returnObject =  UpdateUserProfile( httpPostedFile );

  //Assert code here
}

现在我必须手动将代码文件中的图像文件提供给HttpPostedFile对象,但我不想这样做。请建议我如何在单元测试中进一步模拟图像。

1 个答案:

答案 0 :(得分:1)

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
}