我试图在采用ODataQueryOptions
参数的Web API
控制器方法中对GET方法进行单元测试。我需要验证OData
过滤器的结果,我不知道如何做断言。我坚持什么?我正确地测试这个吗?使用Moq在Web API中进行单元测试OData
我用这作为灵感:Web API, OData, $inlinecount and testing
编辑:我需要坚持这一点对于一个有效的测试?这是我的TryGetContentValue
调用返回的内容。如果是这样,我该怎么做?
{System.Collections.Generic.List`1[CSR.Service.Models.CSRRole].Where($it => ($it.RoleName == value(System.Web.Http.OData.Query.Expressions.LinqParameterContainer+TypedLinqParameterContainer`1[System.String]).TypedProperty))}
单位测试
[TestMethod]
public void GetTestWithOData()
{
// Arrange
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:21584/api/test?$filter=RoleName%20eq%20'User'");
ODataModelBuilder modelBuilder = new ODataConventionModelBuilder();
modelBuilder.EntitySet<CSRRole>("CSRRoles");
var opts = new ODataQueryOptions<CSRRole>(new ODataQueryContext(modelBuilder.GetEdmModel(), typeof(CSRRole)), request);
var uowMock = new Mock<ICSRUnitOfWork>();
uowMock.SetupGet(i => i.TestRepository).Returns(new Mock<IGenericRepository<CSRRole, CSRContext>>().Object);
var controller = new TestController(uowMock.Object);
controller.Request = new HttpRequestMessage();
controller.Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration());
// Act
var result = controller.Get(opts);
//Assert
IQueryable<CSRRole> roles;
Assert.IsNotNull(result);
// **** I don't think this is a good test ****
Assert.IsTrue(result.TryGetContentValue<IQueryable<CSRRole>>(out roles));
}
控制器方法
public HttpResponseMessage Get(System.Web.Http.OData.Query.ODataQueryOptions<CSRRole> options)
{
HttpResponseMessage response;
if (options == null)
{
return response = new HttpResponseMessage(HttpStatusCode.BadRequest);
}
var result = options.ApplyTo(_csrUnitOfWork.TestRepository.Get());
if (result == null)
{
response = new HttpResponseMessage(HttpStatusCode.NotFound);
}
else
{
response = Request.CreateResponse(HttpStatusCode.OK, result);
response.Content.Headers.Expires = new DateTimeOffset(DateTime.Now.AddSeconds(300));
}
return response;
}
你是否以某种方式工作? – Rikard 2015-05-20 07:15:24
@Rikard ......我从来没有放弃过。如果您有解决方案,请发布答案。 – 2015-05-20 10:56:56
我管理测试查询,如果我使用QueryOptions.ApplyTo。你应该使用那个函数来代替吗? – Rikard 2015-05-20 13:19:07