【问题标题】:How to test MediatR handlers in XUnit with FluentAssertions如何使用 FluentAssertions 在 XUnit 中测试 MediatR 处理程序
【发布时间】:2019-08-25 15:51:53
【问题描述】:

我正在使用 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 调用传入我的模拟数据?

【问题讨论】:

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


    【解决方案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());
    

    【讨论】:

    • GetActualResult(handler) 在哪里定义,它有什么作用?它会调用 handler.Handle(...) 吗?
    • 另外,请包括“人”的实际设置(var people = ....)
    猜你喜欢
    • 1970-01-01
    • 2022-01-21
    • 2022-01-08
    • 1970-01-01
    • 2019-07-02
    • 2020-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多