-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathtestng_listeners.html
511 lines (495 loc) · 20.5 KB
/
testng_listeners.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="Asciidoctor 2.0.18">
<title>TestNG Listeners</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400,700">
<link rel="stylesheet" href="./asciidoctor.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prettify/r298/prettify.min.css">
</head>
<body class="article toc2 toc-left">
<div id="header">
<div id="toc" class="toc2">
<div id="toctitle">Table of Contents</div>
<ul class="sectlevel2">
<li><a href="#_testng_listeners">TestNG Listeners</a></li>
</ul>
</div>
</div>
<div id="content">
<div class="sect2">
<h3 id="_testng_listeners">TestNG Listeners</h3>
<div class="paragraph">
<p>There are several interfaces that allow you to modify TestNG’s behavior. These interfaces are broadly called "TestNG Listeners". Here are a few listeners:</p>
</div>
<div class="sect3">
<h4 id="_listener_list">Listener list</h4>
<table class="tableblock frame-all grid-all stretch">
<colgroup>
<col style="width: 33.3333%;">
<col style="width: 33.3333%;">
<col style="width: 33.3334%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">Listener name</th>
<th class="tableblock halign-left valign-top">User Documentation</th>
<th class="tableblock halign-left valign-top">API Documentation</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">IAlterSuiteListener</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="altering_suites.html">docs</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">{javadocs-base-url}/org/testng/IAlterSuiteListener.html[javadocs]</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">IAnnotationTransformer</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="annotation_transformers.html">docs</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">{javadocs-base-url}/org/testng/IAnnotationTransformer.html[javadocs]</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">IConfigurationListener</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="method_invocations.html#_listening_to_configuration_invocations">docs</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">{javadocs-base-url}/org/testng/IConfigurationListener.html[javadocs]</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">IDataProviderListener</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="method_invocations.html#_listening_to_data_provider_invocations">docs</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">{javadocs-base-url}/org/testng/IDataProviderListener.html[javadocs]</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">IExecutionListener</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="method_invocations.html#_listening_to_testng_lifecycle_events">docs</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">{javadocs-base-url}/org/testng/IExecutionListener.html[javadocs]</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">IExecutionVisualiser</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="execution_visualiser.html">docs</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">{javadocs-base-url}/org/testng/IExecutionVisualiser.html[javadocs]</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">IHookable</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="ihookable.html">docs</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">{javadocs-base-url}/org/testng/IHookable.html[javadocs]</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">IConfigurable</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="iconfigurable.html">docs</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">{javadocs-base-url}/org/testng/IConfigurable.html[javadocs]</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">IInvokedMethodListener</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="method_invocations.html#_listening_to_method_invocations">docs</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">{javadocs-base-url}/org/testng/IInvokedMethodListener.html[javadocs]</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">IClassListener</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="method_invocations.html#_listening_to_class_level_invocations">docs</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">{javadocs-base-url}/org/testng/IClassListener.html[javadocs]</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">IMethodInterceptor</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="method_interceptors.html#_method_interceptors">docs</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">{javadocs-base-url}/org/testng/IMethodInterceptor.html[javadocs]</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">IDataProviderInterceptor</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="method_interceptors.html#_interceptors_for_data_providers">docs</a>.</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">{javadocs-base-url}/org/testng/IDataProviderInterceptor.html[javadocs]</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">IReporter</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="logging_and_results.html#_logging_reporters">docs</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">{javadocs-base-url}/org/testng/IReporter.html[javadocs]</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">ISuiteListener</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="method_invocations.html#_listening_to_suite_level_invocations">docs</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">{javadocs-base-url}/org/testng/ISuiteListener.html[javadocs]</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">ITestListener</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="logging_and_results.html#_logging_listeners">docs</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">{javadocs-base-url}/org/testng/ITestListener.html[javadocs]</p></td>
</tr>
</tbody>
</table>
</div>
<div class="sect3">
<h4 id="_specifying_listeners_with_testng_xml_or_in_java">Specifying listeners with testng.xml or in Java</h4>
<div class="paragraph">
<p>Here is how you can define listeners in your <code>testng.xml</code> file:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code data-lang="xml"><suite>
<listeners>
<listener class-name="com.example.MyListener" />
<listener class-name="com.example.MyMethodInterceptor" />
</listeners>
<!-- rest of the contents omitted for brevity -->
</suite></code></pre>
</div>
</div>
<div class="paragraph">
<p>Or if you prefer to define these listeners in Java:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code data-lang="java">@Listeners({ com.example.MyListener.class, com.example.MyMethodInterceptor.class })
public class MyTest {
// ...
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>@Listeners</code> annotation can contain any class that extends <code>org.testng.ITestNGListener</code> except <code>IAnnotationTransformer</code>. The reason is that these listeners need to be known very early in the process so that TestNG can use them to rewrite your annotations, therefore you need to specify these listeners in your <code>testng.xml</code> file.</p>
</div>
<div class="paragraph">
<p>Note that the <code>@Listeners</code> annotation will apply to your entire suite file, just as if you had specified it in a testng.xml file. If you want to restrict its scope (for example, only running on the current class), the code in your listener could first check the test method that’s about to run and decide what to do then. Here’s how it can be done.</p>
</div>
<div class="ulist">
<ul>
<li>
<p>First define a new custom annotation that can be used to specify this restriction:</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code data-lang="java">@Retention(RetentionPolicy.RUNTIME)
@Target ({ElementType.TYPE})
public @interface DisableListener {}</code></pre>
</div>
</div>
<div class="ulist">
<ul>
<li>
<p>Add an edit check as below within your regular listeners:</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code data-lang="java">public void beforeInvocation(IInvokedMethod iInvokedMethod, ITestResult iTestResult) {
ConstructorOrMethod consOrMethod =iInvokedMethod.getTestMethod().getConstructorOrMethod();
DisableListener disable = consOrMethod.getMethod().getDeclaringClass().getAnnotation(DisableListener.class);
if (disable != null) {
return;
}
// else resume your normal operations
}</code></pre>
</div>
</div>
<div class="ulist">
<ul>
<li>
<p>Annotate test classes wherein the listener is not to be invoked:</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code data-lang="java">@DisableListener
@Listeners({ com.example.MyListener.class, com.example.MyMethodInterceptor.class })
public class MyTest {
// ...
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_specifying_listeners_with_serviceloader">Specifying listeners with ServiceLoader</h4>
<div class="paragraph">
<p>Finally, the JDK offers a very elegant mechanism to specify implementations of interfaces on the class path via the <a href="https://docs.oracle.com/javase/6/docs/api/java/util/ServiceLoader.html">ServiceLoader</a> class.</p>
</div>
<div class="paragraph">
<p>With ServiceLoader, all you need to do is create a jar file that contains your listener(s) and a few configuration files, put that jar file on the classpath when you run TestNG and TestNG will automatically find them.</p>
</div>
<div class="paragraph">
<p>Here is a concrete example of how it works.</p>
</div>
<div class="paragraph">
<p>Let’s start by creating a listener (any TestNG listener should work):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code data-lang="java">package test.tmp;
public class TmpSuiteListener implements ISuiteListener {
@Override
public void onFinish(ISuite suite) {
System.out.println("Finishing");
}
@Override
public void onStart(ISuite suite) {
System.out.println("Starting");
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Compile this file, then create a file at the location <code>META-INF/services/org.testng.ITestNGListener</code>, which will name the implementation(s) you want for this interface.</p>
</div>
<div class="paragraph">
<p>You should end up with the following directory structure, with only two files:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code data-lang="bash">$ tree
|____META-INF
| |____services
| | |____org.testng.ITestNGListener
|____test
| |____tmp
| | |____TmpSuiteListener.class
$ cat META-INF/services/org.testng.ITestNGListener
test.tmp.TmpSuiteListener</code></pre>
</div>
</div>
<div class="paragraph">
<p>Create a jar of this directory:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code data-lang="bash">$ jar cvf ../sl.jar .
added manifest
ignoring entry META-INF/
adding: META-INF/services/(in = 0) (out= 0)(stored 0%)
adding: META-INF/services/org.testng.ITestNGListener(in = 26) (out= 28)(deflated -7%)
adding: test/(in = 0) (out= 0)(stored 0%)
adding: test/tmp/(in = 0) (out= 0)(stored 0%)
adding: test/tmp/TmpSuiteListener.class(in = 849) (out= 470)(deflated 44%)</code></pre>
</div>
</div>
<div class="paragraph">
<p>Next, put this jar file on your classpath when you invoke TestNG:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code data-lang="bash">$ java -classpath sl.jar:testng.jar org.testng.TestNG testng-single.yaml
Starting
f2 11 2
PASSED: f2("2")
Finishing</code></pre>
</div>
</div>
<div class="paragraph">
<p>This mechanism allows you to apply the same set of listeners to an entire organization just by adding a jar file to the classpath, instead of asking every single developer to remember to specify these listeners in their <code>testng.xml</code> file.</p>
</div>
</div>
<div class="sect3">
<h4 id="_ordering_listeners_in_testng">Ordering listeners in TestNG</h4>
<div class="paragraph">
<p>TestNG now allows you to control the order in which listeners are executed.</p>
</div>
<div class="paragraph">
<p>This is particularly useful when you have multiple listeners that are altering the test result states and so you would like to ensure that they do so in some deterministic order.</p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
This feature is ONLY available from TestNG version <code>7.10.0</code>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Following is how we can get this done.</p>
</div>
<div class="ulist">
<ul>
<li>
<p>To start with, you would need to build an implementation of the interface <code>org.testng.ListenerComparator</code></p>
</li>
<li>
<p>Now this implementation needs to be plugged into TestNG via the configuration parameter <code>-listenercomparator</code></p>
</li>
</ul>
</div>
<div class="admonitionblock caution">
<table>
<tr>
<td class="icon">
<i class="fa icon-caution" title="Caution"></i>
</td>
<td class="content">
TestNG orders only user’s listeners and which are not part of the exclusion list that can be specified via the JVM argument <code>-Dtestng.preferential.listeners.package</code> (Multiple fully qualified class names can be specified as comma separated values). If nothing is specified, TestNG by default excludes all the IntelliJ IDEA listeners under the package <code>com.intellij.rt.*</code>.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Let’s see an example.</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Let’s create a custom annotation that will help us define the order in which <strong>our</strong> listeners should be invoked.</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code data-lang="java">@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@Target({ TYPE})
public @interface RunOrder {
int value();
}</code></pre>
</div>
</div>
<div class="ulist">
<ul>
<li>
<p>Now let’s create an implementation of <code>org.testng.ListenerComparator</code> which honours this custom annotation that we just now created.</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code data-lang="java">import org.testng.ITestNGListener;
import org.testng.ListenerComparator;
import java.util.Optional;
public class AnnotationBackedListenerComparator implements ListenerComparator {
@Override
public int compare(ITestNGListener l1, ITestNGListener l2) {
int first = getRunOrder(l1);
int second = getRunOrder(l2);
return Integer.compare(first, second);
}
private static int getRunOrder(ITestNGListener listener) {
RunOrder runOrder = listener.getClass().getAnnotation(RunOrder.class);
return Optional.ofNullable(runOrder)
.map(RunOrder::value)
.orElse(Integer.MAX_VALUE); //If annotation was not found then return a max value so that
//the listener can be plugged in to the end.
}
}</code></pre>
</div>
</div>
<div class="ulist">
<ul>
<li>
<p>Lets say we have the below listeners as samples.</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code data-lang="java">import org.testng.IExecutionListener;
public class ExecutionListenerHolder {
public static final String PREFIX = ExecutionListenerHolder.class.getName() + "$";
public abstract static class KungFuWarrior implements IExecutionListener {
@Override
public void onExecutionStart() {
System.err.println(getClass().getSimpleName() + ".onExecutionStart");
}
@Override
public void onExecutionFinish() {
System.err.println(getClass().getSimpleName() + ".onExecutionFinish");
}
}
@RunOrder(1)
public static class MasterOogway extends KungFuWarrior { }
@RunOrder(2)
public static class MasterShifu extends KungFuWarrior { }
public static class DragonWarrior extends KungFuWarrior { }
}</code></pre>
</div>
</div>
<div class="ulist">
<ul>
<li>
<p>A sample code snippet that uses the TestNG APIs to run the test could look like below:</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code data-lang="java">TestNG testng = create(NormalSampleTestCase.class);
testng.addListener(new ExecutionListenerHolder.DragonWarrior());
testng.addListener(new ExecutionListenerHolder.MasterShifu());
testng.addListener(new ExecutionListenerHolder.MasterOogway());
testng.setListenerComparator(new AnnotationBackedListenerComparator());
testng.run();</code></pre>
</div>
</div>
<div class="paragraph">
<p>Here’s a variant of the same above sample, which invokes the <code>main()</code> method:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code data-lang="java">String prefix = ExecutionListenerHolder.PREFIX;
String[] args = new String[] {
"-listener",
prefix + "DragonWarrior,"+
prefix + "MasterShifu,"+
prefix + "MasterOogway",
"-testclass",
NormalSampleTestCase.class.getName(),
"-listenercomparator",
AnnotationBackedListenerComparator.class.getName()
};
TestNG.main(args);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Here’s how the trimmed version of execution output would look like:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code data-lang="bash">MasterOogway.onExecutionStart
MasterShifu.onExecutionStart
DragonWarrior.onExecutionStart
===============================================
Command line suite
Total tests run: 2, Passes: 2, Failures: 0, Skips: 0
===============================================
DragonWarrior.onExecutionFinish
MasterShifu.onExecutionFinish
MasterOogway.onExecutionFinish</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
As seen from the above output, we wanted to have the listener <code>MasterOogway</code> be invoked first, followed by the listener <code>MasterShifu</code> and finally <code>DragonWarrior</code> (because this class does not have any <code>@RunOrder</code> annotation and hence it should be ONLY added at the end)
</td>
</tr>
</table>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
Also it should be noted that the teardown methods get executed in a symmetrical order. So if <code>onExecutionStart()</code> of the listener <code>DragonWarrior</code> got executed as the last listener, then its corresponding <code>onExecutionFinish()</code> would be called first.
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
<div id="footer">
<div id="footer-text">
Last updated 2025-02-27 18:51:48 UTC
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prettify/r298/run_prettify.min.js"></script>
</body>
</html>