Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for a time-out in a JUnit test case

Tags:

java

junit

I have a JUnit test case where I'm expecting a particular method call to take a long time (over a minute). I want to

  1. Make the method call.
  2. Make sure the method call takes at least a minute and have a JUnit assertion fail if it doesn't.
  3. Then kill the method call (assuming it took more than a minute as it should) because it could take a really long time.

How do I do this?

like image 499
Paul Reiners Avatar asked Jan 21 '23 05:01

Paul Reiners


1 Answers

You can write a class implementing runnable that wraps around the method of interest; assuming spawning threads is allowed.

public class CallMethod implements Runnable
{
   //time in milli
   public long getStartTime()
   {
     return startTime;
   }

   //time in milli
   public long getEndTime()
   {
     return endTime;
   }

   public void run()
   {
       startTime = ...;
       obj.longRunningMethod();
       endTime = ...;
   }
}

Then in your JUnit you can do something like:

public void testCase1()
{
  CallMethod call = new CallMethod();
  Thread t = new Thread(call);
  t.start();
  t.join(60000); // wait one minute

  assertTrue(t.alive() || call.getEndTime() - call.getStartTime() >= 60000);

}
like image 109
Alvin Avatar answered Feb 01 '23 18:02

Alvin