1
我正在圈圈。所以当我在调试中运行时,我的WebApi将所需的输出返回给浏览器。 Firefox和IE显示我需要的列表。然而,当我试图单元测试使用模拟和Autofac的响应HttpResponseMessage
我回来没有内容。我感觉它是在不同的上下文或类似的东西上返回的。我不完全确定,因此提出这个问题。我通过谷歌搜索和Autofac文档一起把下面的单元测试一起串起来。使用Autofac和Moq单元测试HttpResponseMessage
WebApiMethod(包含在InScrapController
,_WebScrapSprocService
由Autofac在构造函数注入)
public HttpResponseMessage GetFormItemsByFormNumber(int FormNumber)
{
HttpResponseMessage response;
try
{
//response = Request.CreateResponse(HttpStatusCode.OK, _WebScrapSprocService.GetFormItemsByFormNumber(FormNumber),new MediaTypeHeaderValue("application/json"));
response = Request.CreateResponse(HttpStatusCode.OK, new MediaTypeHeaderValue("application/json"));
response.Content = new StringContent(JsonConvert.SerializeObject(_WebScrapSprocService.GetFormItemsByFormNumber(FormNumber)),Encoding.UTF8, "application/json");
} catch (Exception e)
{
response = Request.CreateResponse(HttpStatusCode.InternalServerError, new StringContent(e.Message), new MediaTypeHeaderValue("application/json"));
}
//Checking if bob knows anything about this...
string bob = response.Content.ReadAsStringAsync().Result;
return response;
}
单元测试
public void GetFormItemsByFormNumber()
{
using (var mock = AutoMock.GetLoose())
{
var Service = mock.Mock<IWebScrapSprocService>().Setup(x => x.GetFormItemsByFormNumber(3392));
var service = mock.Create<InScrapController>();
service.Request = new HttpRequestMessage();
service.Request.SetConfiguration(new HttpConfiguration());
var HttpResponse = service.Request.CreateResponse(HttpStatusCode.OK, Service, new MediaTypeHeaderValue("application/json"));
var response = service.GetFormItemsByFormNumber(3392);
mock.Mock<IWebScrapSprocService>().Verify(x => x.GetFormItemsByFormNumber(3392));
Assert.AreEqual(HttpResponse, response);
}
}
任何理由简单地移除'串BOB = response.Content.ReadAsStringAsync()结果;'我有问题茎形式ReadAsStringAsync根本就不是被mockable –
我最终没有嘲笑响应内容,只是设置了响应 –