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 –
我最終沒有嘲笑響應內容,只是設置了響應 –