![]() |
VOOZH | about |
Using TestNG listeners specifically IInvokedMethodListener we can capture all kinds of nice info related to the test method just before and after it actually invokes. This is quite handy when you are building logs and log parsers to debug and give contextual info in a report. In this way, you have much control over the execution flow and can monitor and interact during runtime.
To get the description of a test method before and after execution in TestNG, one can follow these steps. This approach involves developing a listener that will connect to the execution of test methods and provide the required information.
With TestNG, you can create listener classes that enable you to apply custom behavior during the lifetime of a test. For this case, we will use the IInvokedMethodListener interface to obtain information about test method invocation, both before and after its execution.
The IInvokedMethodListener interface contains two methods:
To begin, create a class that implements the IInvokedMethodListener interface. This class will hold the logic for capturing and displaying the description of test methods.
To activate the listener, you need to attach it to your test class. There are two common ways to do this:
In your test class, you can annotate test methods with the @Test annotation, providing a description for each method. This description will be displayed before and after the test method runs.
Once the listener is attached and the test methods are annotated with descriptions, you can run the test suite as usual. TestNG will automatically invoke the custom listener and output the descriptions of each test method before and after execution.
CustomListener.java
TestClass.java
testng.xml
Output:
Using the TestNG listeners, particularly IInvokedMethodListener, you easily get information about a test method before and after its invocation. Logging, debugging, and further invocation for report addition may use this. You also have better control over the flow of execution using the powerful listener interface in TestNG and can track and interact with the methods while they are being executed.