简体   繁体   English

如何对将在计时器处理程序中调用委托的方法进行单元测试?

[英]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. 我想验证委托调用的正确性,但是我必须等待计时器引发它的事件(大约5秒),所以我应该在我的单元测试代码中执行一些操作,例如Thread.Sleep(5000),我认为这不是单元测试中的最佳实践。

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. 假设您自己的接口ITimer并将其作为依赖项注入。

Then it becomes very easy to mock out ITimer to raise the event immediately. 这样就很容易模拟出ITimer以立即引发事件。

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

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