2013-10-29 59 views
11

我曾提升網絡API項目到最新版本,使用MVC 5 應用程序正常運行,但此行的代碼是不是我單位工作了測試:單元測試與不工作的ASP.NET MVC 5級網站API路線數據

string uri = this.Url.Link("DefaultApi", new { id = savedOrganization.Id }); 

控制器的Url屬性現在爲空。 這是我如何配置模擬控制器:

var config = new HttpConfiguration(); 
var request = new HttpRequestMessage(HttpMethod.Post, "http://xxx/api/organization"); 
var route = config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}"); 
var routeData = new HttpRouteData(route, new HttpRouteValueDictionary {{"controller", "organization"}}); 

controller.ControllerContext = new HttpControllerContext(config, routeData, request); 
controller.Request = request; 
controller.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config; 
controller.Request.Properties[HttpPropertyKeys.HttpRouteDataKey] = routeData; 

升級到MVC 5這是工作的罰款之前。

當我調試測試表明Url屬性是現在空 enter image description here

回答

13

它看起來像在MVC 5以不同的方式創建Url屬性。 我在我的測試中引入了這一行,現在Url屬性恢復正常了

private static void SetupControllerForTests(ApiController controller) 
{ 
    var config = new HttpConfiguration(); 
    var request = new HttpRequestMessage(HttpMethod.Post, "http://api.clientele-itsm.com/api/organization"); 
    var route = config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}"); 
    var routeData = new HttpRouteData(route, new HttpRouteValueDictionary 
    { 
     {"id", Guid.Empty}, 
     {"controller", "organization"} 
    }); 
    controller.ControllerContext = new HttpControllerContext(config, routeData, request); 
    UrlHelper urlHelper = new UrlHelper(request); 
    controller.Request = request; 
    controller.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config; 
    controller.Request.Properties[HttpPropertyKeys.HttpRouteDataKey] = routeData; 
    /// inject a fake helper 
    controller.Url = urlHelper; 
}