使用Moq.在Web API中对OData进行单元测试

本文关键字:OData 单元测试 中对 API Moq Web 使用 | 更新日期: 2023-09-27 18:28:18

我正试图在接受ODataQueryOptions参数的Web API控制器方法中对GET方法进行单元测试。我需要验证OData过滤器的结果,但我不知道如何进行断言。我凭什么断言?我测试得正确吗?

我正以此为灵感:Web API、OData、$inlinecount和测试

编辑:我需要断言这一点才能进行有效的测试吗?这是我的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;
        }

使用Moq.在Web API中对OData进行单元测试

您也需要模拟opts。例如:

var opts = new Mock<IDataQueryOptions>();
opts.Setup(m => m.ApplyTo(It.IsAny</* Whatever class this takes in */>()))
    .Returns(/* Whatever this needs to return */);

注意mock作用于接口,所以您也需要创建它。对于一个模拟对象,您可以调用tell它来返回单元测试所需的任何内容。