简体   繁体   中英

Is there a way to unit test ScheduledExecutorService.scheduleAtFixedRate without using Thread.sleep?

I would like to unit test a class that executes a task using ScheduledExecutorService.scheduleAtFixedRate, and I can't find a way to "schedule" multiple runs of the task in a unit test without using Thread.sleep, which is slow and not as precise as I'd like. Is there any way to pass a mocked time reference to the executor service or other workarounds to simulate the passage of time?

Unit Tests verify behavior of your code in isolation from its dependencies.

The implementations of ScheduledExecutorService are provided by the JVM and therefore not your code, but a dependency that must be replaced with a test double while unittesting your code. (There might be a valid setup for a test that needs the ScheduledExecutorService implementation to be executed, but this is not a unit test then.)

So in case you are writing a unit test (and not some other kind of test as ie integration tests , that happens to be using the JUnit framwork ) you should create a mock for the ScheduledExecutorService interface using a mocking framework (like Mockito or alike) and verify that your code calls the desired method on the mock.

To enable your test for this verification you should inject the implementation of ScheduledExecutorService interface into your code (preferably via constructor injection ) and not have your unit under test acquiring it itself, so that you have a seam at which you can exchange the real implementation of ScheduledExecutorService interface whith the mock for the purpose of unit testing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM