测试异步方法并没有给出一致的结果

本文关键字:结果 异步方法 并没有 测试 | 更新日期: 2023-09-27 18:25:34

我正在努力找出为什么我的单元测试在与解决方案中的其他单元测试一起运行时会失败,但在单独运行时会通过。有人能告诉我我缺了什么吗?

SUT是一个名为CompositeClient的类,本质上是围绕另外两个客户端的包装类。它的主要思想是优先考虑其中一个客户。

public class CompositeClient : IReceiverChannel
{
    private static readonly List<IReceiverChannel> ReceiverChannels = new List<IReceiverChannel>();
    public CompositeClient(IReceiverChannel priority, IReceiverChannel normal)
    {
        ReceiverChannels.Add(priority);
        ReceiverChannels.Add(normal);
    }
    public async Task<IEnumerable<Request>> ReceiveBatchAsync(int batchSize)
    {
        var req = new List<Request>();
        foreach (var channel in ReceiverChannels)
        {
            req.AddRange(await channel.ReceiveBatchAsync(batchSize - req.Count).ConfigureAwait(false));
            if (req.Count >= batchSize)
            {
                break;
            }
        }
        return req;
    }
}

将下面的单元测试与解决方案中的所有其他单元测试一起运行会导致失败。但如果我单独运行这个测试,它就会通过

[TestMethod]
public async Task ReceivedRequestShouldComeFromPriorityClientFirst()
{
    var normalPriorityClient = GetNormalClientMock();
    var highPriorityClient = GetPriorityClientMock();
    var compositeClient = new CompositeClient(highPriorityClient, normalPriorityClient);
    var requests = await compositeClient.ReceiveBatchAsync(1);  
    requests.Should().HaveCount(1);
    requests.First().Origin.Should().BeSameAs("priority");
    normalPriorityClient.CallCount.Should().Be(1); // It will fail here with actual CallCount = 0.
    highPriorityClient.CallCount.Should().Be(0);
}
private static ReceiverChannelMock GetNormalClientMock()
{
    return new ReceiverChannelMock("normal");
}
private static ReceiverChannelMock GetPriorityClientMock()
{
    return new ReceiverChannelMock("priority");
}
private class ReceiverChannelMock : IReceiverChannel
{
    private readonly string name;
    public ReceiverChannelMock(string name)
    {
        this.name = name;
    }
    public int CallCount { get; private set; }
    public Task<IEnumerable<Request>> ReceiveBatchAsync(int batchSize)
    {
        this.CallCount++;
        return Task.FromResult<IEnumerable<Request>>(
            new List<Request>
                            {
                                new Request
                                    {
                                        Origin = this.name
                                    }
                            });
    }
}

使用的工具:

  • Visual Studio 2013
  • .NET框架4.5.2
  • Resharper 9.2
  • FluentAssession

测试异步方法并没有给出一致的结果

正如David所指出的,我忽略了在CompositeClient类中声明的静态字段。删除static关键字解决了问题。