我試圖在採用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