NUnit实战,第一个测试类,测试事件触发是否是并行的

以前测试都是新建一个控制台测试的方式来进行,感觉版本管理啥的非常麻烦。也是非常原始的办法。后来想以前有写过测试单元,不过好久没弄了。Nuget了NUnit后写了正式的第一个测试类。

测试用例:

测试事件触发是否是并行的;公司项目经常使用一个自定义的线程池(只有一个工作线程的线程池)内部维护一个Queue,先进队列的数据先放入队列然后再抛给另外一个事件。

测试结果:

事件是支持并行的,事件对应的委托方法是支持多播的。

测试代码

 

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Threading.Tasks;
using System.Diagnostics;

namespace WinLabelPrinter.Tests
{
    [TestClass()]
    public class BarcodeDesignFormTests
    {
        volatile int index = 0;
        public event Action<string, Stopwatch> OnExecScanReceived;

        [TestMethod()]
        public void EventParallelTest()
        {
            this.OnExecScanReceived += BarcodeDesignFormTests_OnExecScanReceived;
            Action demo = () =>
            {
                string data = Guid.NewGuid().ToString().Replace("-", "");
                Stopwatch sw = new Stopwatch();
                sw.Start();
                OnExecScanReceived?.Invoke(data, sw);
            };
            while (index < 10001)
                demo.BeginInvoke(null, null);
            Assert.IsTrue(index % 2 == 0);
        }

        object lockObj = new object();

        private void BarcodeDesignFormTests_OnExecScanReceived(string arg1, Stopwatch arg2)
        {
            while (index < 10001)
            {
                lock (lockObj)
                {
                    index++;
                }
            }
            arg2.Stop();
            //Console.WriteLine(DateTime.Now + "->" + "OnExecScanReceived:" + arg1 + ",耗时:" + arg2.ElapsedMilliseconds);
        }
    }
}

  

测试花絮

刚开始以为index的值是10000,但是调试发现实际是10002。发现我的电脑是双核,所以TPL启动了2个并行的线程。我换成Parallel.Invoke(demo,demo,demo,demo);这样也是10002。所以把断言改成“Assert.IsTrue(index % 2 == 0);”这样子了,测试通过。

 

原文地址:https://www.cnblogs.com/datacool/p/datacool_NUint_2017.html