小编Kev*_*ist的帖子

如何在.NET Core中模拟/存根HttpRequestMessage?

我有一个要从Azure Functions v1移植到v2的函数,并且作为其中一部分,我遇到了更新单元测试(创建存根的HttpRequestMessage)的问题。这是针对.NET Framework 4.7的在Function v1上运行的代码

public class FunctionExample
{
    [FunctionName(nameof(SomeFunction))]
    public static async Task<HttpResponseMessage> SomeFunction
    (
        [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "SomeFunction")]
        HttpRequestMessage request
    )
    {
        var body = await request.Content.ReadAsStringAsync();
        if (string.IsNullOrEmpty(body))
        {
            return request.CreateResponse(HttpStatusCode.BadRequest, "Bad job");
        }
        else
        {
            return request.CreateResponse(HttpStatusCode.OK, "Good job");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

还有我的测试代码

public class FunctionExampleTests
{
    [Test]
    public async Task TestSomeFunction()
    {
        var request = new HttpRequestMessage
        {
            Method = HttpMethod.Post,
            RequestUri = new Uri("http://localhost/"),
            Content = new StringContent("", Encoding.UTF8, "application/json")
        };

        request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, …
Run Code Online (Sandbox Code Playgroud)

c# azure .net-core azure-functions asp.net-core-webapi

3
推荐指数
1
解决办法
595
查看次数