2016-11-16 42 views
0

我有web api控制器,我想執行集成測試。所以我按照文章here配置了內存中的Web API主機。 我的集成測試和web api是同一VS解決方案中的兩個不同項目。如何在內存中託管網頁API?

下面是代碼

的Web API控制器

public class DocumentController : ApiController 
{ 

    public DocumentController(IDomainService domainService) 
    { 
     _domainService = domainService;    
    }   

    [HttpPost] 
    public async Task<IEnumerable<string>> Update([FromBody]IEnumerable<Document> request) 
    { 
     return await _domainService.Update(request).ConfigureAwait(false); 
    } 
} 

集成測試

[TestClass] 
    public class IntegrationTests 
    { 
     private HttpServer _server; 
     private string _url = "http://www.strathweb.com/"; 

     [TestInitialize] 
     public void Init() 
     { 
      var config = new HttpConfiguration(); 
      config.Routes.MapHttpRoute(name: "Default", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional }); 
      config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always; 
      config.MessageHandlers.Add() 
      _server = new HttpServer(config); 
     } 


     [TestMethod] 
     public void UpdateTransformedDocuments() 
     { 
      var doc = new Document() 
      { 
       // set all properties 
      } 
      var client = new HttpClient(_server); 
      var request = createRequest<Document>("api/document/Update", "application/json", HttpMethod.Post, doc, new JsonMediaTypeFormatter()); 

      using (var response = client.SendAsync(request).Result) 
      { 
       // do something with response here 
      } 
     }   

     private HttpRequestMessage createRequest<T>(string url, string mthv, HttpMethod method, T content, MediaTypeFormatter formatter) where T : class 
     { 
      Create HttpRequestMessage here 
     } 
    } 

然而即時得到錯誤

的StatusCode:404,ReasonPhrase: '未找到'

如何&我在哪裏可以告訴HttpServer的執行DocumentController?

UPDATE1 所以我固定上述錯誤改變[TestIntialize]代碼爲打擊

[TestInitialize] 
    public void Init() 
    { 
     var config = new HttpConfiguration(); 
     UnityWebApiActivator.Start(); 
     WebApiConfig.Register(config); 
     config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always; 
     _server = new HttpServer(config); 
    } 

我不現在得到404錯誤。但Unity無法解決DocumentController。 HttpResponse包含錯誤

嘗試創建類型爲 'DocumentController'的控制器時發生錯誤。確保控制器具有 無參數公共構造函數。

TestInitialize方法我叫UnityWebApiActivator.Start()它註冊所有需要的類型與Unity。

回答

0

我解決我的第二問題,通過設置 'HttpConfiguration.DependencyResolver'

[TestInitialize] 
    public void Init() 
    { 
     var config = new HttpConfiguration(); 
     //UnityWebApiActivator.Start(); 
     config.DependencyResolver = new UnityHierarchicalDependencyResolver(UnityConfig.GetConfiguredContainer()); 
     WebApiConfig.Register(config); 
     config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always; 
     _server = new HttpServer(config); 
    }