如何使用 FluentAssertions 在 XUnit 中测试 MediatR 处理程序

How to test MediatR handlers in XUnit with FluentAssertions

我正在使用 XUnit 测试我的 ASP.NET Core 2.2 项目。

与它一起,我在测试项目中有 FluentAssertions。

我想做的是测试我的 MediatR 处理程序。

在这个处理程序中我有 API 调用。

我看了文章,好像需要先设置fixture,但是我没有找到容易理解的代码。

我的处理程序看起来像:

     public class GetCatsHandler : IRequestHandler<GetCatsQuery, GetCatsResponse>
{
    private readonly IPeopleService _peopleService;

    public GetCatsHandler(IPeopleService peopleService)
    {
        _peopleService = peopleService;
    }

    public async Task<GetCatsResponse> Handle(GetCatsQuery request, CancellationToken cancellationToken)
    {
        var apiResponse = await _peopleService.GetPeople();
        List<Person> people = apiResponse;

        var maleCatsGroup = GetCatsGroup(people, Gender.Male);
        var femaleCatsGroup = GetCatsGroup(people, Gender.Female);

        var response = new GetCatsResponse()
        {
            Male = maleCatsGroup,
            Female = femaleCatsGroup
        };

        return response;
    }

    private static IEnumerable<string> GetCatsGroup(IEnumerable<Person> people, Gender gender)
    {
      .....
    }
}

PeopleService 是具有 HttpClient 并调用 API 检索结果的服务 class。

这是我的灯具:

public class GetCatsHandlerFixture : IDisposable
{
    public TestServer TestServer { get; set; }
    public HttpClient Client { get; set; }

    public GetCatsHandlerFixture()
    {
        TestServer = new TestServer(
            new WebHostBuilder()
            .UseStartup<Startup>()
            .ConfigureServices(services => {
            }));

        Client = TestServer.CreateClient();
    }
    public void Dispose()
    {
        TestServer.Dispose();
    }
 }

从这里开始,我如何为不同场景中的 api 调用传递我的模拟数据?

我最终使用 Moq 替换我的 PeopleService 并指定设计的 return 对象进行测试。

效果惊人且易于使用。

看起来像:

  mockPeopleService = new Mock<IPeopleService>();
  var people = ....;

            var expectedResult = new GetCatsResponse()
            {
                Male = new List<string>() { "Garfield", "Jim", "Max", "Tom" },
                Female = new List<string>() { "Garfield", "Simba", "Tabby" }
            };

            mockPeopleService.Setup(ps => ps.GetPeople()).Returns(people);

            var handler = new GetCatsHandler(mockPeopleService.Object);

            var actualResult = await GetActualResult(handler);

            actualResult.Should().BeEquivalentTo(expectedResult, optons => optons.WithStrictOrdering());