1

I have implemented a method that executes some logic, after a certain amount of time, using a TimerTask and Timer.schedule. I want to verify this behaviour using Junit, however, I would like to know if there are better ways to test it, without using thread sleeping, or measuring time.

Thanks.

romain-lavoix
  • 403
  • 2
  • 6
  • 20
  • You can't test whether a timing schedule is correct without measuring time. – Warren Dew Jun 25 '16 at 23:49
  • 1
    Not a direct answer, but you should consider using `java.util.concurrent.ScheduledExecutorService` in new code rather than `java.util.Timer`. See also this question: http://stackoverflow.com/questions/2213109/java-util-timer-is-it-deprecated – Daniel Pryden Jun 26 '16 at 00:03
  • 1
    It certainly is possible to write tests of scheduling code without starting threads or waiting. Instead, you can mock or fake out dependencies. The real question is what you're measuring time relative to -- basically, if the task was executed immediately, how would your test know to fail? Fake that out and you have the solution to your problem. – Daniel Pryden Jun 26 '16 at 00:06
  • Thank you @DanielPryden, that's inspiring, I'll explore that solution – romain-lavoix Jun 26 '16 at 00:38
  • If you need to perform assertions from a Timer or ExecutorService thread, check out [ConcurrentUnit](https://github.com/jhalterman/concurrentunit). – Jonathan Jul 23 '16 at 00:39

1 Answers1

1

You can use a "own thread" excecutor service to get around the "multiple threads" complications.

You can further test that some class A pushes tasks into such a service; and you can also use unit tests to ensure that the parameters used when pushing tasks are what you expect them to be.

In other words: you really don't want to use unit tests to prove that scheduling is working (assuming that you didn't completely re-invent the wheel and you implemented your own scheduling ... which is something that you simply should not do). You want use unit tests to prove that your code is using existing (well tested) frameworks with the arguments you expect to see.

GhostCat
  • 137,827
  • 25
  • 176
  • 248