【发布时间】:2020-05-03 19:21:01
【问题描述】:
我的单元测试是-
String xmlText = File.ReadAllText(@"C:\PrashantWorkspace\Weather.xml");
var mockFactory = new Mock<IHttpClientFactory>();
var mockHttpMessageHandler = new Mock<HttpMessageHandler>();
mockHttpMessageHandler.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent(xmlText, Encoding.UTF8, "application/xml"),
});
var client = new HttpClient(mockHttpMessageHandler.Object);
mockFactory.Setup(_ => _.CreateClient(It.IsAny<string>())).Returns(client);
WeatherController wController = new WeatherController(_logger.Object, _configuration.Object, mockFactory.Object);
var result = await wController.Get("1", "2", false);
Assert.IsType<OkObjectResult>(result);
如何在我的控制器中传递第二个 api 调用将使用的另一个 xml?
【问题讨论】:
-
在模拟上使用 SetupSequence
标签: unit-testing asp.net-core dependency-injection moq dotnet-httpclient