lundi 22 mai 2017

How to unit test method with disposable objects in it

I was having unit test about my controller which was looking like that:

    [Test]
    public void Test()
    {
        //Arrange
        var dummySeamlessCustomerRequest = CustomerControllerTestsHelper.CreateDummyCustomerRequest();
        var dummySeamlessCustomerResponse = CustomerControllerTestsHelper.CreateDummyCustomerResponse();

        _mockSeamlessService.Setup(s => s.GetSeamlessCustomerCallRequest(_controller.Request, "Credit Customer"))
            .Returns(new ModuleResultSet<SeamlessCustomerRequest>(HttpStatusCode.OK, null, dummySeamlessCustomerRequest));

        _mockAdapter.Setup(a => a.SendCreditCustomerCallToProvider(dummySeamlessCustomerRequest))
            .Returns(dummySeamlessCustomerResponse);

        //Act
        var actionResult = _controller.CreditCustomer();
        var expectedResponse = actionResult as ResponseMessageResult;

        //Assert
        Assert.IsNotNull(expectedResponse);
        Assert.AreEqual(CustomerControllerTestsHelper.CreateSeamlessCustomerResponseString(dummySeamlessCustomerResponse),
            expectedResponse.Response.Content.ReadAsStringAsync().Result);
    }

My targeted method by the test is the following:

    public override IHttpActionResult CreditCustomer()
    {
        //...

        using (var response = new HttpResponseMessage())
        {

            //...
            return this.ResponseMessage(response);
        }
    }

I left most important part of the method to me(if you think I should show more tell me but there are only some service calls that I mock in my test with ease. Problem is that when I run my test I receive following error:

Test Name: Test Test FullName: ETIAdapter.Tests.Controllers.CustomerControllerTests.Test Test Outcome: Failed Test Duration: 0:00:00.005

Result StackTrace:
at System.Net.Http.HttpContent.CheckDisposed() at System.Net.Http.HttpContent.ReadAsStringAsync() at ETIAdapter.Tests.Controllers.CustomerControllerTests.Test() in D:\Repositories\test_seamless-service\seamless-service\src\ETIAdapter.Tests\Controllers\CustomerControllerTests.cs:line 79 Result Message: System.ObjectDisposedException : Cannot access a disposed object. Object name: 'System.Net.Http.StringContent'.

I tried to search for solutions to test such methods but I couldn't find it. Most of the questions are about custom objects that implement IDisposable so they are mocking them , but I can't do that with HttpResponseMessage.

Aucun commentaire:

Enregistrer un commentaire