How test code performance in Junit

In the previous article, we saw how to write a test case to test an exception How to test Exception in JUnit? In this article, we will learn how to test the performance of a test case.

Test Performance in JUnit

The performance of code is an important aspect of any programming language. In this article, we will be testing the performance of arrays. To know more about sorting arrays in JUnit do check here How to Compare Arrays in JUnit Automation Test.

When we want to have a strict performance to some code then JUnit provides us an option of timeout. During testing, when some test case takes more time than the required JUnit will fail the test case automatically. The value of timeout is given in milliseconds.

Write Unit Test to Test a Performance

We will understand the testing of performance using an example. In this example, we will create an array of integers. It is initialized with three values. And, we will test the sorting of millions of records of the arrays of three-element each is happening within 1000 ms.(we will be using timeout)

Step 1: Open Eclipse > File > New > Maven Project.

Step 2: Now, you will get a New Maven Project. Check the create a simple project. Click on Next.

Step 3: Now, Enter group id, artifact id as shown below

Step 4: First, create our JUnit Test case. Here, we will keep our test file in a separate package. Mostly, we keep the test case file inside src/test/java. After that, click Finish. After Finish you will get the alert box, just click OK.

Step 5: Now, we will get the default test case generated and we will modify the code as shown below

package in.codedec.junit.util;

import static org.junit.Assert.*;

import java.util.Arrays;

import org.junit.Test;

public class PerformanceTest {

    @Test(timeout=1000)
    public void test() {
        int a[] = {50,60,20};
        for (int i = 1; i <=1000000; i++) {
            a[0] = i;
            Arrays.sort(a);
        }
    }

}
  • On-line no:11, Add the timeout attribute in the @Test annotation. It will check the performance of the Arrays.sort() method like whether it is able to sort the records in 1000 ms.
  • On-line no:13, an array of integers is created which is initialized with some values.
  • On-line no:16, Use Arrays.sort() to sort millions of records.

Step 6: Now, Run the Application as JUnit Test and see the following stack trace.

Here, after running the JUnit test, we can observe that the sorting of arrays is possible in 1000 ms. Hence the Test is run successfully.

From here, we can conclude that if you have a strict performance in your project then we can use the timeout attribute.

Thus, in this way, we learn how to test the performance of our code by just simply using @Test(timeout = value in milliseconds).