Test Instance Post-processing

Understand how to test instances post-process using TestInstancePostProcessor in JUnit 5.

We'll cover the following

Extension interface

After test instances are created by JUnit, we can post-process them using extensions. This is useful when we want to inject custom dependencies into test instances or invoke custom logic on test instances. The extension interface for test instances post-process is TestInstancePostProcessor. It only has one method, void postProcessTestInstance(Object testInstance, ExtensionContext context) throws Exception. The testInstance parameter is the test instance to process. The ExtensionContext is also passed to retrieve context information.

Suppose that some test cases require configuration information contained in the class Config. We can have a ConfigAware interface to set the Config object. See the code below, for example.

Get hands-on with 1200+ tech skills courses.