简体   繁体   中英

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");
}

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM