测试之间的共享上下文

时间:2018-12-25 14:20:37

标签: c# timer task-parallel-library xunit

我有以下代码:

public class Batcher<TPayload> : IBatcher<TPayload>
{    
    private static readonly BufferBlock<BatchElement<TPayload>> BufferBlock = new BufferBlock<BatchElement<TPayload>>(new DataflowBlockOptions
    {
        EnsureOrdered = true
    });

    private readonly TransformBlock<BatchElement<TPayload>, BatchElement<TPayload>> BufferInterceptor;
    private readonly TransformBlock<BatchElement<TPayload>, BatchElement<TPayload>> TimeoutInterceptor;

    public EventsBatcher(int size, int interval, IMagicService magicService, ILogger<Batcher<TPayload, TStrategy>> logger)
    {
        BufferInterceptor =
            new TransformBlock<BatchElement<TPayload>, BatchElement<TPayload>>(x =>
            {
                logger.LogInformation($"Get a message with value: {x}");
                return x;
            });

        TimeoutInterceptor =
            new TransformBlock<BatchElement<TPayload>, BatchElement<TPayload>>(x =>
            {
                logger.LogInformation($"Move out from transformation block with a value: {x}");
                return x;
            });

        var batchBlock = new BatchBlock<BatchElement<TPayload>>(size, new GroupingDataflowBlockOptions()
        {
            EnsureOrdered = true
        });

        var timer = new Timer(async _ =>
        {
            try
            {
                batchBlock.TriggerBatch();
                var data = await batchBlock.ReceiveAsync();
                if (!data.Any() && data.SomeLogic())
                     return;

                await magicService.PushMessageAsync(batchElement.Payload);
            }
            catch (Exception e)
            {
                logger.LogError($"Error occurs while trying to invoke action on batch", e);
            }
        }, null, 0, 500);

        var timeoutBlock = new TransformBlock<BatchElement<TPayload>, BatchElement<TPayload>>(v =>
        {
            timer.Change(interval, Timeout.Infinite);
            return v;
        });

        TimeoutInterceptor.LinkTo(batchBlock);
        timeoutBlock.LinkTo(TimeoutInterceptor);
        BufferInterceptor.LinkTo(timeoutBlock);
        BufferBlock.LinkTo(BufferInterceptor);
    }

    public async Task<Result<Unit>> SendAsync(BatchElement<TPayload> msg, CancellationToken token = new CancellationToken())
    {
        try
        {
            var result = await BufferBlock.SendAsync(msg, token);
            return result
                ? ResultFactory.CreateSuccess()
                : ResultFactory.CreateFailure<Unit>("Message was refused by queue");
        }
        catch (Exception e)
        {
            return ResultFactory.CreateFailure<Unit>(e.Message);
        }
    }     
}

每x毫秒应该以某种方式评估数据。我尝试为此编写单元测试,以确保一切正常。这些测试在这里:

public class BatcherTests
{
    public EventsBatcher<int> Initialize(Dictionary<DateTime, int> output)
    {
        var busMock = new Mock<IMagicService>();
        busMock.Setup(x => x.PushMessageAsync(It.IsAny<int>()))
            .Callback<Data>((data) =>
            {
                output.Add(DateTime.Now, data);
            }).Returns(Task.CompletedTask);

        var loggerMock = new Mock<ILogger<Batcher<int>>>();
        return new Batcher<int>(
            2, 
            5000, 
            busMock.Object,
            loggerMock.Object
        );
    }

    [Fact]
    public async Task Batcher_ShouldRemoveDuplicatedMessages()
    {
        var output = new Dictionary<DateTime, int>();
        var batcher = Initialize(output);
        var first = await batcher.SendAsync(new MockEvent { Payload = 1 });
        var second = await batcher.SendAsync(new MockEvent { Payload = 1 });

        (first.IsSuccess && second.IsSuccess).ShouldBeTrue();
        while (output.Count != 2)
        {
        }

        output.Count.ShouldBe(2);
        output.First().Value.ShouldBe(1);
        output.Last().Value.ShouldBe(1);
        output.Clear();
    }

    [Fact]
    public async Task Batcher_WhenSizeIsSetTo2AndWeSend3Items_ReturnTwoBatchedItemsWithDateIntervalPlusMinus5000msAndAllSendRequestsEndsWithSuccess()
    {
        var output = new Dictionary<DateTime, int>();
        var batcher = Initialize(output);

        var first = await batcher.SendAsync(new MockEvent { Payload = 1 });
        var second = await batcher.SendAsync(new MockEvent { Payload = 1 });
        var third = await batcher.SendAsync(new MockEvent { Payload = 1 });

        (first.IsSuccess && second.IsSuccess && third.IsSuccess).ShouldBeTrue();
        while (output.Count != 2) //never ends because there are already two elements in output dictionary
        {
        }

        output.Count.ShouldBe(2);
        output.First().Value.ShouldBe(2);
        output.Last().Value.ShouldBe(1);

        var interval = (output.Last().Key - output.First().Key).TotalSeconds;

        (interval >= 4.5d && interval <= 5.5d).ShouldBeTrue();
        output.Clear();
    }
}

但是奇怪的是,当我分别运行它们时,它们最终会获得成功状态。但是当我将它们全部运行在一起时,其中一个似乎卡住了。这是因为传递给逻辑方法的字典在开始测试时内部有2个元素。我没有看到共享上下文的可能性,因为stub类是在测试用例的开头创建的,与字典相同。我有什么想念的吗?我还尝试将这些测试用例拆分为单独的类,但是会发生相同的行为。

1 个答案:

答案 0 :(得分:1)

有共享声明,但未在测试中(直接)。

您的BufferBlock在类static中被声明为Batcher<TPayload>。有您的共享状态。

private static readonly BufferBlock<BatchElement<TPayload>> BufferBlock = new BufferBlock<BatchElement<TPayload>>(new DataflowBlockOptions
{
    EnsureOrdered = true
});

执行多个测试时,该共享块多次链接到其他块。