I have a method which is calling sleep of 30 seconds but I dont want my unit test to have the same. I want my unit test to ignore the sleep and execute the rest on the method or reduce the sleep time to 1 sec.
public runwithSleep(){ System.out.println("Before Sleep Time"); TimeUnit.SECONDS.sleep(30); System.out.println("After Sleep Time"); }
From the above sample code, How do I ignore the TimeUnit.SECONDS.sleep(30)
when executing the unit test for this method. Basically I want to test like if i can reach this method from a condition so I dont want the sleep in the test.
Advertisement
Answer
To complement the previous answer from @Michael Gantman, currently above:
- Replace the dependencies to the sleep method with a dependency to a Sleeper object that you will inject. In the unit tests, you’ll inject a Sleeper that does not wait. Bonus: the tests can interrogate the Sleeper to check if it was called, and with which parameter.