gpt4 book ai didi

c# - 为 Web API 单元测试指定 HttpRequestMessage 的内容

转载 作者:行者123 更新时间:2023-11-30 16:39:55 26 4
gpt4 key购买 nike

我有一个 Web API Controller 方法,我想对其进行单元测试。它接受一个 HttpRequestMessage 但我不知道如何设置我想传入的内容。是否可以创建/模拟 HttpRequestMessage 以便我可以给它一个 string,我希望它成为 await request.Content.ReadAsStringAsync() 的结果吗?

这是我的 Controller 方法:

[HttpPost]
public async Task<HttpResponseMessage> Post(HttpRequestMessage request)
{
var data = await request.Content.ReadAsStringAsync();
//do something with data
}

我可以使用其无参数构造函数轻松创建 HttpRequestMessage,但我不知道如何将内容设置为有意义的值。我希望我的测试按照这些思路进行:

[TestMethod]
public async Task PostMethodWorks()
{
var controller = new MyController();

var data = "this will be JSON";
var httpRequestMessage = new HttpRequestMessage();
//set the content somehow so that httpRequestMessage.Content.ReadAsStringAsync returns data

var response = await controller.Post(httpRequestMessage);

//assert something about the response here
}

是否可以将内容的值设置为某个 JSON,或者我是否需要更改方法以便它接受不同的参数?

(对于更多的上下文,我想让方法接受 HttpRequestMessage 的原因是因为我正在处理一个遗留代码库,它有大量的 Controller 方法接受 HttpRequestMessage.)

最佳答案

Is it possible to set the value of the content to some JSON

您可以使用许多 HttpContent 中的任何一个 |派生类。因为在这种情况下你想发送 JSON 内容,你会想使用 StringContent class

例如

[TestMethod]
public async Task PostMethodWorks() {
//Arrange
var controller = new MyController();

var data = "this will be JSON";
var httpRequestMessage = new HttpRequestMessage();

//set the content somehow so that httpRequestMessage.Content.ReadAsStringAsync returns data
httpRequestMessage.Content = new StringContent(data, Encoding.UTF8, "application/json");


//Act
var response = await controller.Post(httpRequestMessage);

//Assert
//assert something about the response here
}

然而,这感觉像是一个 XY problem理想情况下,Web API 操作不要将 HttpRequestMessage 作为参数。

or will I need to change the method so it takes in a different parameter?

存在可用于具有强类型操作参数的模型绑定(bind)器,这些参数将解析传入数据并在传递给操作之前填充模型。

关于c# - 为 Web API 单元测试指定 HttpRequestMessage 的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52318250/

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