SlideShare a Scribd company logo
AssertJ
Quick introduction
What is it?
Library to simplify assertions in tests
Forked from fest-assert: actively maintained
Focus on improving readability through its fluent API: IDE friendly
How to use?
Add Maven dependency (already on parent/pom.xml):
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.2.0</version> <!-- Not needed on common-uber sub-projects -->
<scope>test</scope> <!-- Not needed on common-uber sub-projects -->
</dependency>
Add static import to Eclipse:
1. Go to : Preferences > Java > Editor > Content assist > Favorites > New Type
2. Enter : org.assertj.core.api.Assertions
3. You should see : org.assertj.core.api.Assertions.* in the list.
Simple assertions
// AssertJ
Assertions.assertThat(retrievedStore)
.isNotNull();
Assertions.assertThat(retrievedStore.name)
.isEqualTo(dbStore.getName());
Assertions.assertThat(retrievedStore.isMobileOptimized)
.isTrue();
Assertions.assertThat(detailReport.getEntries())
.as("Detail report %s entries", countryCode)
.isNotNull().hasSize(5);
// Hamcrest
MatcherAssert.assertThat(retrievedStore,
Matchers.is(Matchers.notNullValue()));
MatcherAssert.assertThat(retrievedStore.name,
Matchers.equalTo(dbStore.getName()));
MatcherAssert.assertThat(retrievedStore.isMobileOptimized,
Matchers.is(true));
MatcherAssert.assertThat(detailReport.getEntries(),
Matchers.is(Matchers.notNullValue()));
MatcherAssert.assertThat(detailReport.getEntries(),
Matchers.hasSize(5));
Friendly and comprehensive error messages
// AssertJ - Strings comparison
Assertions.assertThat("The quick brown fox jump over the
lazy dog").isEqualTo("The quick brown fox jumps over the
lazy dog");
expected:<...quick brown fox jump[s] over the lazy dog"> but
was:<...quick brown fox jump[] over the lazy dog">
// Hamcrest - Strings comparison
MatcherAssert.assertThat("The quick brown fox jump over the
lazy dog", Matchers.equalTo("The quick brown fox jumps over
the lazy dog"));
Expected: "The quick brown fox jumps over the lazy dog"
but: was "The quick brown fox jump over the lazy dog"
// Hamcrest - List elements comparison
MatcherAssert.assertThat(Arrays.asList(1, 2, 3, 4, 5),
Matchers.hasItems(5, 7));
Expected: (a collection containing <5> and a collection
containing <7>)
but: a collection containing <7> mismatches were: [was
<1>, was <2>, was <3>, was <4>, was <5>]
// AssertJ - List elements comparison
Assertions.assertThat(Arrays.asList(1, 2, 3, 4,
5)).contains(5, 7);
Expecting:
<[1, 2, 3, 4, 5]>
to contain:
<[5, 7]>
but could not find:
<[7]>
Filtering and assertions on iterables or arrays
// AssertJ
// Filter uses introspection to get property/field value
Assertions.assertThat(fellowshipOfTheRing)
.filteredOn("race", HOBBIT)
.containsOnly(sam, frodo, pippin, merry);
// Nested properties are supported
Assertions.assertThat(fellowshipOfTheRing)
.filteredOn("race.name", "Man")
.containsOnly(aragorn, boromir);
// Chaining multiple filter criteria
Assertions.assertThat(fellowshipOfTheRing)
.filteredOn("race", MAN)
.filteredOn("name", not("Boromir"))
.containsOnly(aragorn);
// Hamcrest
// Not even fair… you have to do it manually =/
List<TolkienCharacter> fellowshipHobbits =
fellowshipOfTheRing.stream()
.filter(c -> c.getRace().equals(Race.HOBBIT))
.collect(Collectors.toList());
MatcherAssert.assertThat(fellowshipHobbits,
Matchers.contains(sam, frodo, pippin, merry));
// No containsOnly
Filtering and assertions on iterables or arrays (cont.)
// AssertJ
// WesterosHouse class has a method: public String sayTheWords()
List<WesterosHouse> greatHouses = new ArrayList<>();
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 great houses in Westeros:
Assertions.assertThat(greatHouses).extractingResultOf("sayTheWords")
.contains("Winter is Coming", "We Do Not Sow", "Hear Me Roar!")
.doesNotContain("Lannisters always pay their debts");
Friendly exceptions/throwables testing
// Hamcrest
// Given
Long inexistentStoreId = 999L;
try {
// When
this.repository.retrieve(inexistentStoreId);
Assert.fail();
}
catch (NoSuchElementException e) {
// Then
assertThat(e.getMessage(),
containsString("Store ID '999' does not exist"));
}
// AssertJ
// Given
Long inexistentStoreId = 999L;
// When - Then
assertThatThrownBy(() -> repository.retrieve(inexistentStoreId))
.isInstanceOf(NoSuchElementException.class)
.hasMessageContaining("Store ID '999' does not exist");
Java 8 Support: Time API
// AssertJ
LocalDate firstOfJanuary2000 =
LocalDate.parse("2000-01-01");
// AssertJ converts String parameters to LocalDate
// to ease writing expected LocalDate
Assertions.assertThat(firstOfJanuary2000)
.isEqualTo("2000-01-01");
Assertions.assertThat(firstOfJanuary2000)
.isAfter("1999-12-31")
.isAfterOrEqualTo("1999-12-31")
.isAfterOrEqualTo("2000-01-01");
// Hamcrest - using third-party extension:
// org.exparity:hamcrest-date
LocalDate firstOfJanuary2000 =
LocalDate.parse("2000-01-01");
MatcherAssert.assertThat(firstOfJanuary2000,
Matchers.equalTo(LocalDate.parse("2000-01-01")));
MatcherAssert.assertThat(firstOfJanuary2000,
LocalDateMatchers.after(
LocalDate.parse("1999-12-31")));
// No afterOrEqual matcher
Java 8 Support: Optionals
// AssertJ
// optional with value
Optional<String> optional = Optional.of("Test");
Assertions.assertThat(optional)
.isPresent().contains("Test");
// empty optional
Optional<Object> emptyOptional = Optional.empty();
Assertions.assertThat(emptyOptional).isEmpty();
// Hamcrest
// optional with value
Optional<String> optional = Optional.of("Test");
MatcherAssert.assertThat(optional.isPresent(),
Matchers.is(true));
MatcherAssert.assertThat(optional.get(),
Matchers.equalTo("Test"));
// empty optional
Optional<Object> emptyOptional = Optional.empty();
MatcherAssert.assertThat(emptyOptional,
Matchers.equalTo(Optional.<Object> empty()));
Other features
Assertions on extracted fields/properties
extracts properties from iterable elements for assertions
Soft assertions
collect all assertions instead of stopping at the first one
String assertions on file contents
no need to manually read the file (useful for small files)
Flat(map) extracting
flatten a collection by extracting a field from it
Questions?
Thanks!

More Related Content

What's hot

ApacheCon: Abdera A Java Atom Pub Implementation
ApacheCon: Abdera A Java Atom Pub ImplementationApacheCon: Abdera A Java Atom Pub Implementation
ApacheCon: Abdera A Java Atom Pub Implementation
David Calavera
 
Programming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorialProgramming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorial
Jeff Smith
 
for this particular program how do i create the input innotepad 1st ? #includ...
for this particular program how do i create the input innotepad 1st ? #includ...for this particular program how do i create the input innotepad 1st ? #includ...
for this particular program how do i create the input innotepad 1st ? #includ...
hwbloom59
 
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalksSelenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Lohika_Odessa_TechTalks
 
Unit testing with PHPUnit
Unit testing with PHPUnitUnit testing with PHPUnit
Unit testing with PHPUnit
ferca_sl
 

What's hot (20)

Java 8: the good, the bad and the ugly (JBCNConf 2017)
Java 8: the good, the bad and the ugly (JBCNConf 2017)Java 8: the good, the bad and the ugly (JBCNConf 2017)
Java 8: the good, the bad and the ugly (JBCNConf 2017)
 
Testing My Patience
Testing My PatienceTesting My Patience
Testing My Patience
 
Java 8: the good, the bad and the ugly (Oracle Code Brussels 2017)
Java 8: the good, the bad and the ugly (Oracle Code Brussels 2017)Java 8: the good, the bad and the ugly (Oracle Code Brussels 2017)
Java 8: the good, the bad and the ugly (Oracle Code Brussels 2017)
 
Easy REST APIs with Jersey and RestyGWT
Easy REST APIs with Jersey and RestyGWTEasy REST APIs with Jersey and RestyGWT
Easy REST APIs with Jersey and RestyGWT
 
Unlock The Mystery Of PHPUnit (Wave PHP 2018)
Unlock The Mystery Of PHPUnit (Wave PHP 2018)Unlock The Mystery Of PHPUnit (Wave PHP 2018)
Unlock The Mystery Of PHPUnit (Wave PHP 2018)
 
Unit Testing Lots of Perl
Unit Testing Lots of PerlUnit Testing Lots of Perl
Unit Testing Lots of Perl
 
Crushing React bugs with Jest and Enzyme
Crushing React bugs with Jest and EnzymeCrushing React bugs with Jest and Enzyme
Crushing React bugs with Jest and Enzyme
 
Effective Benchmarks
Effective BenchmarksEffective Benchmarks
Effective Benchmarks
 
First glance at Akka 2.0
First glance at Akka 2.0First glance at Akka 2.0
First glance at Akka 2.0
 
State of the CFEngine 2018
State of the CFEngine 2018State of the CFEngine 2018
State of the CFEngine 2018
 
ApacheCon: Abdera A Java Atom Pub Implementation
ApacheCon: Abdera A Java Atom Pub ImplementationApacheCon: Abdera A Java Atom Pub Implementation
ApacheCon: Abdera A Java Atom Pub Implementation
 
Develop and Deploy your JavaEE micro service in less than 5 minutes with Apac...
Develop and Deploy your JavaEE micro service in less than 5 minutes with Apac...Develop and Deploy your JavaEE micro service in less than 5 minutes with Apac...
Develop and Deploy your JavaEE micro service in less than 5 minutes with Apac...
 
Java(8) The Good, The Bad and the Ugly
Java(8) The Good, The Bad and the UglyJava(8) The Good, The Bad and the Ugly
Java(8) The Good, The Bad and the Ugly
 
Programming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorialProgramming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorial
 
Client server part 12
Client server part 12Client server part 12
Client server part 12
 
JavaScript Classes and Inheritance
JavaScript Classes and InheritanceJavaScript Classes and Inheritance
JavaScript Classes and Inheritance
 
for this particular program how do i create the input innotepad 1st ? #includ...
for this particular program how do i create the input innotepad 1st ? #includ...for this particular program how do i create the input innotepad 1st ? #includ...
for this particular program how do i create the input innotepad 1st ? #includ...
 
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalksSelenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
 
Workshop quality assurance for php projects - phpbelfast
Workshop quality assurance for php projects - phpbelfastWorkshop quality assurance for php projects - phpbelfast
Workshop quality assurance for php projects - phpbelfast
 
Unit testing with PHPUnit
Unit testing with PHPUnitUnit testing with PHPUnit
Unit testing with PHPUnit
 

Viewers also liked

Assertj-core
Assertj-coreAssertj-core
Assertj-core
fbenault
 
Senay Johnson Portfolio V2
Senay Johnson Portfolio V2Senay Johnson Portfolio V2
Senay Johnson Portfolio V2
SenayJohnson
 
Simple present tense
Simple present tenseSimple present tense
Simple present tense
CELe CUI
 
Koc 3402 nota 1 face to face ke-2
Koc 3402   nota 1 face to face ke-2Koc 3402   nota 1 face to face ke-2
Koc 3402 nota 1 face to face ke-2
Agga Rock
 

Viewers also liked (16)

Assertj-core
Assertj-coreAssertj-core
Assertj-core
 
JUnit & AssertJ
JUnit & AssertJJUnit & AssertJ
JUnit & AssertJ
 
Clean Unit Test Patterns
Clean Unit Test PatternsClean Unit Test Patterns
Clean Unit Test Patterns
 
Showdown of the Asserts by Philipp Krenn
Showdown of the Asserts by Philipp KrennShowdown of the Asserts by Philipp Krenn
Showdown of the Asserts by Philipp Krenn
 
Senay Johnson Portfolio V2
Senay Johnson Portfolio V2Senay Johnson Portfolio V2
Senay Johnson Portfolio V2
 
Press Kit Solo show Younes Baba Ali
Press Kit Solo show Younes Baba AliPress Kit Solo show Younes Baba Ali
Press Kit Solo show Younes Baba Ali
 
Sabrina Amrani Abstraction Contained En
Sabrina Amrani Abstraction Contained EnSabrina Amrani Abstraction Contained En
Sabrina Amrani Abstraction Contained En
 
\'Dissident\' - Ubik solo show- Press kit
\'Dissident\' - Ubik solo show- Press kit\'Dissident\' - Ubik solo show- Press kit
\'Dissident\' - Ubik solo show- Press kit
 
#wlearn - Enterprise Peer-to-Peer Learning Platform
#wlearn - Enterprise Peer-to-Peer Learning Platform#wlearn - Enterprise Peer-to-Peer Learning Platform
#wlearn - Enterprise Peer-to-Peer Learning Platform
 
Sabrina Amrani Press Kit Zoulikha Bouabdellah Show
Sabrina Amrani Press Kit Zoulikha Bouabdellah ShowSabrina Amrani Press Kit Zoulikha Bouabdellah Show
Sabrina Amrani Press Kit Zoulikha Bouabdellah Show
 
Solo Show Elvire Bonduelle - Gallery Sabrina Amrani
Solo Show Elvire Bonduelle - Gallery Sabrina AmraniSolo Show Elvire Bonduelle - Gallery Sabrina Amrani
Solo Show Elvire Bonduelle - Gallery Sabrina Amrani
 
Property based-testing
Property based-testingProperty based-testing
Property based-testing
 
DéJa Vu
DéJa VuDéJa Vu
DéJa Vu
 
Simple present tense
Simple present tenseSimple present tense
Simple present tense
 
Koc 3402 nota 1 face to face ke-2
Koc 3402   nota 1 face to face ke-2Koc 3402   nota 1 face to face ke-2
Koc 3402 nota 1 face to face ke-2
 
Clase
ClaseClase
Clase
 

Similar to AssertJ quick introduction

international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitinternational PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
smueller_sandsmedia
 
Class loader basic
Class loader basicClass loader basic
Class loader basic
명철 강
 
Unit Testing using PHPUnit
Unit Testing using  PHPUnitUnit Testing using  PHPUnit
Unit Testing using PHPUnit
varuntaliyan
 
Aura Project for PHP
Aura Project for PHPAura Project for PHP
Aura Project for PHP
Hari K T
 
Lambda functions in java 8
Lambda functions in java 8Lambda functions in java 8
Lambda functions in java 8
James Brown
 
Creating and Maintaining WordPress Plugins
Creating and Maintaining WordPress PluginsCreating and Maintaining WordPress Plugins
Creating and Maintaining WordPress Plugins
Mark Jaquith
 
Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the Finish
Yehuda Katz
 

Similar to AssertJ quick introduction (20)

international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitinternational PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
PhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsPhpUnit - The most unknown Parts
PhpUnit - The most unknown Parts
 
PHPUnit best practices presentation
PHPUnit best practices presentationPHPUnit best practices presentation
PHPUnit best practices presentation
 
Class loader basic
Class loader basicClass loader basic
Class loader basic
 
Unit Testing using PHPUnit
Unit Testing using  PHPUnitUnit Testing using  PHPUnit
Unit Testing using PHPUnit
 
Testing Java Code Effectively
Testing Java Code EffectivelyTesting Java Code Effectively
Testing Java Code Effectively
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
Spring into rails
Spring into railsSpring into rails
Spring into rails
 
Intro to Testing in Zope, Plone
Intro to Testing in Zope, PloneIntro to Testing in Zope, Plone
Intro to Testing in Zope, Plone
 
Aura Project for PHP
Aura Project for PHPAura Project for PHP
Aura Project for PHP
 
 
Lambda functions in java 8
Lambda functions in java 8Lambda functions in java 8
Lambda functions in java 8
 
Using and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareUsing and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middleware
 
TYPO3 6.2 for extension developer
TYPO3 6.2 for extension developerTYPO3 6.2 for extension developer
TYPO3 6.2 for extension developer
 
Creating and Maintaining WordPress Plugins
Creating and Maintaining WordPress PluginsCreating and Maintaining WordPress Plugins
Creating and Maintaining WordPress Plugins
 
Fighting Fear-Driven-Development With PHPUnit
Fighting Fear-Driven-Development With PHPUnitFighting Fear-Driven-Development With PHPUnit
Fighting Fear-Driven-Development With PHPUnit
 
Using WordPress as your application stack
Using WordPress as your application stackUsing WordPress as your application stack
Using WordPress as your application stack
 
Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the Finish
 
Android Automated Testing
Android Automated TestingAndroid Automated Testing
Android Automated Testing
 

Recently uploaded

Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
mbmh111980
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
Alluxio, Inc.
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 

Recently uploaded (20)

Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdfA Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
Breaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdfBreaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdf
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
 
AI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning FrameworkAI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning Framework
 
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
AI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in MichelangeloAI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in Michelangelo
 
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 

AssertJ quick introduction

  • 2. What is it? Library to simplify assertions in tests Forked from fest-assert: actively maintained Focus on improving readability through its fluent API: IDE friendly
  • 3. How to use? Add Maven dependency (already on parent/pom.xml): <dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> <version>3.2.0</version> <!-- Not needed on common-uber sub-projects --> <scope>test</scope> <!-- Not needed on common-uber sub-projects --> </dependency> Add static import to Eclipse: 1. Go to : Preferences > Java > Editor > Content assist > Favorites > New Type 2. Enter : org.assertj.core.api.Assertions 3. You should see : org.assertj.core.api.Assertions.* in the list.
  • 4. Simple assertions // AssertJ Assertions.assertThat(retrievedStore) .isNotNull(); Assertions.assertThat(retrievedStore.name) .isEqualTo(dbStore.getName()); Assertions.assertThat(retrievedStore.isMobileOptimized) .isTrue(); Assertions.assertThat(detailReport.getEntries()) .as("Detail report %s entries", countryCode) .isNotNull().hasSize(5); // Hamcrest MatcherAssert.assertThat(retrievedStore, Matchers.is(Matchers.notNullValue())); MatcherAssert.assertThat(retrievedStore.name, Matchers.equalTo(dbStore.getName())); MatcherAssert.assertThat(retrievedStore.isMobileOptimized, Matchers.is(true)); MatcherAssert.assertThat(detailReport.getEntries(), Matchers.is(Matchers.notNullValue())); MatcherAssert.assertThat(detailReport.getEntries(), Matchers.hasSize(5));
  • 5. Friendly and comprehensive error messages // AssertJ - Strings comparison Assertions.assertThat("The quick brown fox jump over the lazy dog").isEqualTo("The quick brown fox jumps over the lazy dog"); expected:<...quick brown fox jump[s] over the lazy dog"> but was:<...quick brown fox jump[] over the lazy dog"> // Hamcrest - Strings comparison MatcherAssert.assertThat("The quick brown fox jump over the lazy dog", Matchers.equalTo("The quick brown fox jumps over the lazy dog")); Expected: "The quick brown fox jumps over the lazy dog" but: was "The quick brown fox jump over the lazy dog" // Hamcrest - List elements comparison MatcherAssert.assertThat(Arrays.asList(1, 2, 3, 4, 5), Matchers.hasItems(5, 7)); Expected: (a collection containing <5> and a collection containing <7>) but: a collection containing <7> mismatches were: [was <1>, was <2>, was <3>, was <4>, was <5>] // AssertJ - List elements comparison Assertions.assertThat(Arrays.asList(1, 2, 3, 4, 5)).contains(5, 7); Expecting: <[1, 2, 3, 4, 5]> to contain: <[5, 7]> but could not find: <[7]>
  • 6. Filtering and assertions on iterables or arrays // AssertJ // Filter uses introspection to get property/field value Assertions.assertThat(fellowshipOfTheRing) .filteredOn("race", HOBBIT) .containsOnly(sam, frodo, pippin, merry); // Nested properties are supported Assertions.assertThat(fellowshipOfTheRing) .filteredOn("race.name", "Man") .containsOnly(aragorn, boromir); // Chaining multiple filter criteria Assertions.assertThat(fellowshipOfTheRing) .filteredOn("race", MAN) .filteredOn("name", not("Boromir")) .containsOnly(aragorn); // Hamcrest // Not even fair… you have to do it manually =/ List<TolkienCharacter> fellowshipHobbits = fellowshipOfTheRing.stream() .filter(c -> c.getRace().equals(Race.HOBBIT)) .collect(Collectors.toList()); MatcherAssert.assertThat(fellowshipHobbits, Matchers.contains(sam, frodo, pippin, merry)); // No containsOnly
  • 7. Filtering and assertions on iterables or arrays (cont.) // AssertJ // WesterosHouse class has a method: public String sayTheWords() List<WesterosHouse> greatHouses = new ArrayList<>(); 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 great houses in Westeros: Assertions.assertThat(greatHouses).extractingResultOf("sayTheWords") .contains("Winter is Coming", "We Do Not Sow", "Hear Me Roar!") .doesNotContain("Lannisters always pay their debts");
  • 8. Friendly exceptions/throwables testing // Hamcrest // Given Long inexistentStoreId = 999L; try { // When this.repository.retrieve(inexistentStoreId); Assert.fail(); } catch (NoSuchElementException e) { // Then assertThat(e.getMessage(), containsString("Store ID '999' does not exist")); } // AssertJ // Given Long inexistentStoreId = 999L; // When - Then assertThatThrownBy(() -> repository.retrieve(inexistentStoreId)) .isInstanceOf(NoSuchElementException.class) .hasMessageContaining("Store ID '999' does not exist");
  • 9. Java 8 Support: Time API // AssertJ LocalDate firstOfJanuary2000 = LocalDate.parse("2000-01-01"); // AssertJ converts String parameters to LocalDate // to ease writing expected LocalDate Assertions.assertThat(firstOfJanuary2000) .isEqualTo("2000-01-01"); Assertions.assertThat(firstOfJanuary2000) .isAfter("1999-12-31") .isAfterOrEqualTo("1999-12-31") .isAfterOrEqualTo("2000-01-01"); // Hamcrest - using third-party extension: // org.exparity:hamcrest-date LocalDate firstOfJanuary2000 = LocalDate.parse("2000-01-01"); MatcherAssert.assertThat(firstOfJanuary2000, Matchers.equalTo(LocalDate.parse("2000-01-01"))); MatcherAssert.assertThat(firstOfJanuary2000, LocalDateMatchers.after( LocalDate.parse("1999-12-31"))); // No afterOrEqual matcher
  • 10. Java 8 Support: Optionals // AssertJ // optional with value Optional<String> optional = Optional.of("Test"); Assertions.assertThat(optional) .isPresent().contains("Test"); // empty optional Optional<Object> emptyOptional = Optional.empty(); Assertions.assertThat(emptyOptional).isEmpty(); // Hamcrest // optional with value Optional<String> optional = Optional.of("Test"); MatcherAssert.assertThat(optional.isPresent(), Matchers.is(true)); MatcherAssert.assertThat(optional.get(), Matchers.equalTo("Test")); // empty optional Optional<Object> emptyOptional = Optional.empty(); MatcherAssert.assertThat(emptyOptional, Matchers.equalTo(Optional.<Object> empty()));
  • 11. Other features Assertions on extracted fields/properties extracts properties from iterable elements for assertions Soft assertions collect all assertions instead of stopping at the first one String assertions on file contents no need to manually read the file (useful for small files) Flat(map) extracting flatten a collection by extracting a field from it