我们正在创建一个web api,我正在尝试为web api设置集成测试,因此我们不必使用PostMan来验证它是否正常工作。
当我运行webapi并使用PostMan时,我得到了预期的结果。但是,当我尝试在内存托管中使用并运行webapi进行集成测试时,它总是返回404.
使用XUnit - 测试类如下。
public class UnitTest1
{
private readonly TestServer _server;
private readonly HttpClient _client;
public UnitTest1()
{
var host = new WebHostBuilder()
.UseStartup<Startup>();
this._server = new TestServer(host);
this._client = _server.CreateClient();
}
[Fact]
public async void TestMethod1()
{
var response = await this._client.GetAsync("api/objects");
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
List<obj> result = JsonConvert.DeserializeObject<IEnumerable<obj>>(responseString).ToList();
Assert.Equal(3, result.Count);
}
}
启动班:
public class Startup
{
public void Configuration(IAppBuilder app)
{
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
public void Configure()
{
var config = new HttpConfiguration();
WebApiConfig.Register(config);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
我必须在启动时添加configure方法,否则在初始化类时测试会失败。
答案 0 :(得分:0)
您可以尝试以下内容:
using (HttpConfiguration config = new HttpConfiguration())
{
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
WebApiConfig.Register(config); // If Needed
FilterConfig.RegisterGlobalFilters(GlobalConfiguration.Configuration.Filters); // If Needed
如果需要更多详细信息,可以在此处找到: https://stackoverflow.com/a/49202654/2928038