0

I have a simple C# Class Calculate which contains a Method Plus:

public class Calculate
{
    private int value1 = 2;
    private int value2 = 4;
    private int result;

    public void Plus(int _value1, int _value2)
    {
        value1 = _value1;
        value2 = _value2;
        result = value1 + value2;
    }

    public int Result
    {
        get { return result; }
    }
}

and generated a unit test as follows:

[TestClass()]
public class CalculateTests
{

    [TestMethod()]
    [Timeout(1000)]
    public void PlusTest()
    {
        Calculate calc1 = new Calculate();
        int counter = 0;
        while (true)
        {
            counter++;
            Random rnd = new Random();
            int x1 = rnd.Next(0, 10);
            int x2 = rnd.Next(0, 10);
            calc1.Plus(x1,x2);
            int expected = 10;
            int actual = calc1.Result;

            string message = string.Format("{0} + {1} = {2} at {3} repetion", x1, x2, actual, counter);
            Assert.AreNotEqual(expected, actual, message);
        }
    }

This test checks if the summation of the two random integers is equal to 10. And it is repeated for 1 second.
The question is how should I set the timeout or modify the test so that if during the timeout the condition x1 + x2 == 10 does not happen, the test is considered as successfully performmed.

Fab
  • 14,327
  • 5
  • 49
  • 68
Behy
  • 483
  • 7
  • 23

1 Answers1

0

Timeout attribute checks duration

It checks that duration of the test is under the given value so you cannot use it in the way you want. You have the write the actual condition to exit the test.

Instead of while(true), why not use :

var endDate = Datetime.Now + Timespan.FromSeconds(1);
while(DateTime.Now < endDate)
{
    // ... check there
}

A bit of context

As you can see here, there is no such a thing as what you are look for. Why?

  • because it's against the whole concept of unit tests (which should be fast, reproducible with consistent and deterministic outcome).
  • it would implies to write unit tests that never stop (the ugly while true) only to be (killed ?) and yet considers that killing the test is a success...

And yes, while(true) is an anti-pattern and other examples:

It means that:

  • if there is an unforseen case for which no break is reached, the program will eat all cpu ... ahah so evil program...
  • it hides somewhat the program flow.
  • it permits to have several different cases of breaks (split of same responsibility across different part of the code)
Fab
  • 14,327
  • 5
  • 49
  • 68
  • It is off course a solution and works properly. But I am searching for a kind of Attribute in `Microsoft.VisualStudio.TestTools.UnitTesting` Namespace like [xTimeout] which meets my need. – Behy Mar 08 '18 at 09:21