【问题标题】:How can I assert the duration of the synchronous part of an async call?如何断言异步调用的同步部分的持续时间?
【发布时间】:2023-02-16 23:12:11
【问题描述】:

我需要断言异步方法的 initial synchronous part 在一定时间内执行。流利的断言可能吗?我还需要断言最小和最大总持续时间(例如,使用CompleteWithinAsyncNotCompleteWithinAsync),因此解决方案需要在单个任务调用/等待表达式中涵盖所有三个时间(参见我的其他问题How do I assert that an async task should complete within a minimum and maximum time?) .

【问题讨论】:

  • 在不知道那些指定方法的情况下,我会尝试获取一个 DateTime.Now,然后再定义一个 TimeSpan 并断言两者之间存在差异。这行得通吗?
  • 当方法返回 Task 时,初始同步部分将结束,因此只有您 fluentassertions.com/executiontime 无需等待。但是,如果不模拟 TaskScheduler 的行为,您可能会得到一些变化。
  • 只是好奇:这会告诉你什么,到底是什么?如果测试失败或成功,可能取决于机器及其当时的负载。
  • @Fildor,它是一种可能导致 CI​​/CD 管道间歇性故障的测试。
  • @Fildor 测试涵盖了一些复杂的异步缓存逻辑。测试时,使用虚拟“工作”并控制持续时间,并且断言具有很大的余量。它不完美,但有必要,而且最坏的情况是测试将是明确的(即,不在 CI/DI 中运行)。

标签: c# fluent-assertions


【解决方案1】:

琐碎做作,好像function as expected

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
                    
public class Program
{
    public static async Task Main()
    {
        // Arrange
        static async Task someAsyncBehaviourMock()
        {
            await Task.Yield();
            await Task.Delay(1000);
        };
        
        var s1 = Stopwatch.StartNew();
        var s2 = Stopwatch.StartNew();
        // Act
        var task = Target(someAsyncBehaviourMock);
        s1.Stop();
        await task;
        s2.Stop();
        
        // Assert
        s1.ElapsedMilliseconds.Should().BeGreaterThan(1000).And.BeLessThan(2000);
        s2.ElapsedMilliseconds.Should().BeGreaterThan(2000).And.BeLessThan(3000);
        
        Console.WriteLine(
            $"Success. s1:{s1.ElapsedMilliseconds}, s2:{s2.ElapsedMilliseconds}");
    }
    
    private static async Task Target(Func<Task> someAsyncBehaviour)
    {
        // Initial Sync Behaviour
        Thread.Sleep(1000);
        
        // Injected Async Behaviour
        await someAsyncBehaviour();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    • 2012-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-02
    相关资源
    最近更新 更多