Search code examples
javajunitexecution-time

JUnit: testing speed of calculating


For example, I have a method which computes two numbers with some of the following operation "addition, subtraction, multiplication, division" and returns result.

public int sum(int a, int b) {
   return a + b;
}

Is there a way I can test time of execution of the method, if it didn't take longer than 0.5s to calculate?


Solution

  • Use @Test(timeout=1000) to annotate your test method.

    Timeout parameter on @Test Annotation (applies to test method)

    You can optionally specify timeout in milliseconds to cause a test method to fail if it takes longer than that number of milliseconds. If the time limit is exceeded, the the failure is triggered by an Exception being thrown:

    Have a look over junit doku.