0

I have a simple Xunit project setup to test my code. During the method under test, I make two, separate, consecutive Http requests to an endpoint on the network. My test should check that the first Http request is always made BEFORE the second Http request. Is this possible? Here is what the test looks like. I just need to check if the request with request.AbsolutelUri.EndsWith("Some-Request-1") is made before the subsequent request, ("Some-Request-2).

[Fact]
public async Task HttpRequestMessage1_IsMade_Before_HttpRequest2()
{
    //Arrange
    var builder = new TestClassBuilder();

    var handlerMock = new Mock<HttpMessageHandler>();
    var mockData = fixture.Create<List<string>>();

    var httpClient = new HttpClient(handlerMock.Object);
    var cache = await IMemoryCacheInstance();
    var mapper = new Mock<IMapper>();

    handlerMock.Protected()
               .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.Is<HttpRequestMessage>(rm => rm.RequestUri.AbsoluteUri.EndsWith("Some-Request-1")), ItExpr.IsAny<CancellationToken>())
               .ReturnsAsync(new HttpResponseMessage()
               {
                    StatusCode = System.Net.HttpStatusCode.OK,
                    Content = new StringContent(JsonSerializer.Serialize(mockData), Encoding.UTF8, "application/json")
               })
               .Verifiable();

    handlerMock.Protected()
               .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.Is<HttpRequestMessage>(rm => rm.RequestUri.AbsoluteUri.EndsWith("Some-Request-2")), ItExpr.IsAny<CancellationToken>())
               .ReturnsAsync(new HttpResponseMessage()
               {
                    StatusCode = System.Net.HttpStatusCode.Unauthorized,
                    Content = new StringContent(JsonSerializer.Serialize(mockData), Encoding.UTF8, "application/json")
               })
               .Verifiable();

    var testClass = builder.WithHttpClient(httpClient)
                           .WithMemoryCache(cache)
                           .WithMapper(mapper.Object)
                           .Build();

    //Act
    var result = await testClass.DoSomething(It.IsAny<string>());

    //Assert
    result.Should().NotBeNull();
}

I have not tried anything yet. I have not found a solution. The Assert statement is simply placeholder.

Jonas Nyrup
  • 2,376
  • 18
  • 25
Ben Smith
  • 23
  • 4
  • If trying to validate the sequence with Moq, you can look into MockSequence. Here are some examples: https://github.com/moq/moq4/blob/main/tests/Moq.Tests/MockSequenceFixture.cs https://riptutorial.com/moq/example/23018/validating-call-order-with-mocksequence – Alberto Guerrero Feb 08 '23 at 19:32

0 Answers0