-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathassertj-core-features-highlight.html
836 lines (668 loc) · 46.2 KB
/
assertj-core-features-highlight.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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="AssertJ site">
<meta name="author" content="Joel Costigliola">
<title>AssertJ / Fluent assertions for java</title>
<!-- CSS -->
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Inconsolata|Source+Code+Pro|Open+Sans|Ubuntu|Varela+Round|Karla">
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="font-awesome/css/font-awesome.min.css" rel="stylesheet">
<script src="highlight/highlight.pack.js"></script>
<link rel="stylesheet" href="highlight/styles/railscasts.css">
<script>hljs.initHighlightingOnLoad();</script>
<link href="css/assertj.min.css" rel="stylesheet">
<link rel="shortcut icon" href="favicon.png" />
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<!-- You'll want to use a responsive image option so this logo looks good on devices - I recommend using something like retina.js (do a quick Google search for it and you'll find it) -->
<a class="navbar-brand" href="index.html">AssertJ</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="assertj-core-quick-start.html">Quick start</a></li>
<li><a href="assertj-news.html">News</a></li>
<li><a href="assertj-core.html">Core</a></li>
<li><a href="assertj-assertions-generator.html">Assertions generator</a></li>
<li><a href="assertj-guava.html">Guava</a></li>
<li><a href="assertj-joda-time.html">Joda-Time</a></li>
<li><a href="assertj-db.html">DB</a></li>
<li><a href="assertj-neo4j.html">Neo4j</a></li>
<li><a href="assertj-swing.html">Swing</a></li>
<li><a href="assertj-help.html">Help</a></li>
</ul>
</div>
</div>
</nav>
<div class="container">
<div class="row">
<div class="col-md-2 assertj-sidebar-menu">
<div class="bs-sidebar hidden-print affix-top" role="complementary">
<ul class="bs-sidenav nav ">
<li class="sidenav-header">Main</li>
<li><a href="assertj-core.html">Overview</a></li>
<li><a href="assertj-core-quick-start.html">Quick start</a></li>
<li><a href="assertj-core-news.html">News & releases</a></li>
<li><a href="assertj-core-features-highlight.html">Features highlight</a></li>
<li><a href="assertj-core-conditions.html">Using conditions</a></li>
<li><a href="assertj-core-custom-assertions.html">Custom assertions</a></li>
<li><a href="http://joel-costigliola.github.io/assertj/core/api/index.html" target="_blank">Javadoc (2.x)</a></li>
<li><a href="http://joel-costigliola.github.io/assertj/core-8/api/index.html" target="_blank">Javadoc (3.x)</a></li>
<li><a href="assertj-core.html#help">Help & F.A.Q</a></li>
<li><a href="assertj-core.html#code">Code & issues <i class="fa fa-github"></i></a></li>
<li><a href="assertj-core.html#team">Team</a></li>
<li><a href="assertj-core.html#contributing">Contributing</a></li>
<li class="sidenav-header">Migrating</li>
<li><a href="assertj-core-converting-junit-assertions-to-assertj.html">JUnit 4 Assertions</a></li>
<li><a href="assertj-core-converting-junit5-assertions-to-assertj.html">JUnit 5 Assertions</a></li>
<li><a href="assertj-core-converting-testng-assertions-to-assertj.html">TestNG Assertions</a></li>
<li><a href="assertj-core-migrating-from-fest.html">Fest Assert</a></li>
</ul>
</div>
</div>
<div class="col-lg-10 col-md-10 col-sm-10 text-left" >
<h1 class="page-header">AssertJ Core new website!</h1>
<h2 style="color:darkblue;font-style: italic;">AssertJ Core site has moved to <a href="https://assertj.github.io/doc/">https://assertj.github.io/doc/</a></h2>
<h1 class="page-header">AssertJ Core features highlight</h1>
<p>AssertJ has many great features that not everybody is aware of, here are some of them.</p>
<p>Basic tips :</p>
<ul>
<li>Java 8 assertions, see release notes : <a href="assertj-core-news.html#assertj-core-3.8.0">3.8.0</a> / <a href="assertj-core-news.html#assertj-core-3.7.0">3.7.0</a> / <a href="assertj-core-news.html#assertj-core-3.6.0">3.6.0</a> / <a href="assertj-core-news.html#assertj-core-3.5.0">3.5.0</a> / <a href="assertj-core-news.html#assertj-core-3.4.0">3.4.0</a> / <a href="assertj-core-news.html#assertj-core-3.3.0">3.3.0</a> /<a href="assertj-core-news.html#assertj-core-3.2.0">3.2.0</a> / <a href="assertj-core-news.html#assertj-core-3.1.0">3.1.0</a> / <a href="assertj-core-news.html#assertj-core-3.0.0">3.0.0</a> </li>
<li><a href="#ide-automatic-static-import">IDE configuration to directly get <span class="small-code">assertThat</span> in code completion</a></li>
<li><a href="#describe-assertion">Describe your assertion using <span class="small-code">as(String description, Object... args)</span></a></li>
<li><a href="#exception-assertion">Exception assertions guide</a></li>
<li><a href="#file-content-string-assertions">Using String assertions on the content of a file</a></li>
</ul>
<p>Iterable and arrays assertions :</p>
<ul>
<li><a href="#filters">Combining filtering and assertions on iterables or arrays</a></li>
<li><a href="#extracted-properties-assertion">Assertions on extracted properties/fields of iterable/array elements</a></li>
<li><a href="#flat-extracted-properties-assertion">Flat(map) extracting</a></li>
<li><a href="#extracted-method-result-assertion">Assertions on results of a method call on iterable/array elements</a></li>
</ul>
<p>Advanced tips :</p>
<ul>
<li><a href="#soft-assertions">Gather all errors message with soft assertions</a></li>
<li><a href="#custom-comparison-strategy">Using a custom comparison strategy in assertions</a></li>
<li><a href="#field-by-field-comparison">Field by field comparisons</a></li>
<li><a href="#custom-representation">Using a custom representation in assertions</a></li>
<li><a href="assertj-core-conditions.html">Extending assertions with conditions</a></li>
<li><a href="assertj-core-custom-assertions.html">Creating assertions for your domain</a></li>
</ul>
<h3 class="page-header"><span id="ide-automatic-static-import"></span><i class="fa fa-star"></i> IDE configuration to get assertThat in code completion</h3>
<p>We want to start typing <span class="small-code">asser</span> and let code completion suggest <span class="small-code">assertThat</span> from AssertJ (and not the one from Hamcrest !).</p>
<p class="list-section">Eclipse configuration</p>
<ol>
<li>Go to : Window > Preferences > Java > Editor > Content Assist > Favorites > New Type</li>
<li>Enter : <span class="small-code">org.assertj.core.api.Assertions</span> and click OK</li>
<li>You should see : <span class="small-code">org.assertj.core.api.Assertions.*</span> in the list of favorites.</li>
</ol>
<p class="list-section">IntelliJ Idea</p>
<ul>
<li>No special configuration, just start typing <span class="small-code">assertThat</span> and then invoke completion (Ctrl-Space) twice.</li>
</ul>
<h3 class="page-header"><span id="describe-assertion"></span><i class="fa fa-star"></i> Describe your assertion with as(String description, Object... args)</h3>
<p>It is often valuable to describe the assertion performed, especially for boolean assertion where the default error message just complains that it got <span class="small-code">false</span> instead of <span class="small-code">true</span> (or vice versa).</p>
<p>You can set such a description with <span class="small-code">as(String description, Object... args)</span> but remember to do it <b>before</b> calling the assertion. Otherwise it is simply ignored as a failing assertion breaks the following chained calls.</p>
<p>Example of a failing assertion with a description : </p>
<pre><code class="java"> TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);
// failing assertion, remember to call as() before the assertion, not after !
assertThat(frodo.getAge()).as("check %s's age", frodo.getName()).isEqualTo(100);</code></pre>
<p> The error message starts with the given description in [] :</p>
<pre><code> [check Frodo's age] expected:<100> but was:<33></code></pre>
<h3 class="page-header"><span id="filters"></span><i class="fa fa-star"></i> Combining filtering and assertions on iterables or arrays</h3>
<p>
Filtering can be done on arrays or iterables. Filter criteria are expressed by :
<ul>
<li>a Java 8 <span class="small-code">Predicate</span></li>
<li>a condition (<span class="small-code">org.assertj.core.api.Condition</span>)</li>
<li>some operation on a property/field of array/iterable elements</li>
</ul>
</p>
<p>Let's see both options in some examples taken from <a href="https://github.com/joel-costigliola/assertj-examples/blob/master/assertions-examples/src/test/java/org/assertj/examples/FilterExamples.java">FilterExamples.java</a> of the <a href="https://github.com/joel-costigliola/assertj-examples/">assertj-examples</a> project.</p>
<p class="list-section">Filtering with a <span class="small-code">Predicate</span></p>
<p>You specify the filter condition using simple predicate, best expressed with a lambda.</p>
<p>Example :</p>
<pre><code class="java">assertThat(fellowshipOfTheRing).filteredOn( character -> character.getName().contains("o") )
.containsOnly(aragorn, frodo, legolas, boromir);</code></pre>
<p class="list-section">Filtering on a property or a field</p>
<p>First you specify the property/field name to filter on and then its expected value. The filter first tries to get the value from a property, then from a field. Reading private fields is supported by default, but can be disabled globally by calling <span class="small-code">Assertions.setAllowExtractingPrivateFields(false)</span>.</p>
<p>Filters support reading nested properties/fields. Note that if an intermediate value is null the whole nested property/field is considered to be null. Thus reading <span class="small-code">"address.street.name"</span> will return null if <span class="small-code">"address.street"</span> is null.</p>
<p>Filters support these basic operations : <span class="small-code">not</span>, <span class="small-code">in</span>, <span class="small-code">notIn</span></p>
<pre><code class="java">import static org.assertj.core.api.Assertions.in;
import static org.assertj.core.api.Assertions.not;
import static org.assertj.core.api.Assertions.notIn;
...
// filters use introspection to get property/field values
assertThat(fellowshipOfTheRing).filteredOn("race", HOBBIT)
.containsOnly(sam, frodo, pippin, merry);
// nested properties are supported
assertThat(fellowshipOfTheRing).filteredOn("race.name", "Man")
.containsOnly(aragorn, boromir);
// you can apply different comparison
assertThat(fellowshipOfTheRing).filteredOn("race", notIn(HOBBIT, MAN))
.containsOnly(gandalf, gimli, legolas);
assertThat(fellowshipOfTheRing).filteredOn("race", in(MAIA, MAN))
.containsOnly(gandalf, boromir, aragorn);
assertThat(fellowshipOfTheRing).filteredOn("race", not(HOBBIT))
.containsOnly(gandalf, boromir, aragorn, gimli, legolas);
// you can chain multiple filter criteria
assertThat(fellowshipOfTheRing).filteredOn("race", MAN)
.filteredOn("name", not("Boromir"))
.containsOnly(aragorn);
</code></pre>
<p class="list-section">Filtering with a <span class="small-code">Condition</span></p>
<p>Filter the iterable/array under test keeping only elements matching the given <a href="assertj-core-conditions.html"><span class="small-code">Condition</span></a>. </p>
<p>Two methods are available : <span class="small-code">being(Condition)</span> and <span class="small-code">having(Condition)</span>. They do the same job - pick the one that makes your code more readable !</p>
<pre><code class="java">import org.assertj.core.api.Condition;
Condition<Player> mvpStats= new Condition<Player>() {
@Override
public boolean matches(Player player) {
return player.pointsPerGame() > 20 && (player.assistsPerGame() >= 8 || player.reboundsPerGame() >= 8);
}
};
List<Player> players;
players.add(rose); // Derrick Rose : 25 ppg - 8 assists - 5 rebounds
players.add(lebron); // Lebron James : 27 ppg - 6 assists - 9 rebounds
players.add(noah); // Joachim Noah : 8 ppg - 5 assists - 11 rebounds
// noah does not have more than 20 ppg
assertThat(players).filteredOn(mvpStats)
.containsOnly(rose, lebron);
</code></pre>
<h3 class="page-header" ><span id="extracted-properties-assertion"></span><i class="fa fa-star"></i> Assertions on extracted properties/fields of iterable/array elements</h3>
<p>Let's say you have queried some service/dao and got a list (or an array) of TolkienCharacters. To check the results you have to build the expected TolkienCharacter(s), which can be a lot of work !</p>
<pre><code class="java">List<TolkienCharacter> fellowshipOfTheRing = tolkienDao.findHeroes(); // frodo, sam, aragorn ...
// requires creation of frodo and aragorn, the expected TolkienCharacters
assertThat(fellowshipOfTheRing).contains(frodo, aragorn);</code></pre>
<p>Instead, it is usually sufficient to only check some fields or properties of the TolkienCharacter results elements.
This easy but you still have to write code to extract the fields/properties before performing your assertions, something like :</p>
<pre><code class="java">// extract the names ...
List<String> names = new ArrayList<String>();
for (TolkienCharacter tolkienCharacter : fellowshipOfTheRing) {
names.add(tolkienCharacter.getName());
}
// ... and finally assert something
assertThat(names).contains("Boromir", "Gandalf", "Frodo", "Legolas");</code></pre>
<p>Hey ! It is too much work to extract fields and/or properties by hand. Let AssertJ help you taking care of that. Here is
how to check the names of the TolkienCharacter elements in the fellowshipOfTheRing list:</p>
<pre><code class="java">// "name" needs to be either a property or a field of the TolkienCharacter class
assertThat(fellowshipOfTheRing).extracting("name")
.contains("Boromir", "Gandalf", "Frodo", "Legolas")
.doesNotContain("Sauron", "Elrond");</code></pre>
<p>But there is more ! You can extract several fields/properties and check them using tuples. As an example, let's check the name, age and race's name of each TolkienCharacter element :</p>
<pre><code class="java">// when checking several properties/fields you have to use tuples :
import static org.assertj.core.api.Assertions.tuple;
// extracting name, age and and race.name nested property
assertThat(fellowshipOfTheRing).extracting("name", "age", "race.name")
.contains(tuple("Boromir", 37, "Man"),
tuple("Sam", 38, "Hobbit"),
tuple("Legolas", 1000, "Elf"));</code></pre>
<p>The extracted name, age and race's name values of the current element are grouped in a tuple, thus you need to use tuples for expected values.</p>
<p>More examples are available in the test method <span class="small-code">iterable_assertions_on_extracted_property_values_example</span> in <a href="https://github.com/joel-costigliola/assertj-examples/blob/master/assertions-examples/src/test/java/org/assertj/examples/IterableAssertionsExamples.java">IterableAssertionsExamples.java</a> of the <a href="https://github.com/joel-costigliola/assertj-examples/">assertj-examples</a> project.</p>
<p>Note that <span class="small-code">extracting</span> one property can be made strongly typed by giving the property type as the second argument.</p>
<pre><code class="java">// to have type safe extracting, use the second parameter to pass the expected property type:
assertThat(fellowshipOfTheRing).extracting("name", String.class)
.contains("Boromir", "Gandalf", "Frodo", "Legolas")
.doesNotContain("Sauron", "Elrond");</code></pre>
<h3 class="page-header" ><span id="flat-extracted-properties-assertion"></span><i class="fa fa-star"></i> Flat(map) extracting </h3>
<p>Flat extracting is hard to explain but easy to understand with an example, so let's see how it works (if you are familiar with functional programming, it's just a <span class="small-code">flatMap</span>).</p>
<p>You have a <span class="small-code">Player</span> with a <span class="small-code">teamMates</span> property returning a <span class="small-code">List<Player></span>, you want to assert that it returns the expected players:</p>
<pre><code class="java">Player jordan = ... // initialized with Pippen and Kukoc team mates
Player magic = ... // initialized with Jabbar and Worthy team mates
List<Player> reallyGoodPlayers = list(jordan, magic);
// check all team mates by specifying the teamMates property (Player has a getTeamMates() method):
assertThat(reallyGoodPlayers).flatExtracting("teamMates")
.contains(pippen, kukoc, jabbar, worthy);
// alternatively, you can implement an Extractor to extract the team mates:
assertThat(reallyGoodPlayers).flatExtracting(teamMates)
.contains(pippen, kukoc, jabbar, worthy);</code></pre>
<p>where <span class="small-code">teamMates</span> is an instance of <span class="small-code">PlayerTeammatesExtractor</span>:</p>
<pre><code class="java">public class PlayerTeammatesExtractor implements Extractor<Player, List<Player>> {
@Override
public List<Player> extract(Player input) {
return input.getTeamMates();
}
}</code></pre>
<h3 class="page-header" ><span id="extracted-method-result-assertion"></span><i class="fa fa-star"></i> Assertions on results of a method call on iterable/array elements</h3>
<p>Like <span class="small-code">extracting</span> but instead of extracting properties/fields, it extracts the result of a given method invocation on the elements of the Iterable/Array under test and puts the results into a new Iterable/Array which becomes the object under test.<br>
It allows you to test the results of a method call on elements instead of testing the elements themselves. It's especially useful for classes that do not conform to Java Bean's getter specification (e.g <span class="small-code">toString()</span> or <span class="small-code">String status()</span> instead of <span class="small-code">String getStatus()</span>).
</p>
<p>Let's take an example to make things clearer :</p>
<pre><code class="java">// WesterosHouse class has a method: public String sayTheWords()
List<WesterosHouse> greatHouses = new ArrayList<WesterosHouse>();
greatHouses.add(new WesterosHouse("Stark", "Winter is Coming"));
greatHouses.add(new WesterosHouse("Lannister", "Hear Me Roar!"));
greatHouses.add(new WesterosHouse("Greyjoy", "We Do Not Sow"));
greatHouses.add(new WesterosHouse("Baratheon", "Our is the Fury"));
greatHouses.add(new WesterosHouse("Martell", "Unbowed, Unbent, Unbroken"));
greatHouses.add(new WesterosHouse("Tyrell", "Growing Strong"));
// let's verify the words of the great houses of Westeros:
assertThat(greatHouses).extractingResultOf("sayTheWords")
.contains("Winter is Coming", "We Do Not Sow", "Hear Me Roar")
.doesNotContain("Lannisters always pay their debts");</code></pre>
<h3 class="page-header"><span id="soft-assertions"></span><i class="fa fa-star"></i> Collect all errors with soft assertions</h3>
<p>Using soft assertions, AssertJ collects all assertion errors instead of stopping at the first one.<br>
So, assuming something goes awry at your dinner party, when using "standard" assertions, this test ...</p>
<pre><code class="java">@Test
public void host_dinner_party_where_nobody_dies() {
Mansion mansion = new Mansion();
mansion.hostPotentiallyMurderousDinnerParty();
assertThat(mansion.guests()).as("Living Guests").isEqualTo(7);
assertThat(mansion.kitchen()).as("Kitchen").isEqualTo("clean");
assertThat(mansion.library()).as("Library").isEqualTo("clean");
assertThat(mansion.revolverAmmo()).as("Revolver Ammo").isEqualTo(6);
assertThat(mansion.candlestick()).as("Candlestick").isEqualTo("pristine");
assertThat(mansion.colonel()).as("Colonel").isEqualTo("well kempt");
assertThat(mansion.professor()).as("Professor").isEqualTo("well kempt");
} </code></pre>
<p>... will yield the less-than-ideal exception message :<br>
<pre><code class="diff">org.junit.ComparisonFailure: [Living Guests] expected:<[7]> but was<[6]></code></pre>
<p>Using soft assertions you can collect all failed assertions:</p>
<pre><code class="java">@Test
public void host_dinner_party_where_nobody_dies() {
Mansion mansion = new Mansion();
mansion.hostPotentiallyMurderousDinnerParty();
// use SoftAssertions instead of direct assertThat methods
SoftAssertions softly = new SoftAssertions();
softly.assertThat(mansion.guests()).as("Living Guests").isEqualTo(7);
softly.assertThat(mansion.kitchen()).as("Kitchen").isEqualTo("clean");
softly.assertThat(mansion.library()).as("Library").isEqualTo("clean");
softly.assertThat(mansion.revolverAmmo()).as("Revolver Ammo").isEqualTo(6);
softly.assertThat(mansion.candlestick()).as("Candlestick").isEqualTo("pristine");
softly.assertThat(mansion.colonel()).as("Colonel").isEqualTo("well kempt");
softly.assertThat(mansion.professor()).as("Professor").isEqualTo("well kempt");
// Don't forget to call SoftAssertions global verification !
softly.assertAll();
}</code></pre>
<p>When the collected assertions are all asserted together they yield a more descriptive error message:</p>
<pre><code class="diff">org.assertj.core.api.SoftAssertionError:
The following 4 assertions failed:
1) [Living Guests] expected:<[7]> but was:<[6]>
2) [Library] expected:<'[clean]'> but was:<'[messy]'>
3) [Candlestick] expected:<'[pristine]'> but was:<'[bent]'>
4) [Professor] expected:<'[well kempt]'> but was:<'[bloodied and dishevelled]'></code></pre>
<p>AssertJ also provides a few ways to avoid having to call <span class="small-code">softly.assertAll()</span> manually:</p>
<ul>
<li><a href="#JUnitSoftAssertions"><span class="small-code">JUnitSoftAssertions</span> with a JUnit rule</a></li>
<li><a href="#AutoCloseableSoftAssertions"><span class="small-code">AutoCloseableSoftAssertions</span> </a></li>
<li><a href="#assertSoftly">Using the static <span class="small-code">assertSoftly</span> method</a></li>
</ul>
<p><span class="small-code">JUnitSoftAssertions</span> example:</p>
<span id="JUnitSoftAssertions"></span><pre><code class="java">@Rule
public final JUnitSoftAssertions softly = new JUnitSoftAssertions();
@Test
public void host_dinner_party_where_nobody_dies() {
Mansion mansion = new Mansion();
mansion.hostPotentiallyMurderousDinnerParty();
// use SoftAssertions instead of direct assertThat methods
softly.assertThat(mansion.guests()).as("Living Guests").isEqualTo(7);
softly.assertThat(mansion.kitchen()).as("Kitchen").isEqualTo("clean");
softly.assertThat(mansion.library()).as("Library").isEqualTo("clean");
softly.assertThat(mansion.revolverAmmo()).as("Revolver Ammo").isEqualTo(6);
softly.assertThat(mansion.candlestick()).as("Candlestick").isEqualTo("pristine");
softly.assertThat(mansion.colonel()).as("Colonel").isEqualTo("well kempt");
softly.assertThat(mansion.professor()).as("Professor").isEqualTo("well kempt");
// No need to call softly.assertAll(), it is automatically done by JUnitSoftAssertions rule
}</code></pre>
<p><span class="small-code">AutoCloseableSoftAssertions</span> example:</p>
<span id="AutoCloseableSoftAssertions"></span><pre><code class="java">@Test
public void host_dinner_party_where_nobody_dies() {
Mansion mansion = new Mansion();
mansion.hostPotentiallyMurderousDinnerParty();
try (AutoCloseableSoftAssertions softly = new AutoCloseableSoftAssertions()) {
softly.assertThat(mansion.guests()).as("Living Guests").isEqualTo(7);
softly.assertThat(mansion.kitchen()).as("Kitchen").isEqualTo("clean");
softly.assertThat(mansion.library()).as("Library").isEqualTo("clean");
softly.assertThat(mansion.revolverAmmo()).as("Revolver Ammo").isEqualTo(6);
softly.assertThat(mansion.candlestick()).as("Candlestick").isEqualTo("pristine");
softly.assertThat(mansion.colonel()).as("Colonel").isEqualTo("well kempt");
softly.assertThat(mansion.professor()).as("Professor").isEqualTo("well kempt");
// no need to call assertAll, it is done when softly is closed.
}
}</code></pre>
<p><span class="small-code">assertSoftly</span> example:</p>
<span id="assertSoftly"></span><pre><code class="java">@Test
public void host_dinner_party_where_nobody_dies() {
Mansion mansion = new Mansion();
mansion.hostPotentiallyMurderousDinnerParty();
SoftAssertions.assertSoftly(softly -> {
softly.assertThat(mansion.guests()).as("Living Guests").isEqualTo(7);
softly.assertThat(mansion.kitchen()).as("Kitchen").isEqualTo("clean");
softly.assertThat(mansion.library()).as("Library").isEqualTo("clean");
softly.assertThat(mansion.revolverAmmo()).as("Revolver Ammo").isEqualTo(6);
softly.assertThat(mansion.candlestick()).as("Candlestick").isEqualTo("pristine");
softly.assertThat(mansion.colonel()).as("Colonel").isEqualTo("well kempt");
softly.assertThat(mansion.professor()).as("Professor").isEqualTo("well kempt");
// no need to call assertAll, it is done by assertSoftly.
});
}</code></pre>
<p>Note that in TestNG it is not possible to make the global verification in an <span class="small-code">@AfterMethod</span> method because if it throws an exception, TestNG skips all subsequent tests.</p>
<h3 class="page-header"><span id="file-content-string-assertions"></span><i class="fa fa-star"></i> Using String assertions on the content of a file</h3>
<p>File assertions are rather poor for checking the file content, so we had the idea to reuse AssertJ String assertions on the content of a file.<br>
See the example below :</p>
<pre><code class="java">File xFile = writeFile("xFile", "The Truth Is Out There");
// classic File assertions
assertThat(xFile).exists().isFile().isRelative();
// String assertions on the file content : contentOf() comes from Assertions.contentOf static import
assertThat(contentOf(xFile)).startsWith("The Truth").contains("Is Out").endsWith("There");</code></pre>
<p>Note that this is meant to be used with small files only, as the whole content is loaded into memory.</p>
<h3 class="page-header"><span id="exception-assertion"></span><i class="fa fa-star"></i> Exception assertions guide</h3>
<p>How to assert that an exception has been thrown and check that it is the expected one ?</p>
<p class="list-section">With Java 8 (AssertJ 3.x) :</p>
<p>Testing assertions in Java 8 is elegant, use <span class="small-code">assertThatThrownBy(ThrowingCallable)</span> to capture and then assert on a <span class="small-code">Throwable</span>, <span class="small-code">ThrowingCallable</span> being a functional interface it can be expressed by a lambda.</p>
<p>Example :</p>
<pre><code class="java">@Test
public void testException() {
assertThatThrownBy(() -> { throw new Exception("boom!"); }).isInstanceOf(Exception.class)
.hasMessageContaining("boom");
}</code></pre>
<p>An alternative syntax is provided as some people find it more natural :</p>
<pre><code class="java">@Test
public void testException() {
assertThatExceptionOfType(IOException.class).isThrownBy(() -> { throw new IOException("boom!"); })
.withMessage("%s!", "boom")
.withMessageContaining("boom")
.withNoCause();
}</code></pre>
<p>This later syntax has been enriched for common exceptions :</p>
<ul>
<li><span class="small-code">assertThatNullPointerException</span></li>
<li><span class="small-code">assertThatIllegalArgumentException</span></li>
<li><span class="small-code">assertThatIllegalStateException</span></li>
<li><span class="small-code">assertThatIOException</span></li>
</ul>
<p>The previous test can be rewritten as:</p>
<pre><code class="java">@Test
public void testException() {
assertThatIOException().isThrownBy(() -> { throw new IOException("boom!"); })
.withMessage("%s!", "boom")
.withMessageContaining("boom")
.withNoCause();
}</code></pre>
<p>You can test that a piece of code does not throw any exception:</p>
<pre><code class="java">assertThatCode(() -> {
// code that should throw an exception
...
}).doesNotThrowAnyException();
</code></pre>
<p>Finally, BDD aficionados can separate <i>when</i> and <i>then</i> steps by using <span class="small-code">catchThrowable(ThrowingCallable)</span> to capture the throwable and then perform assertions.</p>
<p>Example :</p>
<pre><code class="java">@Test
public void testException() {
// given some preconditions
// when
Throwable thrown = catchThrowable(() -> { throw new Exception("boom!"); });
// then
assertThat(thrown).isInstanceOf(Exception.class)
.hasMessageContaining("boom");
}</code></pre>
<p class="list-section">With Java 7 (AssertJ 2.x) :</p>
<p>Asserting on exceptions is not as nice compared to the Java 8 way, this is how you would do it in AssertJ 2.x :</p>
<ol>
<li>Put the code to should throw in a try-catch.</li>
<li>Call <span class="small-code">fail</span> method immediately after the code that should throw the exception, so that if it is not thrown, the test fails.</li>
<li>Make assertions on the caught exception</li>
</ol>
<p>Note that <span class="small-code">fail</span> method can be statically imported from <span class="small-code">Assertions</span> class</p>
<p>Example taken from <a href="https://github.com/joel-costigliola/assertj-examples/blob/master/assertions-examples/src/test/java/org/assertj/examples/FailUsageExamples.java">FailUsageExamples.java</a> in <a href="https://github.com/joel-costigliola/assertj-examples/">assertj-examples</a>.</p>
<pre><code class="java">import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;
// ... code omitted for brevety
assertThat(fellowshipOfTheRing).hasSize(9);
// here's the typical pattern to use Fail :
try {
fellowshipOfTheRing.get(9); // argggl !
// we should not arrive here => use fail to expresses that
// if IndexOutOfBoundsException was not thrown, test would fail the specified message
fail("IndexOutOfBoundsException expected because fellowshipOfTheRing has only 9 elements");
} catch (IndexOutOfBoundsException e) {
assertThat(e).hasMessage("Index: 9, Size: 9");
}
// Warning : don't catch Throwable as it would also catch the AssertionError thrown by fail method
// another way to do the same thing
try {
fellowshipOfTheRing.get(9); // argggl !
// if IndexOutOfBoundsException was not thrown, test would fail with message :
// "Expected IndexOutOfBoundsException to be thrown"
failBecauseExceptionWasNotThrown(IndexOutOfBoundsException.class);
} catch (IndexOutOfBoundsException e) {
assertThat(e).hasMessage("Index: 9, Size: 9");
}</code></pre>
<h3 class="page-header"><span id="custom-comparison-strategy"></span><i class="fa fa-star"></i> Using a custom comparison strategy in assertions</h3>
<p>Sometime you want to compare objects with a strategy not relying on the <span class="small-code">equals</span> method, this is possible in AssertJ thanks to two methods :
<ul>
<li><span class="small-code">usingComparator(Comparator)</span> : concerns object under assertion</li>
<li><span class="small-code">usingElementComparator(Comparator)</span> : concerns elements of iterable/array under assertion</li>
</ul>
</p>
<p><span class="small-code">usingComparator(Comparator)</span> example :</p>
<pre><code class="java">// frodo and sam are instances of TolkienCharacter with Hobbit race (obviously :)), they are not equal ...
assertThat(frodo).isNotEqualTo(sam);
// ... but if we compare race only, they are (raceComparator implements Comparator<TolkienCharacter>)
assertThat(frodo).usingComparator(raceComparator).isEqualTo(sam);</code></pre>
<p><span class="small-code">usingElementComparator(Comparator)</span> example :</p>
<pre><code class="java">// standard comparison : the fellowshipOfTheRing includes Gandalf but not Sauron (believe me) ...
assertThat(fellowshipOfTheRing).contains(gandalf).doesNotContain(sauron);
// ... but if we compare race only, Sauron is in fellowshipOfTheRing (he's a Maia like Gandalf)
assertThat(fellowshipOfTheRing).usingElementComparator(raceComparator).contains(sauron);</code></pre>
<h3 class="page-header"><span id="field-by-field-comparison"></span><i class="fa fa-star"></i> Field by field comparisons</h3>
<p>This is a special case of <a href="#custom-comparison-strategy">custom comparison</a> where objects are compared "by value", the comparison is performed on all fields/properties, several variants are provided :
<ul>
<li><a href="#field-by-field"><span class="small-code">isEqualToComparingFieldByField</span></a> : compares all fields/properties including inherited ones - not recursive</li>
<li><a href="#field-by-field-only"><span class="small-code">isEqualToComparingOnlyGivenFields</span></a> : compares only the specified fields/properties - not recursive</li>
<li><a href="#field-by-field-ignoring"><span class="small-code">isEqualToIgnoringGivenFields</span></a> : compares all fields/properties except specified ones - not recursive</li>
<li><a href="#field-by-field-null"><span class="small-code">isEqualToIgnoringNullFields</span></a> : compares non null fields/properties only - not recursive</li>
<li><a href="#field-by-field-recursive"><span class="small-code">isEqualToComparingFieldByFieldRecursively</span></a> : compares all fields/properties recursively</li>
</ul>
</p>
<p>Except <span class="small-code">isEqualToComparingFieldByFieldRecursively</span>, the comparison performed is not recursive, i.e. if one of the field is an <span class="small-code">Object</span>, it will be compared to the other field using its <span class="small-code">equals</span> method (whether <span class="small-code">equals</span> has been overriden or not). On the other hand <span class="small-code">isEqualToComparingFieldByFieldRecursively</span> compares <span class="small-code">Object</span> fields with a field by field strategy unless it has a custom <span class="small-code">equals</span> implementation (i.e. the overriden <span class="small-code">equals</span> method will be used instead of a field by field comparison).</p>
<p>You can specify a custom comparison strategy by <a href="assertj-core-news.html#assertj-core-2.4.0-usingComparatorForType">field type</a> or for a given <a href="assertj-core-news.html#assertj-core-2.4.0-usingComparatorForFields">group of fields</a>, this is useful when comparing doubles or floats as shown at the end of <span class="small-code">isEqualToComparingFieldByFieldRecursively</span> <a href="#field-by-field-recursive">example</a>.</p>
<p><u>Examples :</u></p>
<p>In the following examples, the <span class="small-code">TolkienCharacter</span> class has getters but its <span class="small-code">equals</span> method has not been overridden.</p>
<p><span id="field-by-field" class="small-code">isEqualToComparingFieldByField</span> :</p>
<pre><code class="java">TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);
TolkienCharacter frodoClone = new TolkienCharacter("Frodo", 33, HOBBIT);
// Fail as equals compares object references
assertThat(frodo).isEqualsTo(frodoClone);
// frodo and frodoClone are equal when doing a field by field comparison.
assertThat(frodo).isEqualToComparingFieldByField(frodoClone);</code></pre>
<p><span id="field-by-field-only" class="small-code">isEqualToComparingOnlyGivenFields</span> :</p>
<pre><code class="java">TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);
TolkienCharacter sam = new TolkienCharacter("Sam", 38, HOBBIT);
// frodo and sam both are hobbits, so they are equal when comparing only race
assertThat(frodo).isEqualToComparingOnlyGivenFields(sam, "race"); // OK
// they are also equals when comparing only race name (nested field).
assertThat(frodo).isEqualToComparingOnlyGivenFields(sam, "race.name"); // OK
// ... but not when comparing both name and race
assertThat(frodo).isEqualToComparingOnlyGivenFields(sam, "name", "race"); // FAIL</code></pre>
<p><span id="field-by-field-ignoring" class="small-code">isEqualToIgnoringGivenFields</span> :</p>
<pre><code class="java">TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);
TolkienCharacter sam = new TolkienCharacter("Sam", 38, HOBBIT);
// frodo and sam are equal when ignoring name and age as the only remaining field is race
assertThat(frodo).isEqualToIgnoringGivenFields(sam, "name", "age"); // OK both are HOBBIT
// ... but they are not equals if only age is ignored as their names differ.
assertThat(frodo).isEqualToIgnoringGivenFields(sam, "age"); // FAIL</code></pre>
<p><span id="field-by-field-null" class="small-code">isEqualToIgnoringNullFields</span> :</p>
<pre><code class="java">TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);
TolkienCharacter mysteriousHobbit = new TolkienCharacter(null, 33, HOBBIT);
// Null fields in expected object are ignored, mysteriousHobbit has a null name thus it's ignored
assertThat(frodo).isEqualToIgnoringNullFields(mysteriousHobbit); // OK
// ... but this is not reversible !
assertThat(mysteriousHobbit).isEqualToIgnoringNullFields(frodo); // FAIL</code></pre>
<p><span id="field-by-field-recursive" class="small-code">isEqualToComparingFieldByFieldRecursively</span> :</p>
<pre><code class="java">public class Person {
public String name;
public double height;
public Home home = new Home();
public Person bestFriend;
// constructor with name and height omitted for brevity's sake
}
public class Home {
public Address address = new Address();
}
public static class Address {
public int number = 1;
}
Person jack = new Person("Jack", 1.80);
jack.home.address.number = 123;
Person jackClone = new Person("Jack", 1.80);
jackClone.home.address.number = 123;
// cycle are handled in comparison
jack.bestFriend = jackClone;
jackClone.bestFriend = jack;
// will fail as equals compares object references
assertThat(jack).isEqualsTo(jackClone);
// jack and jackClone are equal when doing a recursive field by field comparison
assertThat(jack).isEqualToComparingFieldByFieldRecursively(jackClone);
// any type/field can be compared with a a specific comparator.
// let's change jack's height a little bit
jack.height = 1.81;
// assertion fails because of the height difference
// (the default precision comparison for double is 1.0E-15)
assertThat(jack).isEqualToComparingFieldByFieldRecursively(jackClone);
// use usingComparatorForType to specify how to compare the given type
// assertion succeeds because we allow a 0.5 tolerance on double
assertThat(jack).usingComparatorForType(new DoubleComparator(0.5), Double.class)
.isEqualToComparingFieldByFieldRecursively(jackClone);
// use usingComparatorForFields to specify how to compare some fields (nested fields are supported)
assertThat(jack).usingComparatorForFields(new DoubleComparator(0.5), "height")
.isEqualToComparingFieldByFieldRecursively(jackClone);</code></pre>
<h3 class="page-header"><span id="custom-representation"></span><i class="fa fa-star"></i> Using a custom
representation in assertions</h3>
<p>
Assertions error messages use a <span class="small-code">Representation</span> to format different types
involved.
There are multiple ways of registering a custom representation for assertions:
</p>
<ul>
<li>
global scope (default on startup): Since 2.9.0 / 3.9.0, one can register an implementation of <span class="small-code">Representation</span>
via a Service Provider Interface (SPI). This will cause AssertJ to use that assertion per default all the time.
There won't be a need to call <span class="small-code">Assertions.useRepresentation(myRepresentation)</span>.
And calling <span class="small-code">Assertions.useDefaultRepresentation()</span> will actually use the SPI registered <span class="small-code">Representation</span>
</li>
<li>
global scope (after calling): <span class="small-code">Assertions.useRepresentation(myRepresentation)</span>
- After this call AssertJ will use the implemented <span class="small-code">myRepresentation</span> globally
</li>
<li>
per assertion scope: <span class="small-code">assertThat(actual).withRepresentation(myRepresentation)</span>
- This will cause AssertJ to use to passed representation only during the scope of that particular assertion
</li>
</ul>
<p>
Examples:
</p>
<pre><code class="java">private class Example {} // dummy class
public class CustomRepresentation extends StandardRepresentation {
// override needed to hook non predefined type formatting
@Override
public String fallbackToStringOf(Object o) {
if (o instanceof Example) return "Example";
// fallback to default formatting.
return super.fallbackToStringOf(o);
}
// override a predefined type formatting : String
@Override
protected String toStringOf(String str) {
return "$" + str + "$";
}
}</code></pre>
<p>Global scope custom representation (default on startup) :</p>
<p>
You will need to register your <span class="small-code">Representation</span> as an SPI. You need to do the following for that:
</p>
<ul>
<li>
Create a file named <span class="small-code">org.assertj.core.presentation.Representation</span>
in the <span class="small-code">META-INF/services</span> directory
</li>
<li>
Put the fully qualified class name of your <span class="small-code">Representation</span> in it
</li>
<li>
Make sure <span class="small-code">META-INF/services/org.assertj.core.presentation.Representation</span>
is in the runtime classpath, usually putting it in <span class="small-code">src/test/resources</span> is enough
</li>
<li>
We recommend that you extend from the <span class="small-code">StandardRepresentation</span> and override the
<span class="small-code">fallbackToStringOf(Object)</span> method. By doing this all the defaults of AssertJ
would be applied and you can apply your own customization in there.
</li>
</ul>
<pre><code class="java">//You don't need to do anything, AssertJ will pick up the Representation automatically
// this assertion fails ...
assertThat(new Example()).isNull();
// ... with error :
expected:<[null]> but was:<[Example]>
// this one fails ...
assertThat("foo").startsWith("bar");
// ... with error :
Expecting:
<$foo$>
to start with:
<$bar$></code></pre>
<p>Global scope custom representation (after call) :</p>
<pre><code class="java">// register CustomRepresentation only once. However, all tests before calling this would use the default one
Assertions.useRepresentation(new CustomRepresentation());
// this assertion fails ...
assertThat(new Example()).isNull();
// ... with error :
expected:<[null]> but was:<[Example]>
// this one fails ...
assertThat("foo").startsWith("bar");
// ... with error :
Expecting:
<$foo$>
to start with:
<$bar$></code></pre>
<p>Per assertion scope custom representation :</p>
<pre><code class="java">// we need to register CustomRepresentation for each assertions
Representation customRepresentation = new CustomRepresentation();
// this assertion fails ...
assertThat(new Example()).withRepresentation(customRepresentation)
.isNull();
// ... with error :
expected:<[null]> but was:<[Example]>
// this one fails ...
assertThat("foo").withRepresentation(customRepresentation)
.startsWith("bar");
// ... with error :
Expecting:
<$foo$>
to start with:
<$bar$></code></pre>
</div>
</div>
</div>
<br>
<!--
<div class="container">
<footer>
<div class="row">
<div class="col-lg-12">
<p>AssertJ - Licensed under the Apache License, Version 2.0.</p>
</div>
</div>
</footer>
</div>
-->
<script src="js/jquery-1.10.2.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/modern-business.js"></script>
<script src="js/assertj.js"></script>
</body>
</html>