2016-11-09 32 views
7

我試圖單元測試出OData的控制器,但API的變化,先前建議我嘗試不工作方法 - 目前我得到如何正確單元測試OData v6.0控制器?

沒有登記的非的OData HTTP路線。

試圖實例ODataQueryOptions時傳遞到控制器的Get方法

我當前的代碼(基於像this one答案):

 [TestMethod()] 
    public void RankingTest() 
    { 
     var serviceMock = new Mock<IVendorService>(); 
     serviceMock.SetReturnsDefault<IEnumerable<Vendor>>(new List<Vendor>() 
     { 
      new Vendor() { id = "1" } 
     }); 

     HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/odata/Vendor"); 

     ODataModelBuilder builder = new ODataConventionModelBuilder(); 
     builder.EntitySet<Vendor>("Vendor"); 
     var model = builder.GetEdmModel(); 

     HttpRouteCollection routes = new HttpRouteCollection(); 
     HttpConfiguration config = new HttpConfiguration(routes) { IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always }; 

     // attempting to register at least some non-OData HTTP route doesn't seem to help 
     routes.MapHttpRoute("Default", "{controller}/{action}/{id}", 
      new 
      { 
       controller = "Home", 
       action = "Index", 
       id = UrlParameter.Optional 
      } 
      ); 
     config.MapODataServiceRoute("odata", "odata", model); 
     config.Count().Filter().OrderBy().Expand().Select().MaxTop(null); 
     config.EnsureInitialized(); 

     request.SetConfiguration(config); 
     ODataQueryContext context = new ODataQueryContext(
      model, 
      typeof(Vendor), 
      new ODataPath(
       new Microsoft.OData.UriParser.EntitySetSegment(
        model.EntityContainer.FindEntitySet("Vendor")) 
      ) 
     ); 


     var controller = new VendorController(serviceMock.Object); 
     controller.Request = request; 

     // InvalidOperationException in System.Web.OData on next line: 
     // No non-OData HTTP route registered 
     var options = new ODataQueryOptions<Vendor>(context, request); 

     var response = controller.Get(options) as ViewResult; 

    } 

感謝您的任何意見或指針!

回答

12

調用EnableDependencyInjection方法從System.Web.OData.Extensions.HttpConfigurationExtensions類地址:

HttpConfiguration config = new HttpConfiguration(); 

//1   
config.EnableDependencyInjection(); 

//2 
config.EnsureInitialized(); 
+2

謝謝,這似乎已經做到了! – kerray