gpt4 book ai didi

c# - 如何正确地对 OData v6.0 Controller 进行单元测试?

转载 作者:太空狗 更新时间:2023-10-29 20:04:15 27 4
gpt4 key购买 nike

我正在尝试对 OData Controller 进行单元测试,但是 API 发生了变化并且我之前尝试过的推荐方法不起作用 - 目前我正在获取

No non-OData HTTP route registered.

当尝试实例化 ODataQueryOptions 以传递给 Controller ​​的 Get 方法时

我当前的代码(基于类似 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 方法的调用:

HttpConfiguration config = new HttpConfiguration();

//1
config.EnableDependencyInjection();

//2
config.EnsureInitialized();

关于c# - 如何正确地对 OData v6.0 Controller 进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40504289/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com