Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I mock HttpRequestMessage, specifically the CreateResponse?

How can I mock HttpRequestMessage, specifically the CreateResponse?

var requestMessage = Substitute.For<HttpRequestMessage>();
requestMessage.CreateResponse().ReturnsForAnyArgs(
       new HttpResponseMessage(HttpStatusCode.OK));

but I get the exception ...

NSubstitute.Exceptions.CouldNotSetReturnDueToNoLastCallException: 
  'Could not find a call to return from.

I've seen the questions ... How to mock the CreateResponse<T> extension method on HttpRequestMessage

And associated ... ASP.NET WebApi unit testing with Request.CreateResponse ...

But they don't seem to actually end up mocking the CreateResponse

Additional comments:

I'm trying to write a unit test around the starter of an Azure precompiled C# function ...

[FunctionName("Version")]
public static HttpResponseMessage Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]
    HttpRequestMessage req,
    TraceWriter log)
{
    log.Info("Version function processed a request ... ");

    return req.CreateResponse(HttpStatusCode.OK, "Version 0.0.1");
}

and the actual test, where I want to mock up the HttpRequestMessage, specifically the CreateReponse where I get the error is ...

[TestMethod]
public void Version_returns_value()
{
    var requestMessage = Substitute.For<HttpRequestMessage>();
    requestMessage.CreateResponse(Arg.Any<HttpStatusCode>(), Arg.Any<string>())
                  .Returns(new HttpResponseMessage(HttpStatusCode.OK));
    var log = new CustomTraceWriter(TraceLevel.Verbose);

    var httpResponseMessage = VersionFunction.Run(requestMessage, log);
    var httpContent = httpResponseMessage.Content;

    httpContent.Should().Be("Version 0.0.1 :: valid");
}
like image 875
SteveC Avatar asked Jul 21 '17 13:07

SteveC


1 Answers

No need to mock anything here. Everything can be stubbed safely for this test. CreateResponse is an extension method that, internally, makes use of the request's associated HttpConfiguration. That is the only requirements that needs to be setup before using it in your test.

With that, if you update your test as follows, you should be able to properly exercise your test.

[TestMethod]
public async Task Version_returns_value() {
    var expected = "\"Version 0.0.1\"";
    var config = new HttpConfiguration();
    var requestMessage = new HttpRequestMessage();
    requestMessage.SetConfiguration(config);

    var log = new CustomTraceWriter(TraceLevel.Verbose);

    var httpResponseMessage = VersionFunction.Run(requestMessage, null);
    var httpContent = httpResponseMessage.Content;
    var content = await httpContent.ReadAsStringAsync();

    content.Should().Be(expected);
}
like image 165
Nkosi Avatar answered Nov 13 '22 16:11

Nkosi