Search code examples
javajunitjunit4

How to exclude execution duration from methods annotated with JUnit 4's Before and After annotations


I am running some simple performance tests with JUnit 4 and using Jenkin's perfReport so that I can generate a performance report.

While running these tests, I noticed that the test method execution includes execution time of methods annotated with JUnit 4's @before and @after.

I came across a similar post: Exclude @Before method duration from JUnit test time, however I require my output format in a JUnit-style report since the Jenkin's perfReport parses JUnit-style format only.

As such, is there a way to exclude the execution time of these annotated methods?


Solution

  • I solved it by performing the following:

    1. Extending the BlockJUnit4Runner
    2. Overriding the runChild() method, as this is where test notifiers are received
    3. Writing a custom runLeaf() method, as this is where the test notifiers are fired to notify the test has started or stopped.
    4. Overriding the methodInvoker() method, as this is where the test method is invoked
    5. Creating a new Statement class that functionally, performs the same set of actions as a invokeMethod() statement object created in methodInvoker. This class however, receives the test notifier, thus allow you to control how and when the test is considered to have started.

    One issue of the above approach is that you will need to extract code sections that help to run JUnit rules, in order to preserve rule execution as these methods are strangely private.