Test deadlock with nUnit

I am new to unit testing and nUnit (2.48). I would like to write a test method in which the failure case is that it blocks. Is it possible? Obviously, nUnit doesn’t know by default how long the method should take to execute, so would I have to write code to work on a separate thread and then interrupt it, and also quit and exclude if it takes more time than I define? Is there a better way to do this?

thanks

+5
source share
5 answers

It is possible, but it may not be the best. Unit tests are not suitable for testing concurrency behavior; unfortunately, there are not many suitable testing methods.

NUnit does nothing with threads. You can write tests that run multiple threads and then test their interaction. But they would become more like integration tests than unit tests.

Another problem is that deadlock behavior usually depends on which order flows are planned. Therefore, it would be difficult to write the final test to check for a specific deadlock problem, because you do not have any control over the scheduling of threads, these are made by the OS. You can complete tests that sometimes fail on multi-core processors but always succeed on single-core processors.

+5

, , , . ( ):

[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);
    }
}

, " ", , .

+7

.

, , . , 100%. , , .

+5

, unit test. ressources . , .

A unit test ( ), .

, .

+3

All Articles