c# - 单元测试 : Custom Timer Assert

标签 c# unit-testing assert

我想为我的单元测试做一个自定义断言,它将测量两个 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());

谁有更好的办法

关于c# - 单元测试 : Custom Timer Assert,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47098892/

相关文章:

Spring 启动测试 - 找不到测试属性

java - 针对 WAR 运行测试

javascript - 如何创建和缓存尚不存在的 DOM 元素?

try-catch - 何时使用 assert() 何时使用 try catch?

c# - PostgreSQL 错误 : query string argument of EXECUTE is null

c# - 在 WCF 中使用 MvcMailer

javascript - 我如何强制 Karma 在每次测试之间重新启动浏览器?

java - 如何在 Eclipse 程序中启用 Java 关键字断言?

c# - C++/CLI pin_ptr

C# WinForm 在安装时设置 ConnectionString 和 Entity Framework