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

时间:2019-04-04 01:39:17

标签: c# asp.net-core xunit fluent-assertions mediatr

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

与此同时,我在测试项目中有FluentAssertions。

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

在此处理程序中,我有API调用。

我已经通读了文章,似乎我需要首先设置固定装置,但是我发现代码不容易理解。

我的处理程序如下:

     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检索结果的服务类。

这是我的固定装置:

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调用传递模拟数据?

1 个答案:

答案 0 :(得分:1)

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

它的工作原理惊人且易于使用。

看起来像这样:

  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());
相关问题