2017-06-02 42 views
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); 
    } 
} 

我不得不添加的配置方法在啓動,否則當類被初始化測試將失敗。

回答

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