Testing for a deadlock with nUnit

时间秒杀一切 提交于 2019-12-05 08:04:44

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.

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.

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.

Take a look at the Microsoft Project called "Chess". It is designed to find concurred bugs http://research.microsoft.com/en-us/projects/chess/

To test for a deadlock, you must implement a state graph and a check for cycles in your current state graph in the unit test. The state graph consists of the ressources as nodes and the dependencies as edges. I have no idea of the implementation of such a thing, but thats the theory.

A unit test tests for the correctness of the in and output of data (mainly for the later point) and not for the correctness of the execution flow of your application.

Mark Heath's idea seems reasonable, but is academically wrong.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!