简体   繁体   中英

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#? Let's say a test for SemaphoreSlim implementation. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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