public async Task<HttpResponseMessage> UpdateUserProfile(HttpPostedFile postedFile)
{
//update operations
}我有一个UpdateUserProfile方法,在这里我正在更新一个使用HttpPostedFile的人的图像。邮递员/斯威格公司的工作很好。现在,我也在为同样的问题编写UnitTestCases。我有下面的代码
public void UpdateUserProfile_WithValidData()
{
HttpPostedFile httpPostedFile;
//httpPostedFile =??
var returnObject = UpdateUserProfile( httpPostedFile );
//Assert code here
}现在,我必须手动将图像文件交给HttpPostedFile对象,这是我试图做的,但做不到。请建议我如何在单元测试中继续模拟映像。
发布于 2017-09-14 11:23:17
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
}https://stackoverflow.com/questions/46217164
复制相似问题