Home > Back-end >  How to ignore TimeUnit.SECONDS.sleep in unit tests
How to ignore TimeUnit.SECONDS.sleep in unit tests

Time:02-08

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.

CodePudding user response:

  1. extract your business logic into separate method and call it after sleep from your original method. This way in your unit test you can just test your extracted method that does not include sleep.
  2. Make a sleep value as a parameter instead of hardcoded value, and in your test you can set it to a small value while for regular runtime keep it to 30 sec.

CodePudding user response:

To complement the previous answer from @Michael Gantman, currently above:

  1. 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.
  •  Tags:  
  • Related