tags:

views:

37

answers:

2

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?

+1  A: 

with JUnit version 4+

@Test(timeout = 100)
public void performanceTest() { ... }
Erhan Bagdemir
I want to make sure that the timeout *does* occur, not that it doesn't occur. The test passes if the timeout does occur.
Paul Reiners
+4  A: 

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);

}
Alvin