vendredi 4 septembre 2015

Moq: HttpContextBase.ApplicationInstance invocation failed with mock behavior Strict

I'm trying to mock up an HttpContextWrapper for an API controller method that is supposed to return the UserHostAddress. I have no control over the implementation. I am only supposed to unit test the code that I have been given.

I have followed some examples already on StackOverflow, and while I have come closer to achieving what I need, I can't get past this exception:

Moq.MockException : HttpContextBase.ApplicationInstance invocation failed with mock behavior Strict. All invocations on the mock must have a corresponding setup.

Here are my unit test methods:

    private static HttpRequestMessage CreateRequest(string url, string mthv, HttpMethod method)
    {
        var request = new HttpRequestMessage();

        var baseRequest = new Mock<HttpRequestBase>(MockBehavior.Strict);
        var baseContext = new Mock<HttpContextBase>(MockBehavior.Strict);

        baseRequest.Setup(br => br.UserHostAddress).Returns("127.0.0.1");
        baseContext.Setup(bc => bc.Request).Returns(baseRequest.Object);

        var baseContextWrapper = new Mock<HttpContextWrapper>(baseContext.Object.ApplicationInstance.Context);

        request.RequestUri = new Uri(url);
        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(mthv));
        request.Properties.Add("MS_HttpContext", baseContextWrapper.Object);
        request.Method = method;

        return request;
    }

    [Test]
    public void IsClientIpAddressReturned()
    {
        // Assign
        var request = CreateRequest("http://myserver/api/CustomerController", "application/json", HttpMethod.Get);

        var apiCachedController = new ApiCachedController();

        // Act
        RequestManager.RegisterRequestWithThread();

        var address = apiCachedController.GetClientIpAddress(request);

        // Assert
        Assert.AreEqual(address, "127.0.0.1");
    }

Aucun commentaire:

Enregistrer un commentaire