Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good practice to measure executed time of a method in a unit test to throw an exception if it runs too slow?

All is in the title, and I wonder if it is a good practice or not :

[TestMethod]
public void Compute_Array_In_Less_1_Second()
{
    Stopwatch watcher = new Stopwatch();

    int[] A = Enumerable.Range(0, 50000).Select(i => GetRandomNumber(MIN_INT, MAX_INT)).ToArray();

    watcher.Start();
    int[] R = Program.MethodThatReturnsAnArray(A);
    watcher.Stop();

    if (watcher.ElapsedMilliseconds > 1000)
        Assert.Fail("The method runs in more 1 second");
}
like image 334
Florian Avatar asked Mar 12 '12 16:03

Florian


2 Answers

No it's not.

Unit tests are not performed under 'normal' conditions so the results would be useless.

Use Unit-testing to verify the correct semantics of your code.

Set up a performance test (usually end-to-end) under conditions close to the production environment.

like image 61
Henk Holterman Avatar answered Oct 13 '22 23:10

Henk Holterman


You should be using the appropriate mechanisms provided by your testing framework, like: http://nunit.org/index.php?p=timeout&r=2.5

But note that you don't want to be doing this everywhere ( to measure performance) but to test that the unit is actually finishing in time or times out if it needs to do that.

like image 44
manojlds Avatar answered Oct 13 '22 23:10

manojlds