How to unit test a timer based on System.Threading.Timer in .NET The System.Threading.Timer has a callback method
相关问题
- Generic Generics in Managed C++
- How to Debug/Register a Permanent WMI Event Which
- How to let a thread communicate with another activ
- 'System.Threading.ThreadAbortException' in
- Bulk update SQL Server C#
You can unit-test it by not actually creating a direct dependency on
System.Threading.Timer
. Instead, create anITimer
interface, and a wrapper aroundSystem.Threading.Timer
that implements it.First you need to convert the callback to an event, so that it can be made part of an interface:
Then create an interface:
And a wrapper:
Obviously you would add whatever overloads of the constructor and/or
Change
method you need to use from theThreading.Timer
. Now you can unit test anything depending onITimer
with a fake timer:Whenever you want to simulate a tick, just call
RaiseTickEvent
on the fake.Hopefully whatever this feature is a larger part of allows the timer interval to be configured. You should be able to use that interface to inject a short interval suitable for unit testing. I do have the question the value of this test: Are you testing the interval (pointless) or that the routine is actually called approximately every so often?
I will test it in the same way as any other class but with short time intervals as to avoid the unit test to run a long time. Another approach is to test your own code only and using a mock timer (eg. NMock), but it depends how your code design is. Can you post some code snippets?
If the time simply changes the callback method then you just need to check the correctness of that method, not how the system time works.
Besides that, I recommend using the MultimediaTimer instead - it is much more accurate.