如何正确地对OData v6.0控制器进行单元测试? [英] How to correctly unit test OData v6.0 controller?
问题描述
我正在尝试对OData控制器进行单元测试,但是API发生了变化,以前尝试的推荐方法不起作用-当前我正在获得
I'm attempting to unit test out OData controllers, however the APIs changed and previously recommended methods I tried do not work - currently I'm getting
未注册非OData HTTP路由.
No non-OData HTTP route registered.
当尝试实例化ODataQueryOptions传递给控制器的Get方法时
when trying to instantiate ODataQueryOptions to be passed into the Get method of the controller
我当前的代码(基于类似此代码的答案):
My current code (based on answers like 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;
}
感谢任何想法或建议!
推荐答案
从System.Web.OData.Extensions.HttpConfigurationExtensions
类添加对EnableDependencyInjection
方法的调用:
Add a call to EnableDependencyInjection
method from the System.Web.OData.Extensions.HttpConfigurationExtensions
class:
HttpConfiguration config = new HttpConfiguration();
//1
config.EnableDependencyInjection();
//2
config.EnsureInitialized();
这篇关于如何正确地对OData v6.0控制器进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!