0
我們正在創建一個Web API,我正在嘗試爲Web API設置集成測試,所以我們不必使用PostMan來驗證它是否工作。集成測試 - WebApi - 內存託管返回404錯誤
當我運行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);
}
}
我不得不添加的配置方法在啓動,否則當類被初始化測試將失敗。