Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly unit test OData v6.0 controller?

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

No non-OData HTTP route registered.

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;

    }

Thanks for any ideas or pointers!

like image 707
kerray Avatar asked Nov 09 '16 10:11

kerray


1 Answers

Add a call to EnableDependencyInjection method from the System.Web.OData.Extensions.HttpConfigurationExtensions class:

HttpConfiguration config = new HttpConfiguration();

//1        
config.EnableDependencyInjection();

//2 
config.EnsureInitialized();
like image 67
Andriy Tolstoy Avatar answered Oct 31 '22 16:10

Andriy Tolstoy