In the last week I've created two classes which my team expressed some concerns about in regards to their performance. To evaluate my code I wrote some simple JUnit tests which exercised these classes by building rich sets of test data, then feeding that data through the relevant methods for thousands of iterations. I recorded the runtime of each iteration then logged out the high, low, and average times by using loops and System.nanoTime()
. Finally I had JUnit assert that the high and average times were within acceptable limits. This testing approach gave my team confidence in this code.
Is JUnit the right tool to test performance in this way? Are there better tools to test performance at the unit (method and class) level?
Using a unit testing tool allows the tests to run automatically within a CI/CD process, under a test management system such as TestRail. Performance testing, on the other hand, is the process of determining how fast a piece of software executes.
Which methods cannot be tested by the JUnit test class? Explanation: When a method is declared as “private”, it can only be accessed within the same class. So there is no way to test a “private” method of a target class from any JUnit test class.
There may be better approaches, but there are also some frameworks that help implement benchmarking with JUnit. Some useful practices are warmup runs, statistical evaluations. Take a look at JUnitBenchmarks and JUnitPerf
EDIT looks like JUnitBenchmarks has been deprecated since the question has been stated. The project's maintainers recommend moving on to JMH. Thank you, Barry NL for the heads-up.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With