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

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

测试用例:

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

测试结果:

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

 

测试代码

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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);”这样子了,测试通过。

 

posted @   数据酷软件  阅读(250)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示