简体   繁体   English

为信号量编写单元测试?

[英]Writing a unit test for a semaphore?

I've found a lot of questions on how to write tests for multithreaded code. 我发现了很多有关如何为多线程代码编写测试的问题。 They are mostly too abstract anyway and there are only a few examples of real tests. 无论如何,它们大多太抽象了,只有很少的真实测试示例。 I came up with a more narrow question. 我提出了一个更狭窄的问题。

How to write a good test for a semaphore in C#? 如何在C#中为信号量编写好的测试? Let's say a test for SemaphoreSlim implementation. 假设有一个针对SemaphoreSlim实现的测试。 It should cover the essence logic not the whole bunch of implementation details. 它应该覆盖本质逻辑,而不是全部实现细节。

It's always very difficult to test any blocking operation. 测试任何阻塞操作始终非常困难。 Typically, a lock / semaphore is tested functionally. 通常,对锁/信号量进行功能测试。 In other words, rather than try to create a complex unit test to try and verify blocking calls, I'd recommend creating a test that attempts to break the code... Semaphores are usually used to throttle so if the code remains functional despite a very heavy battery of calls, I'd consider it good. 换句话说,与其建议创建一个复杂的单元测试来尝试验证阻塞调用,不如创建一个尝试破坏代码的测试...信号量通常用于限制信号,因此即使有大量的电话,我认为这很好。 Semaphores are not code you've written (assuming you're using the .NET provided classes), so you should not feel the need to test their functionality. 信号量不是您编写的代码(假设您使用的是.NET提供的类),因此您不应感到需要测试它们的功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM