我如何模仿HttpRequestMessage
,特别是CreateResponse
?
var requestMessage = Substitute.For<HttpRequestMessage>();
requestMessage.CreateResponse().ReturnsForAnyArgs(
new HttpResponseMessage(HttpStatusCode.OK));
但我得到例外......
NSubstitute.Exceptions.CouldNotSetReturnDueToNoLastCallException:
'Could not find a call to return from.
我见过这些问题...... How to mock the CreateResponse<T> extension method on HttpRequestMessage
并关联... ASP.NET WebApi unit testing with Request.CreateResponse ...
但他们似乎并没有真正嘲笑CreateResponse
其他评论:
我正在尝试围绕Azure预编译C#函数的启动程序编写单元测试...
[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");
}
和实际测试,我想模拟HttpRequestMessage,特别是我得到错误的CreateReponse是......
[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");
}
答案 0 :(得分:9)
这里不需要嘲笑任何东西。对于此测试,一切都可以安全存根。 CreateResponse
是一种扩展方法,在内部使用请求的关联HttpConfiguration
。这是在测试中使用它之前需要设置的唯一要求。
有了这个,如果您按如下方式更新测试,您应该能够正确地进行测试。
[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);
}