在ASP.NET的Web API控制器NUnit测试实例化新System.Web.Http.OData.Query.ODataQueryOptions [英] Instantiate new System.Web.Http.OData.Query.ODataQueryOptions in nunit test of ASP.NET Web API controller
问题描述
我有一个接受ODataQueryOptions参数作为其输入之一的ApiController,继承控制器的ASP.NET MVC4的Web API项目。
I have an ASP.NET MVC4 Web API project with an ApiController-inheriting controller that accepts an ODataQueryOptions parameter as one of its inputs.
我使用NUnit和起订量测试的项目,这让我从由ApiController使用的相关库方法设置的自动回应。这工作,如:
I am using NUnit and Moq to test the project, which allow me to setup canned responses from the relevant repository methods used by the ApiController. This works, as in:
[TestFixture]
public class ProjectControllerTests
{
[Test]
public async Task GetById()
{
var repo = new Mock<IManagementQuery>();
repo.Setup(a => a.GetProjectById(2)).Returns(Task.FromResult<Project>(new Project()
{
ProjectID = 2, ProjectName = "Test project", ProjectClient = 3
}));
var controller = new ProjectController(repo.Object);
var response = await controller.Get(2);
Assert.AreEqual(response.id, 2);
Assert.AreEqual(response.name, "Test project");
Assert.AreEqual(response.clientId, 3);
}
}
我的挑战是,要使用这个模式,我需要在相关的查询字符串参数传递给控制器和存储库(这实际上是我的意图)。然而,在案件ODataQueryOptions,接受ApiController方法,甚至在我想只使用默认参数ODataQueryOptions的情况下,我需要知道如何实例之一。这得到棘手的:
The challenge I have is that, to use this pattern, I need to pass in the relevant querystring parameters to the controller as well as the repository (this was actually my intent). However, in the case of ODataQueryOptions-accepting ApiController methods, even in the cases where I would like to use just the default parameters for ODataQueryOptions, I need to know how to instantiate one. This gets tricky:
- ODataQueryOptions没有实现一个接口,所以我不能直接嘲笑它。
- 构造要求System.Web.Http.OData.ODataQueryContext的实现,这需要一些实施Microsoft.Data.Edm.IEdmModel,为其文档是稀缺的和Visual Studio 2012查找引用和查看调用层次结构的实现不提供洞察(什么实现该接口?)。
什么我需要做的/是否有这样做的更好的办法?
What do I need to do/Is there a better way of doing this?
感谢。
推荐答案
看起来像别人已经回答了这个在评论<一个href=\"http://stackoverflow.com/questions/15790695/web-api-odata-inlinecount-and-testing?rq=1\">here,但它不是我的用例的完整解决方案(见下文评论)
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);
这篇关于在ASP.NET的Web API控制器NUnit测试实例化新System.Web.Http.OData.Query.ODataQueryOptions的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!