Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xUnit.net how can I specify a timeout how long a test should maximum need

I have integration tests set up with xUnit.net.

Is there a way to configure how long an integration test should last maximum? I mean a threshold.

like image 607
codefruit Avatar asked Nov 29 '13 09:11

codefruit


People also ask

What is test fixture in xUnit?

In xUnit, a test fixture is all the things we need to have in place in order to run a test and expect a particular outcome. Some people call this the test context.

Is xUnit a test runner?

The MSBuild runner in xUnit.net v2 is capable of running unit tests from both xUnit.net v1 and v2. It can run multiple assemblies at the same time, and build file options can be used to configuration the parallelism options used when running the tests.

How do I ignore tests in xUnit?

When using the default testing framework in . NET your tests will be decorated with a testmethod attribute and you can just place the ignore attribute above them. When you have the ignore attribute above a testmethod the test will be skipped. Now when you run your tests you will see that this test has been skipped.


1 Answers

For the newer xunit versions, I am using this method, which seems to work well:

public static class AssertAsync
{
    public static void CompletesIn(int timeout, Action action)
    {
        var task = Task.Run(action);
        var completedInTime = Task.WaitAll(new[] { task }, TimeSpan.FromSeconds(timeout));

        if (task.Exception != null)
        {
            if (task.Exception.InnerExceptions.Count == 1)
            {
                throw task.Exception.InnerExceptions[0];
            }

            throw task.Exception;
        }

        if (!completedInTime)
        {
            throw new TimeoutException($"Task did not complete in {timeout} seconds.");
        }
    }
}

You can use it like so:

[Fact]
public void TestMethod()
{
    AssertAsync.CompletesIn(2, () =>
    {
        RunTaskThatMightNotComplete();
    });
}

However, be sure to read the reason about why this was removed in the first place as one of the maintainers of the project does make a pretty good point about potentially deadlocking your test run. I run these tests in single-threaded mode and it doesn't appear to cause a problem.

like image 91
Steve Rukuts Avatar answered Sep 27 '22 19:09

Steve Rukuts