【问题标题】:Mock HttpClient with multiple clients to be used in single controller模拟HttpClient,具有多个客户端要用于单个控制器
【发布时间】: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


【解决方案1】:

如果您的意思是您有 另一个端点(而不是第二次调用 同一端点),那么您可以传递一个与 @987654321 匹配的谓词@HttpRequestMessage:

_httpMessageHandlerMock = new Mock<HttpMessageHandler>();

var booksResponse = new HttpResponseMessage
{
    StatusCode = HttpStatusCode.OK,
    Content = new StringContent(
        @"<?xml version=""1.0"" encoding=""utf-8""?> ")
};

_httpMessageHandlerMock
    .Protected()
    .Setup<Task<HttpResponseMessage>>(
        "SendAsync",
        ItExpr.Is<HttpRequestMessage>(x =>
            x.RequestUri != null && x.RequestUri.ToString().Contains("books")),
        ItExpr.IsAny<CancellationToken>())
    .ReturnsAsync(booksResponse);

var authorsResponse = new HttpResponseMessage
{
    StatusCode = HttpStatusCode.OK,
    Content = new StringContent(
        @"<?xml version=""1.0"" encoding=""utf-8""?> ")
};

_httpMessageHandlerMock
    .Protected()
    .Setup<Task<HttpResponseMessage>>(
        "SendAsync",
        ItExpr.Is<HttpRequestMessage>(x =>
            x.RequestUri != null && x.RequestUri.ToString().Contains("authors")),
        ItExpr.IsAny<CancellationToken>())
    .ReturnsAsync(authorsResponse);

_client = new HttpClient(_httpMessageHandlerMock.Object) {BaseAddress = new Uri("http://tempuri")};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-12
    相关资源
    最近更新 更多