In my humble opinion it is definitely not a good idea! Why?
- It is brittle test because it depends to the CPU load of the machine running the test. Maybe it runs fine on your development machine, and will for sure from time to time fail on your build server because of the load on the server.
- It is slower then needed. If you increase the sleep time so that you “ensure” that the test should pass in all situation then the test will always as long as this time.
So what can we do about it?
One of the first approach is to using polling like NUnit and it’s Delayed Contraint does. But I am not a big fan of this because you have to remember the details of it, and you can fall in that trap easily:
Use of a DelayedConstraint with a value argument makes no sense, since the value will be extracted at the point of call. It’s intended use is with delegates and references. If a delegate is used with polling, it may be called multiple times so only methods without side effects should be used in this way.
My personal preferred approach is:
- to expose as a protected property the Task running the background operation
- to create a SUT class in my test class which inherit from the class with the protected property
- to make the Task a public property of the SUT class
- to have my test use the Task by calling the Task.Wait() just before the assertion
For example here is one of my test using that approach: