Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing for a deadlock with nUnit

I'm new to unit testing and nUnit (2.48). I'd like to write a test method where the failure case is that it deadlocks. Is this possible? Obviously nUnit doesn't know by default how long the method should take to execute, so would I have to write code to do the work on a separate thread and then abort it and throw and exception if it took longer than some time I define? Is there a better way to do this?

Thank you

like image 930
xyz Avatar asked Jan 23 '09 12:01

xyz


3 Answers

Well its certainly possible to test for a deadlock by running your code on another thread and seeing if it returns in a timely fashion. Here's some (very basic) example code:

[TestFixture]
public class DeadlockTests
{
    [Test]
    public void TestForDeadlock()
    {
        Thread thread = new Thread(ThreadFunction);
        thread.Start();
        if (!thread.Join(5000))
        {
            Assert.Fail("Deadlock detected");
        }
    }

    private void ThreadFunction()
    {
        // do something that causes a deadlock here
        Thread.Sleep(10000);
    }
}

I wouldn't like to say that this is the "best way", but it is one I have found useful on occasions.

like image 155
Mark Heath Avatar answered Oct 08 '22 00:10

Mark Heath


It is possible but it might not be the best thing to do. Unit tests aren't really suitable for testing concurrency behaviour, unfortunately there aren't many test-methods that are suitable.

NUnit doesnt do anything with threads. You could write tests that start several threads and then test their interaction. But these would start to look more like integration tests than unit tests.

Another problem is that deadlock behaviour usually depends on the order threads are scheduled in. So it would be hard to write a conclusive test to test a certain deadlock issue because you don't have any control over the thread scheduling, this is done by the OS. You could end up with tests that sometimes fail on multicore processors but always succeed on single core processors.

like image 38
Mendelt Avatar answered Oct 08 '22 00:10

Mendelt


Deadlock detection is equivalent to the halting problem, and therefore currently not solvable in the general case.

If you have a specific problem to guard against, there might be specific hacks to get at least a modicum of security. Be aware though, that this can only be a hack and never 100%. For example such a test might always pass on the development machine but never on the production machine.

like image 25
David Schmitt Avatar answered Oct 07 '22 23:10

David Schmitt