ker*_*ray 7 c# unit-testing odata asp.net-web-api2
我正在尝试对OData控制器进行单元测试,但API已更改,之前推荐的方法我尝试不起作用 - 目前我正在使用
没有注册非OData HTTP路由.
当试图将ODataQueryOptions实例化为传递给控制器的Get方法时
我当前的代码(基于像回答这一个):
[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;
}
Run Code Online (Sandbox Code Playgroud)
感谢您的任何想法或指示!
And*_*toy 12
EnableDependencyInjection从System.Web.OData.Extensions.HttpConfigurationExtensions类中添加对方法的调用:
HttpConfiguration config = new HttpConfiguration();
//1
config.EnableDependencyInjection();
//2
config.EnsureInitialized();
Run Code Online (Sandbox Code Playgroud)