C# Unit Testing - Thread.Sleep(x) - How to Mock the System Clock -
I have to test a method that performs certain functions after the interval.
while (running) {... // work ... thread. Sleep (interval); }
The interval is passed in the class as a parameter, so I can only pass in 0 or 1, but I was curious how to fake the system clock if it That was not the case.
In my trial, I just want to be able to determine the time schedule set by the
I have never written a written test for code that works on the execution thread before and I am sure there are some disadvantages to avoid - please see the approach that you use. Feel free to expand.
Thank you!
If you do not want to test the fact that the thread actually sleeps, then one more direct The approach (and which is possible) is for an ISST service then you can fake it out, and then can not sleep in your tests, but there is an implementation that causes the thread. Sleep in your production code.
IS sleepService sleepService = Container.Resolve & lt; ISleepService & gt; (); .. while (running) {... // work ... sleep service Sleep (interval); }
Use the example:
Public Interface ISSLS Service {Passive Sleep (Inter Interval); } [Test] Public Zero Test () {const int interval = 1000; Fake & lt; ISleepService & gt; SleepService = New Fake & lt; ISleepService & gt; (); SleepService.Setup (s => sleep (this is any & lt; int & gt; ()); _container.RegisterInstance (sleepService.Object); SomeClass someClass = _container.Resolve & lt; SomeClass & gt; (); SomeClass.DoSomething (interval: interval); // Something to say // Alternatively the wine service is called sleeping service. Verify (S => S. sleep (interval)); } Private Class SomeClass {Private Redondly ISleepService _sleepService; Public Classes (IUnityContainer Container) {_sleepService = container.Resolve & lt; ISleepService & gt; (); } Public Zero DoSomething (int interval) {while (true) {_sleepService.Sleep (interval); break; Note the maintenance on a design, if there is pain in changing the manufacturer of "some class" , Or to add dependency injection points for the user of the class, then a service locator type pattern can help here, for example: private class SomeClass {Personal RedondoIsls Service _Saal service ; Public classes () {_sleepService = ServiceLocator.Container.Resolve & lt; ISleepService & gt; (); } Public Zero DoSomething (int interval) {while (true) {_sleepService.Sleep (interval); break; }}}
Comments
Post a Comment