Search code examples
c#unit-testingassert

Unit Test : Custom Timer Assert


I would like to make a custom Assertion for my unit test which would measure the execution time of two c# functions and compare them. I have written the code below, but there is a better way ?

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);
    }
}

called by :

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

(the goal is to compare the execution time of a function with the execution time of the same function in cache)


Solution

  • The best way i found it's refactor it with MSTest-2 like :

    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));
    }
    

    And call it with :

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

    If anyone has a better way