简体   繁体   中英

How to unit test a method which will invoke a delegate in a timer handler?

I want to verify the correctness of delegate invoking, but i must wait the timer raise it's event(about 5 seconds), so i should do some operation like Thread.Sleep(5000) in my unit test code, and i think it is not a best practise in unit test.

Is there another better idea for this situation?

模拟计时器并引发事件,无需等待

You need to decouple the code which uses timer and make it depend on some abstraction. Lets say your own interface ITimer and inject it as the dependency.

Then it becomes very easy to mock out ITimer to raise the event immediately.

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