gpt4 book ai didi

c# - 在单元测试中模拟 HttpPostedFile

转载 作者:行者123 更新时间:2023-12-04 14:25:27 25 4
gpt4 key购买 nike

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 对象,我正在尝试这样做但做不到。请建议我如何在单元测试中进一步模拟图像。

最佳答案

HttpPostedFile 是密封的并且有一个内部构造函数。这使得模拟您的单元测试变得困难。

我建议更改您的代码以使用抽象 HttpPostedFileBase

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

因为它是一个抽象类,所以您可以通过继承或模拟框架直接创建模拟。

例如(使用最小起订量)

[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
}

关于c# - 在单元测试中模拟 HttpPostedFile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46217164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com