Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Junit Test case for java.util.Timer/TimerTask

 
Alka Bhardwaj
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How can we create Junit test cases for class that schedules the task with Timer?
 
Timothy Frey
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could just write test cases for your TimerTask; I think it's safe to assume that Timer works correctly.
 
Lasse Koskela
author
Sheriff
Posts: 11962
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let's say you have three objects:
- java.util.Timer
- com.acme.YourTimerTask
- com.acme.YourClassThatUsesTimer

You could test that...
...YourTimerTask does what it's supposed to when its run() method is invoked.
...YourClassThatUsesTimer schedules an appropriately configured YourTimerTask when it's supposed to.
 
Alka Bhardwaj
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Main class -> initialises log file, parameter from xml file, timer, schedules the task.
Task -> Inturn calls log file to log the information, reads the parameter from the parameter file(which is initilized from the main class)

So the problem is that I am able to write the test case for Main class as it is the one that initilizes all the parameters and files.
But when I try to run the test case for Task, half of the time it executes the exceptions as everything that it needs is not initilazed (as every configurable thing is indirectly available form Main class).
I am not sure how to write a test case for the task. Its an old application which was written by someone else and project team wants to evaluavate if we can create unit test cases for each class.
To me it looks like the testcase would look more like integrated test case than unit test case :-( Any suggestion if in such a case it is better to write normal integration test case or still can we write unit test cases??
 
Timothy Frey
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sounds like your TimerTask is strongly coupled with your main class. Is it possible for you to reduce this coupling. For example, instead of having your TimerTask access the member variables of your Main class directly, you can pass them into the TimerTask's constructor. Then you can provide prepared objects during your test cases:



In your production code, you would pass in the Main class's Log and paramter but during testing you can pass in whatever you want. Will this work in your case?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic