I’ve been reading over the questions about unit testing with timers and threading. I found the SO question about unit testing system.threading.timers, but I need to unit test a system.timers.timer and a wrapper class doesn’t seem to work quite as smoothly for this one.
I just need to know how to mock the timer and/or system time in order to unit test against it. I can’t seem to find this anywhere on google.
edit & update:
It makes sense that if I extract the timer by wrapping it as below, I can generate a timer and use mocking to replace it with a different timer. The relevant part is then to take that timer that I’m injecting at runtime (the original, not a mock) and test it’s elapsed event code.
What stops you from wrapping this one?
That’s pretty much all your interface needs. Let’s see how this could go (note that you could of course expose more
Timerproperties, but that’s pretty much basic stuff that should be enough):Now, how would you utilize this in your testing (assuming we’re using FakeItEasy as mocking framework of choice):
Example above actually does test the code that happens once the event on timer is raised. Consider
MyClasslooking like this:In the test, we force timer to raise when we need it, and we check whether code in
TimerElapsedHandlerexecuted, by assertingReceivedEventproperty was set. In reality, this method might do more than that, but that will only change the way we do assertions – idea remains the same.Edit: You can also try Moles, a framework that allows you to generate fakes of any framework types/methods. However, if mocking timer was all you wanted, I’d go with wrapper approach.