运行多线程nunit测试的最佳方法

时间:2008-12-09 13:27:47

标签: multithreading unit-testing nunit

我目前正在尝试找到一个解决方案,如果在测试方法产生的线程中发生异常,如何确保测试失败。

我不想在单元测试中开始讨论多个线程。 => “单元测试”.Replace(“unit”,“integration”);

我已经在几个论坛中阅读了很多主题,我知道CrossThreadTestRunner,但我正在寻找一个集成到nunit中的解决方案,并且不需要重写很多测试。

3 个答案:

答案 0 :(得分:3)

答案 1 :(得分:0)

我遇到了同样的问题,我的解决方法是捕获异常并增加异常计数器,因此Test方法只需断言异常计数器为0以确认没有线程得到异常。

删除特定环境内容后,我的测试代码的摘录:

    const int MaxThreads = 25;
    const int MaxWait = 10;
    const int Iterations = 10;
    private readonly Random random=new Random();
    private static int startedThreads=MaxThreads ;
    private static int exceptions = 0;

...

[Test]
    public void testclass()
    {
        // Create n threads, each of them will be reading configuration while another one cleans up

        Thread thread = new Thread(Method1)
        {
            IsBackground = true,
            Name = "MyThread0"
        };

        thread.Start();
        for (int i = 1; i < MaxThreads; i++)
        {
            thread = new Thread(Method2)
            {
                IsBackground = true,
                Name = string.Format("MyThread{0}", i)
            };

            thread.Start();
        }

        // wait for all of them to finish
        while (startedThreads > 0 && exceptions==0)
        {
            Thread.Sleep(MaxWait);
        }
        Assert.AreEqual(0, exceptions, "Expected no exceptions on threads");
    }

    private void Method1()
    {
        try
        {
            for (int i = 0; i < Iterations; i++)
            {
            // Stuff being tested
                Thread.Sleep(random.Next(MaxWait));
            }
        }
        catch (Exception exception)
        {
            Console.Out.WriteLine("Ërror in Method1 Thread {0}", exception);
            exceptions++;
        }
        finally
        {
            startedThreads--;
        }
    }

    private void Method2()
    {
        try
        {
            for (int i = 0; i < Iterations; i++)
            {
                // Stuff being tested
                Thread.Sleep(random.Next(MaxWait));
            }
        }
        catch (Exception exception)
        {
            Console.Out.WriteLine("Ërror in Method2 Thread {0}", exception);
            exceptions++;
        }
        finally
        {
            startedThreads--;
        }
    }

答案 2 :(得分:-7)

我通过为nunit创建一个“安装”ITestDecorator的插件解决了这个问题。