【问题标题】:Unit testing HttpResponseMessage with Autofac and Moq使用 Autofac 和 Moq 对 HttpResponseMessage 进行单元测试
【发布时间】:2017-06-06 13:53:51
【问题描述】:

我在兜圈子。因此,当我在调试中运行时,我的 WebApi 将它需要的输出返回给浏览器。 Firefox 和 IE 显示我需要的列表。但是,当我尝试使用 Mock 和 Autofac 对响应进行单元测试时,HttpResponseMessage 我回来时没有内容。我觉得它正在返回不同的上下文或类似的东西。我不完全确定,因此提出这个问题。我通过谷歌搜索和 Autofac 文档将以下单元测试串在一起。

WebApiMethod(包含在InScrapController内,_WebScrapSprocService由Autofac在构造函数中注入)

public HttpResponseMessage GetFormItemsByFormNumber(int FormNumber)
{
    HttpResponseMessage response;
    try
    {
        //response = Request.CreateResponse(HttpStatusCode.OK, _WebScrapSprocService.GetFormItemsByFormNumber(FormNumber),new MediaTypeHeaderValue("application/json"));
        response = Request.CreateResponse(HttpStatusCode.OK, new MediaTypeHeaderValue("application/json"));
        response.Content = new StringContent(JsonConvert.SerializeObject(_WebScrapSprocService.GetFormItemsByFormNumber(FormNumber)),Encoding.UTF8, "application/json");
    } catch (Exception e)
    {
        response = Request.CreateResponse(HttpStatusCode.InternalServerError, new StringContent(e.Message), new MediaTypeHeaderValue("application/json"));
    }
    //Checking if bob knows anything about this...
    string bob = response.Content.ReadAsStringAsync().Result;
    return response;
}

单元测试

public void GetFormItemsByFormNumber()
{
    using (var mock = AutoMock.GetLoose())
    {

        var Service = mock.Mock<IWebScrapSprocService>().Setup(x => x.GetFormItemsByFormNumber(3392));
        var service = mock.Create<InScrapController>();
        service.Request = new HttpRequestMessage();
        service.Request.SetConfiguration(new HttpConfiguration());
        var HttpResponse = service.Request.CreateResponse(HttpStatusCode.OK, Service, new MediaTypeHeaderValue("application/json"));
        var response = service.GetFormItemsByFormNumber(3392);
        mock.Mock<IWebScrapSprocService>().Verify(x => x.GetFormItemsByFormNumber(3392));
        Assert.AreEqual(HttpResponse, response);
    }
}

【问题讨论】:

    标签: c# unit-testing asp.net-web-api moq autofac


    【解决方案1】:

    这些反应不会相同。也应该重构被测方法。您也没有取回任何内容,因为您还没有设置服务以返回任何内容。

    public IHttpActionResult GetFormItemsByFormNumber(int FormNumber) {
        IHttpActionResult response;
        try {
            var result = _WebScrapSprocService.GetFormItemsByFormNumber(FormNumber);
            response = Ok(result);
        } catch (Exception e) {
            response = InternalServerError(e);
        }
        return response;
    }
    

    接下来更新测试

    public void GetFormItemsByFormNumber() {
        using (var mock = AutoMock.GetLoose()) {
            // Arrange.
            var formNumber = 3392;
            var items = new List<FormItemsByFormNumber> {
                new FormItemsByFormNumber { 
                    //Populate as needed 
                },
                new FormItemsByFormNumber { 
                    //Populate as needed 
                },
                //...etc
            };
            var serviceMock = mock.Mock<IWebScrapSprocService>();
            serviceMock.Setup(x => x.GetFormItemsByFormNumber(formNumber)) // Calling this...
                .Returns(items) // should return some value...
                .Verifiable();  // and I want to verify that it was called.
            var sut = mock.Create<InScrapController>();
    
            // Act.   
            var response = sut.GetFormItemsByFormNumber(formNumber) as OkNegotiatedContentResult<List<FormItemsByFormNumber>>();
    
            // Assert.
            serviceMock.Verify(); //verify setups were exercised as expected.
            Assert.IsNotNull(response);
        }
    }
    

    【讨论】:

    • 简单地删除 string bob = response.Content.ReadAsStringAsync().Result; 的任何原因我遇到的问题是 ReadAsStringAsync 根本无法模拟
    • 我最终没有模拟响应内容,只是设置了响应
    猜你喜欢
    • 1970-01-01
    • 2016-12-25
    • 2017-01-19
    • 1970-01-01
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    • 2012-06-01
    相关资源
    最近更新 更多