Asp.net Web Api进行Nunit测试

有两种方式

1、模拟Web请求。

2、直接本地调用Api接口

但是由于本地直接调用没有模拟请求环境,所以request为null

public static HttpResponseMessage CreateResponse<T>(this HttpRequestMessage request, HttpStatusCode statusCode, T value);

在声明Controller的时候要初始化Request。

UserController uc = new UserController() { Request = new HttpRequestMessage() { Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } } } };

然后获取响应内容

HttpResponseMessage ht = uc.Get("Leestar");
Task<string> read = ht.Content.ReadAsStringAsync();
read.Wait();
Console.Out.WriteLine(read.Result);

PS.最好在测试项目里添加一份configuration的副本app.config,因为测试时候读的是测试项目的config

参考http://weblogs.asp.net/shijuvarghese/archive/2013/07/30/writing-unit-tests-for-asp-net-web-api-controller.aspx

原文地址:https://www.cnblogs.com/leestar54/p/3333701.html