user3038296
user3038296

Reputation:

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.

Upvotes: 22

Views: 18227

Answers (4)

Tim
Tim

Reputation: 412

Unfortunately, in newer versions it looks like the Fact attribute no longer has a Timeout parameter

Upvotes: 10

holbizmetrics
holbizmetrics

Reputation: 101

To get a concrete example:

You can just use

[Fact(Timeout = 2000)]

for example.

Hint: Timeout is specified in ms.

Upvotes: 9

bbohac
bbohac

Reputation: 351

It seems, what you are looking for is the Timeout parameter of the Fact attribute.

For further information see the XUnit Docs under Ensuring a Test Does Not Run Too Long.

Upvotes: 13

Steve Rukuts
Steve Rukuts

Reputation: 9367

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.

Upvotes: 18

Related Questions