Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 单元测试:自定义计时器断言_C#_Unit Testing_Assert - Fatal编程技术网

C# 单元测试:自定义计时器断言

C# 单元测试:自定义计时器断言,c#,unit-testing,assert,C#,Unit Testing,Assert,我想为我的单元测试做一个自定义断言,它将测量两个c#函数的执行时间并比较它们。 我已经写了下面的代码,但是有更好的方法吗 public static class AssertExtensions { public static void MoreSlowThan(Action slowFunction, Action fastFunction) { var watch = Stopwatch.StartNew(); slowFunction();

我想为我的单元测试做一个自定义断言,它将测量两个c#函数的执行时间并比较它们。 我已经写了下面的代码,但是有更好的方法吗

public static class AssertExtensions
{
    public static void MoreSlowThan(Action slowFunction, Action fastFunction)
    {
        var watch = Stopwatch.StartNew();
        slowFunction();
        watch.Stop();
        var watchBis = Stopwatch.StartNew();
        fastFunction();
        watchBis.Stop();
        Assert.IsTrue(watch.ElapsedMilliseconds >= watchBis.ElapsedMilliseconds);
    }
}
召集人:

AssertExtensions.MoreSlowThan(() => MyFunction(), () => MyCachedFunction());

(目标是将函数的执行时间与缓存中相同函数的执行时间进行比较)

我发现最好的方法是使用MSTest-2重构它,如:

public static void IsFaster(this Assert assert, Action expectedFastAction, Action actualSlowAction)
{
    var slowStopwatch = Stopwatch.StartNew();
    actualSlowAction();
    slowStopwatch.Stop();

    var fastStopwatch = Stopwatch.StartNew();
    expectedFastAction();
    fastStopwatch.Stop();

    Assert.IsTrue(slowStopwatch.Elapsed >= fastStopwatch.Elapsed, string.Format("First function would be faster than the second. Fast function elapsed time : {0}. Slow function elapsed time : {1}", fastStopwatch.Elapsed, slowStopwatch.Elapsed));
}
并称之为:

Assert.That.IsSlower(() => MyCachedFunction(), () => MyFunction());

如果有人有更好的方法

这个问题可能更适合stackExchange站点:-)