Instantiate new System.Web.Http.OData.Query.ODataQueryOptions in nunit test of ASP.NET Web API controller

ぐ巨炮叔叔 提交于 2019-12-04 01:00:20
user483679

Looks like someone else already answered this in the comments here, but it's not a complete solution for my use-case (see comment below):

ODataModelBuilder modelBuilder = new ODataConventionModelBuilder(); 
modelBuilder.EntitySet<Customer>("Customers"); 
var opts = new ODataQueryOptions<Customer>(new ODataQueryContext(modelBuilder.GetEdmModel(),typeof(Customer)), request);

This is the solution I have been using in my NUnit tests to inject ODataQueryOptions

private static IEdmModel _model;
private static IEdmModel Model
{
    get
    {
        if (_model == null)
        {
            var builder = new ODataConventionModelBuilder();

            var baseType = typeof(MyDbContext);
            var sets = baseType.GetProperties().Where(c => c.PropertyType.IsGenericType && c.PropertyType.GetGenericTypeDefinition() == typeof(IDbSet<>));
            var entitySetMethod = builder.GetType().GetMethod("EntitySet");
            foreach (var set in sets)
            {
                var genericMethod = entitySetMethod.MakeGenericMethod(set.PropertyType.GetGenericArguments());
                genericMethod.Invoke(builder, new object[] { set.Name });
            }

            _model = builder.GetEdmModel();
        }

        return _model;
    }
}

public static ODataQueryOptions<T> QueryOptions<T>(string query = null)
{
    query = query ?? "";
    var url = "http://localhost/Test?" + query;
    var request = new HttpRequestMessage(HttpMethod.Get, url);
    return new ODataQueryOptions<T>(new ODataQueryContext(Model, typeof(T)), request);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!