使用Autofac和Moq对HttpResponseMessage进行单元测试

时间:2017-06-06 13:53:51

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

我要绕圈子走了。因此,当我在调试中运行时,我的WebApi会将所需的输出返回给浏览器。 Firefox和IE显示我需要的List。但是,当我尝试使用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);
    }
}

1 个答案:

答案 0 :(得分: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);
    }
}