From 67850fdda5a33dfff7a2c04c970b3ea9139a5f80 Mon Sep 17 00:00:00 2001 From: Michael Keppler Date: Fri, 13 Oct 2023 15:39:53 +0200 Subject: [PATCH] Globally configure source indentation (#134) --- build.gradle | 3 +- .../assertj-core-assertions-guide.adoc | 176 +++++++++--------- .../user-guide/assertj-core-migration.adoc | 24 +-- .../user-guide/assertj-core-quickstart.adoc | 14 +- .../assertj-core-release-notes.adoc | 130 ++++++------- .../asciidoc/user-guide/assertj-core.adoc | 2 +- .../user-guide/assertj-db-quickstart.adoc | 6 +- .../user-guide/assertj-guava-quickstart.adoc | 8 +- .../assertj-guava-release-notes.adoc | 4 +- .../user-guide/assertj-joda-quickstart.adoc | 12 +- .../assertj-joda-release-notes.adoc | 4 +- 11 files changed, 192 insertions(+), 191 deletions(-) diff --git a/build.gradle b/build.gradle index 709cf68..7c5e051 100644 --- a/build.gradle +++ b/build.gradle @@ -64,7 +64,8 @@ asciidoctor { 'assertj-joda-time-version': assertjJodaTimeVersion, 'assertj-db-version': assertjDbVersion, 'stylesheet': '../../../docs/asciidoc/asciidoctor.css', - 'docinfo': 'shared' + 'docinfo': 'shared', + 'source-indent': '0' } asciidoctorj { diff --git a/src/docs/asciidoc/user-guide/assertj-core-assertions-guide.adoc b/src/docs/asciidoc/user-guide/assertj-core-assertions-guide.adoc index 48dbd1a..aaa3e10 100644 --- a/src/docs/asciidoc/user-guide/assertj-core-assertions-guide.adoc +++ b/src/docs/asciidoc/user-guide/assertj-core-assertions-guide.adoc @@ -10,7 +10,7 @@ AssertJ Core http://www.javadoc.io/doc/org.assertj/assertj-core/[Javadoc] explai Let's start with a simple example showing a few important things. -[source,java,indent=0] +[source,java] ---- include::{testDir}/example/core/SimpleAssertionsExample.java[tags=user_guide] ---- @@ -141,7 +141,7 @@ It is often valuable to describe the assertion performed, especially for boolean You can set such a description with `as(String description, Object... args)` but remember to do it before calling the assertion otherwise it is simply ignored as a failing assertion breaks the chained calls. Example of a failing assertion with a description: -[source,java,indent=0] +[source,java] ---- include::{testDir}/example/core/DescribingAssertionsExample.java[tags=user_guide] ---- @@ -163,7 +163,7 @@ If printing assertion descriptions is not what you need, you can alternatively r Both options are exposed in AssertJ link:#assertj-core-configuration[`Configuration`] class. Example: using a description consumer -[source,java,indent=0] +[source,java] ---- // initialize the description consumer final StringBuilder descriptionReportBuilder = new StringBuilder(String.format("Assertions:%n")); @@ -197,7 +197,7 @@ Assertions: AssertJ tries its best to give helpful error messages, but you can always change it with `overridingErrorMessage()` or `withFailMessage()`. Example with this failing test: -[source,java,indent=0] +[source,java] ---- include::{testDir}/example/core/OverridingErrorMessageExample.java[tags=user_guide] ---- @@ -215,7 +215,7 @@ java.lang.AssertionError: should be TolkienCharacter [name=Frodo, age=33, race=H If the error message is expensive to build, use the overloaded methods taking a `Supplier` instead of a `String`, the message will only be built if the assertion fails. Example: -[source,java,indent=0] +[source,java] ---- assertThat(player.isRookie()).overridingErrorMessage(() -> "Expecting Player to be a rookie but was not.") .isTrue(); @@ -247,14 +247,14 @@ image::spotbugs-invalid-assertj-usage-detection.png[SpotBugs detecting AssertJ i The following examples show incorrect AssertJ API usage to avoid! [.bad]#Bad# -[source,java,indent=0] +[source,java] ---- // DON'T DO THIS ! It does not assert anything assertThat(actual.equals(expected)); ---- [.good]#Good# -[source,java,indent=0] +[source,java] ---- // DO THIS: assertThat(actual).isEqualTo(expected); @@ -264,7 +264,7 @@ assertThat(actual.equals(expected)).isTrue(); ---- [.bad]#Bad# -[source,java,indent=0] +[source,java] ---- // DON'T DO THIS ! It does not assert anything and passes assertThat(1 == 2); @@ -272,7 +272,7 @@ assertThat(1 == 2); ---- [.good]#Good# -[source,java,indent=0] +[source,java] ---- // DO THIS: (fails as expected) assertThat(1).isEqualTo(2); @@ -287,7 +287,7 @@ Describing an assertion must be done before calling the assertion. Otherwise it is ignored as a failing assertion will prevent the call to `as()`. [.bad]#Bad# -[source,java,indent=0] +[source,java] ---- // DON'T DO THIS ! as/describedAs have no effect after the assertion assertThat(actual).isEqualTo(expected).as("description"); @@ -295,7 +295,7 @@ assertThat(actual).isEqualTo(expected).describedAs("description"); ---- [.good]#Good# -[source,java,indent=0] +[source,java] ---- // DO THIS: use as/describedAs before the assertion assertThat(actual).as("description").isEqualTo(expected); @@ -308,7 +308,7 @@ Setting an error message must be done before calling the assertion. Otherwise it is ignored as a failing assertion will prevent the call to `withFailMessage()` / `overridingErrorMessage()`. [.bad]#Bad# -[source,java,indent=0] +[source,java] ---- // DON'T DO THIS ! overridingErrorMessage/withFailMessage have no effect after the assertion assertThat(actual).isEqualTo(expected).overridingErrorMessage("custom error message"); @@ -316,7 +316,7 @@ assertThat(actual).isEqualTo(expected).withFailMessage("custom error message"); ---- [.good]#Good# -[source,java,indent=0] +[source,java] ---- // DO THIS: use overridingErrorMessage/withFailMessage before the assertion assertThat(actual).overridingErrorMessage("custom error message").isEqualTo(expected); @@ -329,14 +329,14 @@ Setting comparators must be done before calling the assertion. Otherwise it is ignored as a failing assertion will prevent the call to `usingComparator()` / `usingElementComparator()`. [.bad]#Bad# -[source,java,indent=0] +[source,java] ---- // DON'T DO THIS ! Comparator is not used assertThat(actual).isEqualTo(expected).usingComparator(new CustomComparator()); ---- [.good]#Good# -[source,java,indent=0] +[source,java] ---- // DO THIS: assertThat(actual).usingComparator(new CustomComparator()).isEqualTo("a"); @@ -359,7 +359,7 @@ To be effective the configuration changes must be applied before the tests are e The `Assertions` class provides static methods to change each configuration properties. -[source,java,indent=0] +[source,java] ---- Assertions.setAllowComparingPrivateFields(true); Assertions.setAllowExtractingPrivateFields(false); @@ -416,28 +416,28 @@ is less than this parameter) or it will be formatted with one element per line. Example: -[source,java,indent=0] +[source,java] ---- String[] greatBooks = array("A Game of Thrones", "The Lord of the Rings", "Assassin's Apprentice"); ---- this array is formatted on one line as its length < 80: -[source,java,indent=0] +[source,java] ---- ["A Game of Thrones", "The Lord of the Rings", "Assassin's Apprentice"] ---- Whereas this array ... -[source,java,indent=0] +[source,java] ---- String[] greatBooks = array("A Game of Thrones", "The Lord of the Rings", "Assassin's Apprentice", "Guards! Guards! (Discworld)"); ---- \... is formatted on multiple lines with one element per line: -[source,java,indent=0] +[source,java] ---- ["A Game of Thrones", @@ -462,7 +462,7 @@ IMPORTANT: Your configuration will be effective once you call `Configuration.app Example: -[source,java,indent=0] +[source,java] ---- Configuration configuration = new Configuration(); @@ -480,7 +480,7 @@ configuration.applyAndDisplay(); Printing the above configuration produces the following output: -[source,plaintext,indent=0] +[source,plaintext] ---- Applying configuration org.assertj.core.configuration.Configuration - representation .................................. = BinaryRepresentation @@ -511,19 +511,19 @@ This is all you have to do, AssertJ will pick up the `Configuration` automatical Here's an example of a custom configuration class: -[source,java,indent=0] +[source,java] ---- include::{testDir}/example/core/CustomConfiguration.java[] ---- With this custom configuration, the content of `META-INF/services/org.assertj.core.configuration.Configuration` must be: -[source,java,indent=0] +[source,java] ---- example.core.CustomConfiguration ---- Printing the `CustomConfiguration` shows: -[source,plaintext,indent=0] +[source,plaintext] ---- Applying configuration example.core.CustomConfiguration - representation .................................. = BinaryRepresentation @@ -555,7 +555,7 @@ Let's go over these different options with a custom `Representation`. ===== Creating a custom Representation An example of a custom `Representation`: -[source,java,indent=0] +[source,java] ---- // dummy class private class Example {} @@ -584,24 +584,24 @@ public class CustomRepresentation extends StandardRepresentation { // <1> Let's see the above custom representation in action when representing `Example` or `String` instances. This assertion fails ... -[source,java,indent=0] +[source,java] ---- assertThat(new Example()).isNull(); ---- ...with the following error: -[source,java,indent=0] +[source,java] ---- expected:<[null]> but was:<[Example]> ---- This one fails ... -[source,java,indent=0] +[source,java] ---- // this one fails ... assertThat("foo").startsWith("bar"); ---- ...with the following error: -[source,java,indent=0] +[source,java] ---- Expecting: <$foo$> @@ -614,7 +614,7 @@ to start with: You only have to register `CustomRepresentation` once but need to do it before executing any tests, for the tests executed before that, AssertJ will use the default representation. -[source,java,indent=0] +[source,java] ---- // to call before executing tests Assertions.useRepresentation(new CustomRepresentation()); @@ -628,7 +628,7 @@ Consider writing a JUnit 5 extension implementing https://junit.org/junit5/docs/ Follow this approach if you want to use a specific representation for a single assertion only. Example with the failing assertions used before: -[source,java,indent=0] +[source,java] ---- Representation customRepresentation = new CustomRepresentation(); @@ -656,7 +656,7 @@ In case different representations can represent the same type, the one with the Let's take a concrete example where we have two domain specific libraries: Lotr and star wars and a project that uses them both. The Lotr library is composed of an `Hobbit` class and a specific representation for it, note that `LotrRepresentation` represents Hobbits starting with `HOBBIT` unlike `Hobbit` `toString` method: -[source,java,indent=0] +[source,java] ---- package org.assertj.example.lotr; @@ -840,7 +840,7 @@ You can assert that all or any elements verify the given assertions with `allSat The given assertions are expressed with a `Consumer` (typically with a lambda). Examples: -[source,java,indent=0] +[source,java] ---- List hobbits = list(frodo, sam, pippin); @@ -867,7 +867,7 @@ NOTE: if `allSatisfy` fails, all the elements and their failing the assertions a You can assert that all or any elements match the given `Predicate` with `allMatch` and `anyMatch`, conversely `noneMatch` lets you assert that no elements verify the given predicate. Examples: -[source,java,indent=0] +[source,java] ---- List hobbits = list(frodo, sam, pippin); @@ -891,7 +891,7 @@ NOTE: this is only available for iterables at the moment. Use `first`, `last` and `element(index)` to navigate to the corresponding element, after navigating you can only use object assertions unless you have specified an Assert class or preferrably an `InstanceOfAssertFactory` as shown in the following examples. Examples: -[source,java,indent=0] +[source,java] ---- // only object assertions available after navigation Iterable hobbits = list(frodo, sam, pippin); @@ -925,7 +925,7 @@ assertThat(hobbitsName, StringAssert.class).first() `singleElement` checks that the iterable has only one element and navigates to it, after navigating you can only use object assertions unless you have specified an Assert class or preferrably an `InstanceOfAssertFactory` as shown in the following examples. Examples: -[source,java,indent=0] +[source,java] ---- Iterable babySimpsons = list("Maggie"); @@ -962,7 +962,7 @@ You specify the filter condition using simple predicate, best expressed with a l Example: -[source,java,indent=0] +[source,java] ---- assertThat(fellowshipOfTheRing).filteredOn( character -> character.getName().contains("o") ) .containsOnly(aragorn, frodo, legolas, boromir); @@ -976,7 +976,7 @@ Filter supports nested properties/fields. Note that if an intermediate value is Filters support these basic operations: `not`, `in`, `notIn` -[source,java,indent=0] +[source,java] ---- import static org.assertj.core.api.Assertions.in; import static org.assertj.core.api.Assertions.not; @@ -1011,7 +1011,7 @@ assertThat(fellowshipOfTheRing).filteredOn("race", MAN) This is a more flexible way of getting the value to filter on but note that there is no support for operators like `not`, `in` and `notIn`. -[source,java,indent=0] +[source,java] ---- assertThat(fellowshipOfTheRing).filteredOn(TolkienCharacter::getRace, HOBBIT) .containsOnly(sam, frodo, pippin, merry); @@ -1023,7 +1023,7 @@ Filters the elements whose specified property/field is null. Filter supports nested properties/fields. Note that if an intermediate value is null the whole nested property/field is considered to be null, for example reading `"address.street.name"` will return null if `"address.street"` is null. -[source,java,indent=0] +[source,java] ---- TolkienCharacter pippin = new TolkienCharacter("Pippin", 28, HOBBIT); TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT); @@ -1042,7 +1042,7 @@ assertThat(hobbits).filteredOnNull("name")) Filters the iterable under test keeping only elements matching the given assertions specified with a `Consumer`. Example: check hobbits whose age < 34 -[source,java,indent=0] +[source,java] ---- TolkienCharacter pippin = new TolkienCharacter("Pippin", 28, HOBBIT); TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT); @@ -1060,7 +1060,7 @@ Filter the iterable/array under test keeping only elements matching the given li Two methods are available: being(Condition) and having(Condition). They do the same job - pick the one that makes your code more readable! -[source,java,indent=0] +[source,java] ---- import org.assertj.core.api.Condition; @@ -1085,7 +1085,7 @@ assertThat(players).filteredOn(mvpStats) Let's say you have called some service and got a list (or an array) of `TolkienCharacter`, to check the results you have to build the expected TolkienCharacters, that can be quite tedious! -[source,java,indent=0] +[source,java] ---- List fellowshipOfTheRing = tolkienDao.findHeroes(); // frodo, sam, aragorn ... @@ -1095,7 +1095,7 @@ assertThat(fellowshipOfTheRing).contains(frodo, aragorn); Instead, it is usually enough to check some fields or properties on the elements, for that you have to extract the fields/properties before performing your assertions, something like: -[source,java,indent=0] +[source,java] ---- // extract the names ... List names = fellowshipOfTheRing.stream().map(TolkienCharacter::getName).collect(toList()); @@ -1116,7 +1116,7 @@ Specify the field/property to extract (or pass a `Function`) from each elements Extracting by name can access private fields/properties which is handy to check internals not exposed with public methods (lambda won't work here), it also supports nested field/property like `"race.name"`. Examples: -[source,java,indent=0] +[source,java] ---- // "name" needs to be either a property or a field of the TolkienCharacter class assertThat(fellowshipOfTheRing).extracting("name") @@ -1138,7 +1138,7 @@ assertThat(fellowshipOfTheRing).map(TolkienCharacter::getName) Note that extracting one property can be made strongly typed by giving the property type as the second argument. -[source,java,indent=0] +[source,java] ---- // to have type safe extracting, use the second parameter to pass the expected property type: assertThat(fellowshipOfTheRing).extracting("name", String.class) @@ -1152,7 +1152,7 @@ You can extract several values from the elements under test and check them using As an example, let's check the name, age and race's name of each TolkienCharacter element: -[source,java,indent=0] +[source,java] ---- // when checking several properties/fields you have to use tuples: import static org.assertj.core.api.Assertions.tuple; @@ -1182,7 +1182,7 @@ More examples are available in link:{assertj-examples-base-package}IterableAsser Flat extracting is hard to explain but easy to understand with an example, so let's see how it works (in functional programming it is juts a flatMap). Let's assume we have a `Player` class with a `teamMates` property returning a `List` and we want to assert that it returns the expected players: -[source,java,indent=0] +[source,java] ---- Player jordan = ... // initialized with Pippen and Kukoc team mates Player magic = ... // initialized with Jabbar and Worthy team mates @@ -1209,7 +1209,7 @@ TIP: You can use `flatMap` in place of `flatExtracting` (except for the variant Flat extracting can be used to group multiple values if you don't want to use `extracting` and tuples: -[source,java,indent=0] +[source,java] ---- // extract a list of values, flatten them and use contains assertion assertThat(fellowshipOfTheRing).flatExtracting("name", "race.name") @@ -1227,7 +1227,7 @@ assertThat(fellowshipOfTheRing).flatExtracting(TolkienCharacter::getName, `usingElementComparator` allows you to change the way elements are compared (instead of using the elements `equals` method). Examples: -[source,java,indent=0] +[source,java] ---- List fellowshipOfTheRing = list(frodo, sam, merry, pippin, gandald, legolas, boromir, aragorn, gimli); @@ -1610,7 +1610,7 @@ The recursive comparison mode starts after calling `usingRecursiveComparison()`. Here's a simple example: -[source,java,indent=0] +[source,java] ---- public class Person { String name; @@ -1677,7 +1677,7 @@ Since 3.17.0 it does not use anymore `equals` methods of classes that have overr Since 3.17.0 `isNotEqualTo` is available in the recursive API, example: -[source,java,indent=0] +[source,java] ---- // equals not overridden in TolkienCharacter TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT); @@ -1703,7 +1703,7 @@ By default the objects to compare can be of different types but must have the sa It is possible to enforce strict type checking by calling `withStrictTypeChecking()` and make the comparison fail whenever the compared objects or their fields are not compatible. Compatible means that the expected object/field types are the same or a subtype of actual/field types, for example if actual is an `Animal` and expected a `Dog`, they will be compared field by field in strict type checking mode. -[source,java,indent=0] +[source,java] ---- public class Person { String name; @@ -1772,7 +1772,7 @@ It is also possible to ignore the the object under test with `ignoringActualNull Examples -[source,java,indent=0] +[source,java] ---- Person sherlock = new Person("Sherlock", 1.80); sherlock.home.address.street = "Baker Street"; @@ -1828,7 +1828,7 @@ Once using overridden `equals` methods is enabled, you can disable it for certai Example: -[source,java,indent=0] +[source,java] ---- public class Person { String name; @@ -1883,7 +1883,7 @@ One use case for that is when the object under test have fields with values hard Example: -[source,java,indent=0] +[source,java] ---- public class Person { String name; @@ -1923,7 +1923,7 @@ assertThat(noName).usingRecursiveComparison() `ignoringActualEmptyOptionalFields()` makes the recursive comparison to ignore all actual empty optional fields (including `Optional`, `OptionalInt`, `OptionalLong` and `OptionalDouble`). + Note that the expected object empty optional fields are not ignored, this only applies to actual's fields. -[source,java,indent=0] +[source,java] ---- public class Person { String name; @@ -1981,7 +1981,7 @@ TIP: Prefer using `withEqualsForFields`/`withEqualsForType`, providing a `BiPred Examples: -[source,java,indent=0] +[source,java] ---- public class TolkienCharacter { String name; @@ -2021,14 +2021,14 @@ assertThat(frodo).usingRecursiveComparison() If AssertJ difference error description is not yo your liking, you can override it either by fields or types. You can override messages for all fields of a given type, example for `Double`: -[source,java,indent=0] +[source,java] ---- withErrorMessageForType("Double field differ", Double.class) ---- Alternatively can override messages for some specific fields which must be specified from the root object, for example if `Foo` has a `Bar` field and both have an `id` field, one can register a message for `Foo` and `Bar` id by calling: -[source,java,indent=0] +[source,java] ---- withErrorMessageForFields("id values differ", "foo.id", "foo.bar.id") ---- @@ -2036,7 +2036,7 @@ withErrorMessageForFields("id values differ", "foo.id", "foo.bar.id") Messages registered with `withErrorMessageForFields` have precedence over the ones registered with `withErrorMessageForType`. Example overriding message for a field: -[source,java,indent=0] +[source,java] ---- public class TolkienCharacter { String name; @@ -2057,7 +2057,7 @@ assertThat(frodo).usingRecursiveComparison() and the error will report the height field with the given overridden message instead of the one computed by AssertJ as with the name error: -[source,text,indent=0] +[source,text] ---- Expecting actual: TolkienCharacter [name=Frodo, height=1.2] @@ -2083,7 +2083,7 @@ The recursive comparison was performed with this configuration: ---- Example overriding message for a type: -[source,java,indent=0] +[source,java] ---- String message = "Double field differ"; @@ -2095,7 +2095,7 @@ assertThat(frodo).usingRecursiveComparison() and the error will report the height field with the given overridden message instead of the one computed by AssertJ as with the name error: -[source,text,indent=0] +[source,text] ---- Expecting actual: TolkienCharacter [name=Frodo, height=1.2] @@ -2129,7 +2129,7 @@ The recursive comparison was performed with this configuration: Another difference is that `usingRecursiveComparison()` exposes a fluent API to tweak the recursive comparison, to achieve the same you will need to initialize a `RecursiveComparisonConfiguration` and pass it to `usingRecursiveFieldByFieldElementComparator`, you can take advantage of the `RecursiveComparisonConfiguration.builder()` to do so. Example: -[source,java,indent=0] +[source,java] ---- public class Person { String name; @@ -2196,7 +2196,7 @@ Here's an example using `ComparingSnakeOrCamelCaseFields` where we compare `Auth The recursive comparison would fail comparing the `Author`/`Book` fields against `AuthorDto`/`BookDto` ones, it would not know to match `Author.firstName` against `AuthorDto.first_name` for example but with `ComparingSnakeOrCamelCaseFields` it will know how to match these fields. Example: -[source,java,indent=0] +[source,java] ---- Author martinFowler = new Author("Martin", "Fowler", 58, "https://www.thoughtworks.com/profiles/leaders/martin-fowler"); Book refactoring = new Book("Refactoring", martinFowler); @@ -2342,7 +2342,7 @@ If you have created your own custom Soft assertions it is possible to link:#asse Let's see first how to use soft assertions *requiring an explicit call to `assertAll()`*, the other approaches that don't require this explicitit call are described in the subsequent sections. Example: -[source,java,indent=0] +[source,java] ---- include::{testDir}/example/core/SoftAssertionsExample.java[tags=basic-soft-assertions] ---- @@ -2382,7 +2382,7 @@ but was not. BDD aficionados can use BDD soft assertions where `assertThat` is replaced by `then`. Example: -[source,java,indent=0] +[source,java] ---- include::{testDir}/example/core/BDDSoftAssertionsExample.java[tags=basic-bdd-soft-assertions] ---- @@ -2399,13 +2399,13 @@ There are BDD soft assertions versions for the different soft assertions approac The JUnit rule provided by AssertJ takes care of calling `assertAll()` at the end of each tests. Example: -[source,java,indent=0] +[source,java] ---- include::{testDir}/example/core/JUnit4SoftAssertionsExample.java[tags=junit4-soft-assertions] ---- In a similar way you can use `JUnitBDDSoftAssertions` where `assertThat` is replaced by `then`: -[source,java,indent=0] +[source,java] ---- include::{testDir}/example/core/JUnit4BDDSoftAssertionsExample.java[tags=junit4-bdd-soft-assertions] ---- @@ -2440,7 +2440,7 @@ This extension throws an `ExtensionConfigurationException` if: * the field type has no default constructor. Example: -[source,java,indent=0] +[source,java] ---- import org.assertj.core.api.SoftAssertions; import org.assertj.core.api.junit.jupiter.SoftAssertionsExtension; @@ -2497,7 +2497,7 @@ This extension throws a `ParameterResolutionException` if the resolved `SoftAsse Example: -[source,java,indent=0] +[source,java] ---- include::{testDir}/example/core/JUnit5SoftAssertionsExample.java[tags=junit5-soft-assertions] ---- @@ -2509,13 +2509,13 @@ include::{testDir}/example/core/JUnit5SoftAssertionsExample.java[tags=junit5-sof As `AutoCloseableSoftAssertions` implements `AutoCloseable#close()` by calling `assertAll()`, when used in a try-with-resources block `assertAll()` is called automatically before exiting the block. Example: -[source,java,indent=0] +[source,java] ---- include::{testDir}/example/core/AutoCloseableSoftAssertionsExample.java[tags=closeable-soft-assertions] ---- In a similar way you can use `AutoCloseableBDDSoftAssertions` where `assertThat` is replaced by `then`: -[source,java,indent=0] +[source,java] ---- include::{testDir}/example/core/AutoCloseableBDDSoftAssertionsExample.java[tags=closeable-bdd-soft-assertions] ---- @@ -2526,7 +2526,7 @@ include::{testDir}/example/core/AutoCloseableBDDSoftAssertionsExample.java[tags= The `assertSoftly` static method takes care of calling `assertAll()` before exiting. Example: -[source,java,indent=0] +[source,java] ---- include::{testDir}/example/core/SoftAssertionsExample.java[tags=assertSoftly-soft-assertions] ---- @@ -2538,7 +2538,7 @@ Since the 3.16.0 version AssertJ provides a way to combine standard soft asserti Let's assume we have written an entry point for `TolkienCharacter` soft assertions so that we can write assertions like: -[source,java,indent=0] +[source,java] ---- TolkienSoftAssertions softly = new TolkienSoftAssertions(); softly.assertThat(frodo).hasRace(HOBBIT) @@ -2552,7 +2552,7 @@ The 3.16.0 release introduced the `SoftAssertionsProvider` interface to define s The first step consists in extending this interface to expose as many custom entry points as you need. + The typical custom `SoftAssertionsProvider` interface exposes default `assertThat` methods, as shown below: -[source,java,indent=0] +[source,java] ---- public interface TolkienSoftAssertionsProvider extends SoftAssertionsProvider { // custom assertions @@ -2577,7 +2577,7 @@ In order to get a concrete entry point exposing all custom entry points, create To get standard soft assertions, inherit from `SoftAssertions` instead of `AbstractSoftAssertions` (or `BddSoftAssertions` to get the BDD flavor). Let's define our concrete entry points implementing both `TolkienSoftAssertionsProvider` and `GoTSoftAssertionsProvider`: -[source,java,indent=0] +[source,java] ---- // we extend SoftAssertions to get standard soft assertions public class FantasySoftAssertions extends SoftAssertions @@ -2592,7 +2592,7 @@ public class FantasySoftAssertions extends SoftAssertions [.underline]#Step 3# + The last step is to use `FantasySoftAssertions`: -[source,java,indent=0] +[source,java] ---- FantasySoftAssertions softly = new FantasySoftAssertions(); @@ -2613,14 +2613,14 @@ softly.assertAll(); Because our custom assertions are defined in an interface, we can also combine them with AssertJ's JUnit 4 rule so that we can use our custom assertions as a test rule for use in JUnit 4: -[source,java,indent=0] +[source,java] ---- // we extend JUnitSoftAssertions to get standard soft assertions classes public class JUnitFantasySoftAssertions extends JUnitSoftAssertions implements TolkienSoftAssertionsProvider, GoTSoftAssertionsProvider {} ---- Then in our test class we use it per normal: -[source,java,indent=0] +[source,java] ---- public class JUnit4_StandardAndCustomSoftAssertionsExamples { @Rule @@ -2644,7 +2644,7 @@ The rule will automatically take care of calling `assertAll()` at the end of eve JUnit 5 `SoftAssertionsExtension` calls `softly.assertAll()` after each test so that we don't have to do it manually. + Since 3.16.0 it is capable of injecting any `SoftAssertionsProvider`, we can then inject our custom `FantasySoftAssertions`: -[source,java,indent=0] +[source,java] ---- @ExtendWith(SoftAssertionsExtension.class) public class JUnit5_StandardAndCustomSoftAssertionsExamples { @@ -2666,7 +2666,7 @@ AssertJ allows to perform an action after an `AssertionError` is collected. The action is specified by the `AfterAssertionErrorCollected` functional interface which can be expressed as lambda, to register your callback call `setAfterAssertionErrorCollected` as shown below: Example: -[source,java,indent=0] +[source,java] ---- SoftAssertions softly = new SoftAssertions(); StringBuilder reportBuilder = new StringBuilder(format("Assertions report:%n")); @@ -2679,7 +2679,7 @@ softly.assertThat(123).isEqualTo(123) .isEqualTo(456); ---- resulting `reportBuilder`: -[indent=0, text] +[source,text] ---- Assertions report: ------------------ @@ -2700,7 +2700,7 @@ but was not. Alternatively, if you have defined your own `SoftAssertions` class and inherited from `AbstractSoftAssertions`, you can instead override `onAssertionErrorCollected(AssertionError)`. Example: -[source,java,indent=0] +[source,java] ---- class TolkienSoftAssertions extends AbstractSoftAssertions { @@ -2733,13 +2733,13 @@ All AssertJ assumptions are static methods in the `Assumptions` class, they matc You can also get assumptions through the `WithAssumptions` interface. Example resulting in the test to be ignored: -[source,java,indent=0] +[source,java] ---- include::{testDir}/example/core/AssumptionsDemo.java[tags=assumption_not_met] ---- Example resulting in the test to be executed normally: -[source,java,indent=0] +[source,java] ---- include::{testDir}/example/core/AssumptionsDemo.java[tags=assumption_met] ---- diff --git a/src/docs/asciidoc/user-guide/assertj-core-migration.adoc b/src/docs/asciidoc/user-guide/assertj-core-migration.adoc index c7c0486..8c4a2ae 100644 --- a/src/docs/asciidoc/user-guide/assertj-core-migration.adoc +++ b/src/docs/asciidoc/user-guide/assertj-core-migration.adoc @@ -5,14 +5,14 @@ This page will help you convert your existing JUnit assertions to AssertJ ones. The idea is to convert code like: -[source,java,indent=0] +[source,java] ---- assertEquals(expected, actual); ---- to: -[source,java,indent=0] +[source,java] ---- assertThat(actual).isEqualTo(expected); ---- @@ -43,12 +43,12 @@ performs search and replace to convert assertions to AssertJ ones. The script handles the cases where you use an assertion description, for example: -[source,java,indent=0] +[source,java] ---- assertEquals("test context", "a", "a"); ---- will be replaced by: -[source,java,indent=0] +[source,java] ---- assertThat("a").as("test context").isEqualTo("a"); ---- @@ -62,14 +62,14 @@ The script works on Windows within a bash console like git bash (tested a long t Execute the script in the base directory containing the test files: -[source,bash,indent=0] +[source,bash] ---- cd ./src/test/java ./convert-junit-assertions-to-assertj.sh ---- If the `*Test.java` file pattern does not suit you, just specify another as an argument: -[source,bash,indent=0] +[source,bash] ---- # enclose your pattern with double quotes "" to avoid it to be expanded by your shell prematurely ./convert-junit-assertions-to-assertj.sh "*IT.java" @@ -137,7 +137,7 @@ The order of find/replace is important to benefit from the most relevant AssertJ Find/replace regex: -[source,bash,indent=0] +[source,bash] ---- assertEquals\(0,(.*).size\(\)\); -> assertThat(\1).isEmpty(); ---- @@ -148,7 +148,7 @@ It's better to run this before the `assertEquals` -> `isEqualTo` conversion to a Find/replace regex: -[source,bash,indent=0] +[source,bash] ---- assertEquals\((.*),(.*).size\(\)\); -> assertThat(\2).hasSize(\1); ---- @@ -159,7 +159,7 @@ It's better to run this before the `assertEquals` -> `isEqualTo` conversion to a Find/replace regex: -[source,bash,indent=0] +[source,bash] ---- assertEquals\((.*),(.*)\); -> assertThat(\2).isEqualTo(\1); ---- @@ -168,7 +168,7 @@ assertEquals\((.*),(.*)\); -> assertThat(\2).isEqualTo(\1); Find/replace regex: -[source,bash,indent=0] +[source,bash] ---- assertNull\((.*)\); -> assertThat(\1).isNull(); ---- @@ -177,7 +177,7 @@ assertNull\((.*)\); -> assertThat(\1).isNull(); Find/replace regex: -[source,bash,indent=0] +[source,bash] ---- assertNotNull\((.*)\); -> assertThat(\1).isNotNull(); ---- @@ -186,7 +186,7 @@ assertNotNull\((.*)\); -> assertThat(\1).isNotNull(); Find/replace regex: -[source,bash,indent=0] +[source,bash] ---- assertFalse\((.*)\); -> assertThat(\1).isFalse(); ---- diff --git a/src/docs/asciidoc/user-guide/assertj-core-quickstart.adoc b/src/docs/asciidoc/user-guide/assertj-core-quickstart.adoc index 98ba120..e5d4fbb 100644 --- a/src/docs/asciidoc/user-guide/assertj-core-quickstart.adoc +++ b/src/docs/asciidoc/user-guide/assertj-core-quickstart.adoc @@ -20,7 +20,7 @@ The AssertJ Core artifact can be included directly using its link:#dependency-me ===== Maven -[source,xml,indent=0,subs=attributes+] +[source,xml,subs=attributes+] ---- org.assertj @@ -32,7 +32,7 @@ The AssertJ Core artifact can be included directly using its link:#dependency-me ===== Gradle -[source,groovy,indent=0,subs=attributes+] +[source,groovy,subs=attributes+] ---- testImplementation("org.assertj:assertj-core:{assertj-version}") ---- @@ -52,7 +52,7 @@ The mechanism for changing a dependency version is documented for both https://d With Maven, you can override the AssertJ Core version by including the following in your `pom.xml` file. -[source,xml,indent=0,subs=attributes+] +[source,xml,subs=attributes+] ---- {assertj-version} @@ -61,7 +61,7 @@ With Maven, you can override the AssertJ Core version by including the following With Gradle, you can override the AssertJ Core version by including the following in your `build.gradle` file. -[source,groovy,indent=0,subs=attributes+] +[source,groovy,subs=attributes+] ---- ext['assertj.version'] = '{assertj-version}' ---- @@ -163,14 +163,14 @@ Alternatively your test class can implement `WithAssertions` to access the same One `Assertions` static import to rule them all ... -[source,java,indent=0] +[source,java] ---- import static org.assertj.core.api.Assertions.*; ---- \... or many if you prefer: -[source,java,indent=0] +[source,java] ---- import static org.assertj.core.api.Assertions.assertThat; // main one import static org.assertj.core.api.Assertions.atIndex; // for List assertions @@ -257,7 +257,7 @@ Intellij Idea: No special configuration is needed, just start typing `asser` and Type `assertThat` followed by the object under test and a dot ... and any Java IDE code completion will show you all available assertions. -[source,java,indent=0] +[source,java] ---- assertThat(objectUnderTest). # <1> ---- diff --git a/src/docs/asciidoc/user-guide/assertj-core-release-notes.adoc b/src/docs/asciidoc/user-guide/assertj-core-release-notes.adoc index d267798..f6e6f4c 100644 --- a/src/docs/asciidoc/user-guide/assertj-core-release-notes.adoc +++ b/src/docs/asciidoc/user-guide/assertj-core-release-notes.adoc @@ -2736,7 +2736,7 @@ assertThat(root).isDirectoryRecursivelyContaining(file -> file.getName().equals( Verifies that the binary content of the actual InputStream is exactly equal to the given one. Example: the following failing assertion ... -[source,java,indent=0] +[source,java] ---- InputStream inputStream = new ByteArrayInputStream(new byte[] {1, 2}); @@ -2755,7 +2755,7 @@ assertThat(inputStream).hasBinaryContent(new byte[] {0, 0}); Verifies that the actual group contains the elements of the given iterable only once (same semantic as `containsOnlyOnce(Object...)`). Examples: -[source,java,indent=0] +[source,java] ---- // assertions will pass assertThat(list("winter", "is", "coming")).containsOnlyOnceElementsOf(list("winter")) @@ -2773,7 +2773,7 @@ assertThat(list("Arya", "Stark", "daughter", "of", "Ned", "Stark")).containsOnly Different date/time types can be represented the same way (`LocalDateTime` and `Date` for example) which makes it difficult to understand error messages as they don't show any difference between actual and expected values. AssertJ now adds the date/time type name for types whose representation may collide. Example: the following failing assertion ... -[source,java,indent=0] +[source,java] ---- Date now = new Date(); Object localDateTime = LocalDateTime.ofInstant(now.toInstant(), ZoneId.systemDefault()); @@ -2783,7 +2783,7 @@ assertThat(List.of(localDateTime)).containsExactly(now); \... fails with this error: -[source,indent=0] +[source] ---- Expecting: <[2020-03-19T22:32:42.875 (java.time.LocalDateTime)]> @@ -2796,7 +2796,7 @@ and others were not expected: ---- Before that the error would have been confusing: -[source,indent=0] +[source] ---- Expecting: <[2020-03-19T22:32:42.875]> @@ -2916,7 +2916,7 @@ The following `java.time.Duration` assertions are available: - `isZero()`: Verifies that the actual Duration is `Duration.ZERO`. Examples: -[source,java,indent=0] +[source,java] ---- assertThat(Duration.ofDays(5)).hasDays(5); assertThat(Duration.ofHours(15)).hasHours(15); @@ -2938,7 +2938,7 @@ assertThat(Duration.ZERO).isZero(); Verifies that the actual `Class` is package-private (i.e. has no modifier). Example: -[source,java,indent=0] +[source,java] ---- class MyClass {} @@ -2955,7 +2955,7 @@ assertThat(String.class).isPackagePrivate(); Verifies that the content of the actual file/path is equal to the content of the given one, the comparison is done at the binary level. Example with `Path` (works the same with `File`): -[source,java,indent=0] +[source,java] ---- // The first two paths have the same content, the third does not Path aPath = Files.write(Paths.get("a-file.bin"), new byte[] { 42 }); @@ -2980,7 +2980,7 @@ The time to wait for can be expressed with a `Duration` or a `TimeUnit`. To get assertions for the future result's type use `succeedsWithin` that takes an additional `InstanceOfAssertFactory` parameter. Examples: -[source,java,indent=0] +[source,java] ---- CompletableFuture future = CompletableFuture.completedFuture("ook!"); @@ -3004,7 +3004,7 @@ assertThat(future).succeedsWithin(100, TimeUnit.MILLISECONDS, STRING) Verifies that the actual `Class` has the given superclass. Example: -[source,java,indent=0] +[source,java] ---- // this assertion succeeds: assertThat(Integer.class).hasSuperclass(Number.class); @@ -3028,7 +3028,7 @@ assertThat(String.class).hasSuperclass(Comparable.class); Verifies that the actual `Class` has no superclass. Example: -[source,java,indent=0] +[source,java] ---- // this assertion succeeds as interfaces have no superclass: assertThat(Cloneable.class).hasNoSuperclass(); @@ -3053,7 +3053,7 @@ At the moment, the only assertion available after in the recursive comparison is The recursive comparison API lets you finely control how to compare instances, please consult the <> for a detailed guide. For the following examples we use `Person` and `Doctor`, two classes with the same structure: -[source,java,indent=0] +[source,java] ---- public class Person { String name; @@ -3075,7 +3075,7 @@ Person raj = new Person("Raj Koothrappali", true); ---- `Iterable` example: -[source,java,indent=0] +[source,java] ---- List doctors = list(drSheldon, drLeonard, drRaj); @@ -3087,7 +3087,7 @@ assertThat(doctors).usingRecursiveComparison() ---- Array example: -[source,java,indent=0] +[source,java] ---- Doctor[] doctors = { drSheldon, drLeonard, drRaj }; @@ -3099,7 +3099,7 @@ assertThat(doctors).usingRecursiveComparison() ---- `Map` example: -[source,java,indent=0] +[source,java] ---- Map doctors = mapOf(entry(drSheldon.name, drSheldon), @@ -3116,7 +3116,7 @@ assertThat(doctors).usingRecursiveComparison() ---- `Optional` example: -[source,java,indent=0] +[source,java] ---- Optional doctor = Optional.of(drSheldon); Optional person = Optional.of(sheldon); @@ -3217,7 +3217,7 @@ Add Behavior Driven Development style entry point for assumption methods for dif The difference with the `Assumptions` class is that entry point methods are named `given` instead of `assumeThat`. Example: -[source,java,indent=0] +[source,java] ---- String hobbit = "HOBBIT"; List fellowshipOfTheRing = list("Aragorn", "Gandalf", "Frodo", "Legolas"); @@ -3243,7 +3243,7 @@ public void given_the_assumption_is_met_the_test_is_executed() { Add `hasCharacteristics` and `hasOnlyCharacteristics` assertions for the link:https://docs.oracle.com/javase/8/docs/api/java/util/Spliterator.html?is-external=true[`Spliterator`] type. Example: -[source,java,indent=0] +[source,java] ---- Spliterator spliterator = Stream.of(1, 2, 3).spliterator(); @@ -3261,7 +3261,7 @@ assertThat(spliterator).hasCharacteristics(Spliterator.SIZED, Verifies that actual and given `OffsetDateTime` are at the same `Instant`. Example: -[source,java,indent=0] +[source,java] ---- OffsetDateTime offsetDateTime1 = OffsetDateTime.of(2000, 12, 12, 3, 0, 0, 0, ZoneOffset.ofHours(3)); OffsetDateTime offsetDateTime2 = OffsetDateTime.of(2000, 12, 12, 0, 0, 0, 0, ZoneOffset.ofHours(0)); @@ -3279,7 +3279,7 @@ assertThat(offsetDateTime1).isAtSameInstantAs(offsetDateTime2); `assertAlso` lets you combine other soft assertions instances together. Example: -[source,java,indent=0] +[source,java] ---- Mansion mansion = new Mansion(); @@ -3321,7 +3321,7 @@ void host_dinner_party_where_nobody_dies() { Verify that the actual `File` is empty (i.e. the file size = 0) or not empty (i.e. the file size > 0) . Example: -[source,java,indent=0] +[source,java] ---- File file = File.createTempFile("tmp", "txt"); @@ -3340,7 +3340,7 @@ assertThat(file).isNotEmpty(); Verifies that the size of the `File` under test is exactly equal to the given size in *bytes*. Example: -[source,java,indent=0] +[source,java] ---- File file = File.createTempFile("tmp", "bin"); Files.write(file.toPath(), new byte[] {1, 1}); @@ -3357,7 +3357,7 @@ assertThat(file).hasSize(1); To avoid clash with libraries like Mockito that exposes a static `then(object)` method, you can statically use the `and` field. -[source,java,indent=0] +[source,java] ---- import static org.mockito.BDDMockito.then; // can't use import static org.assertj.core.api.BDDAssertions.then because of BDDMockito.then; @@ -3388,7 +3388,7 @@ public void bdd_assertions_with_bdd_mockito() { Verifies that the message of the root cause of the actual `Throwable` is equal to the given one, a simple `String` or `String.format` is supported to specify the expected root cause message. Example: -[source,java,indent=0] +[source,java] ---- Throwable throwable = new Throwable(new IllegalStateException(new NullPointerException("expected message"))); @@ -3409,7 +3409,7 @@ assertThat(new Throwable()).hasRootCauseMessage("%s %s", "expected", "message"); A syntax sugar to write fluent assertion with methods having an `InstanceOfAssertFactory` parameter. Added as a static method in `Assertions`, it is also available as a default method in the `WithAssertions` interface. Example: -[source,java,indent=0] +[source,java] ---- Jedi yoda = new Jedi("Yoda", "Green"); @@ -3431,7 +3431,7 @@ Extracts the value of given field/property from the object under test, the extra The `InstanceOfAssertFactory` parameter is used to get the assertions narrowed to the factory type. Examples: -[source,java,indent=0] +[source,java] ---- // Create frodo, setting its name, age and Race (Race having a name property) TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT); @@ -3452,7 +3452,7 @@ Uses the given `Function` to extract a value from the object under test, the ext The `InstanceOfAssertFactory` parameter is used to get the assertions narrowed to the factory type. Examples: -[source,java,indent=0] +[source,java] ---- // Create frodo, setting its name, age and Race (Race having a name property) TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT); @@ -3473,7 +3473,7 @@ Extracts the value of given key from the map under test, the extracted value bec The `InstanceOfAssertFactory` parameter is used to get the assertions narrowed to the factory type. Examples: -[source,java,indent=0] +[source,java] ---- Map map = new HashMap<>(); map.put("name", "kawhi"); @@ -3494,7 +3494,7 @@ Verifies that the optional is not `null` and not empty and returns an new assert The `InstanceOfAssertFactory` parameter is used to get the assertions narrowed to the factory type. Examples: -[source,java,indent=0] +[source,java] ---- Optional optional = Optional.of("Frodo"); @@ -3514,7 +3514,7 @@ Navigates and allows to perform assertions on the first element of the `Iterable The `InstanceOfAssertFactory` parameter is used to get the assertions narrowed to the factory type. Examples: -[source,java,indent=0] +[source,java] ---- Iterable hobbits = newArrayList("Frodo", "Sam", "Pippin"); @@ -3537,7 +3537,7 @@ Navigates and allows to perform assertions on the last element of the `Iterable` The `InstanceOfAssertFactory` parameter is used to get the assertions narrowed to the factory type. Examples: -[source,java,indent=0] +[source,java] ---- Iterable hobbits = newArrayList("Frodo", "Sam", "Pippin"); @@ -3560,7 +3560,7 @@ Navigates and allows to perform assertions on the chosen element of the `Iterabl The `InstanceOfAssertFactory` parameter is used to get the assertions narrowed to the factory type. Examples: -[source,java,indent=0] +[source,java] ---- Iterable hobbits = newArrayList("Frodo", "Sam", "Pippin"); @@ -3582,7 +3582,7 @@ assertThat(hobbits).element(1, as(InstanceOfAssertFactories.INTEGER)) Instead of taking a simple `String` the assertions mentioned above now accept a `String.format` like parameters, i.e. `(String description, Object... parameters)` making it easier to build more involved expected strings. Examples: -[source,java,indent=0] +[source,java] ---- Throwable throwableWithMessage = new IllegalArgumentException("wrong amount 123"); @@ -3598,7 +3598,7 @@ assertThat(throwableWithMessage).hasMessageStartingWith("%s a", "wrong") `extracting` is now able to extract a deeply nested map key, before this improvement extracting a value by key was only supported for a `Map` object under test (but not for fields of type `Map`). Let's clarify things with a concrete example: -[source,java,indent=0] +[source,java] ---- Jedi luke = new Jedi(new Name("Luke", "Skywalker"), 26); // setAttribute puts a new entry in 'attributes' Map field @@ -3625,7 +3625,7 @@ assertThat(luke).extracting("name.last", To make it more readable, reformat the error message when multiple combined conditions with `allOf` and `anyOf` fail. Examples: the following assertion will fail ... -[source,java,indent=0] +[source,java] ---- private static Condition contains(String s) { return new Condition<>(value -> value.contains(s), "contains " + s); @@ -3639,7 +3639,7 @@ assertThat("Gandalf").has(anyOf(contains("i"), contains("c"))))); ---- With the following error message -[source,text,indent=0] +[source,text] ---- Expecting: <"Gandalf"> @@ -3663,7 +3663,7 @@ to have: Syntactic sugar to construct a `Condition` using the Hamcrest Matcher given as a parameter. Example: -[source,java,indent=0] +[source,java] ---- import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.HamcrestCondition.matching; @@ -3694,7 +3694,7 @@ Release date: 2019-07-29 This release addresses the 3.13.0 https://github.com/assertj/assertj-core/issues/1563[issue] by which AssertJ required OpenTest4J to be on the classpath otherwise a `java.lang.NoClassDefFoundError: org/opentest4j/MultipleFailuresError` would be raised. Thanks Pascal Schumacher for the quick fix! -[source,text,indent=0] +[source,text] ---- java.lang.NoClassDefFoundError: org/opentest4j/MultipleFailuresError at java.base/java.lang.ClassLoader.defineClass1(Native Method) @@ -3727,7 +3727,7 @@ Release date: 2019-07-28 The highlight of this release is the addition of `asInstanceOf` which allows to chain specific type assertions from a value that was initially declared with a different type (usually `Object`). Thanks Stefano Cordio for this contribution! Example: -[source,java,indent=0] +[source,java] ---- Object value = "abc"; @@ -3753,7 +3753,7 @@ Special thanks to Nils Winkler for his work on the assertions conversion scripts * As the link:#assertj-core-3.13.0-extracting[`extracting(String)`] method for `Object` and `Map` extracts only one value, it now returns `Object` assertions instead of list assertions (on a singleton list). This means that any list assertions used won't compile anymore, they need to be replaced by `Object` assertions. -[source,java,indent=0] +[source,java] ---- // GIVEN Map basketballPlayer = new HashMap<>(); @@ -3828,7 +3828,7 @@ As a consequence of the two previous points, when comparing collection/map field `asInstanceOf` allows to chain specific type assertions from a value initially declared as a less specific type (often `Object`). Let's start with the problem `asInstanceOf` is solving: in the following example we would like to call `String` assertions but this is not possible since `value` is declared as an `Object` thus only `Object` assertions are accessible. -[source,java,indent=0] +[source,java] ---- // Given a String declared as an Object Object value = "Once upon a time in the west"; @@ -3840,7 +3840,7 @@ assertThat(value).startsWith("ab"); // this does not compile ! Thanks to `asInstanceOf` we can now tell AssertJ to consider `value` as a `String` in order to call `String` assertions. To do so we need to pass an `InstanceOfAssertFactory` that can build a `StringAssert`, fortunately you don't have to write it, it is already available in `InstanceOfAssertFactories`! -[source,java,indent=0] +[source,java] ---- import static org.assertj.core.api.InstanceOfAssertFactories.STRING; @@ -3856,7 +3856,7 @@ AssertJ verifies that the actual value is compatible with the assertions `Instan `InstanceOfAssertFactories` provides static factories for all types AssertJ provides assertions for, additional factories can be created with custom `InstanceOfAssertFactory` instances. Here's another example showing the parameterized type support: -[source,java,indent=0] +[source,java] ---- // Actually a List Object hobbits = list(frodo, pippin, merry, sam); @@ -3881,7 +3881,7 @@ assertThat(hobbits).asInstanceOf(InstanceOfAssertFactories.LIST) Extracts the value of given field/property from the object under test, the extracted value becoming the new object under test. Examples: -[source,java,indent=0] +[source,java] ---- // Create frodo, setting its name, age and Race (Race having a name property) TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT); @@ -3904,7 +3904,7 @@ assertThat(frodo).extracting("name") If the object under test is a Map, the parameter is used as a key to the map. Example: -[source,java,indent=0] +[source,java] ---- Map basketballPlayer = new HashMap<>(); basketballPlayer.put("name", "kawhi"); @@ -3928,7 +3928,7 @@ Read <> chapte Verifies that the actual `Throwable` has a cause that refers to the given one, i.e. using == comparison. Example: -[source,java,indent=0] +[source,java] ---- Throwable invalidArgException = new IllegalArgumentException("invalid arg"); Throwable throwable = new Throwable(invalidArgException); @@ -3957,7 +3957,7 @@ Both `isDirectoryContaining` and `isDirectoryNotContaining` accept either `Predi As `File` and `Path` assertions are similar, the examples will only show `File` assertions. The examples use the following directory structure: -[source,text,indent=0] +[source,text] ---- /root/ /root/sub-dir-1/ @@ -3970,7 +3970,7 @@ The examples use the following directory structure: [[assertj-core-3.13.0-isDirectoryContaining]] `isDirectoryContaining` assertions examples: -[source,java,indent=0] +[source,java] ---- File root = new File("root"); @@ -3997,7 +3997,7 @@ assertThat(root).isDirectoryContaining("glob:**.bin"); [[assertj-core-3.13.0-isDirectoryNotContaining]] `isDirectoryNotContaining` assertion examples: -[source,java,indent=0] +[source,java] ---- File root = new File("root"); @@ -4021,7 +4021,7 @@ assertThat(root).isDirectoryNotContaining("glob:**.{ext,bin"); [[assertj-core-3.13.0-isEmptyDirectory]] `isEmptyDirectory` assertion examples: -[source,java,indent=0] +[source,java] ---- File root = new File("root"); @@ -4035,7 +4035,7 @@ assertThat(new File(root, "sub-dir-1")).isEmptyDirectory(); [[assertj-core-3.13.0-isNotEmptyDirectory]] `isNotEmptyDirectory` assertion examples: -[source,java,indent=0] +[source,java] ---- File root = new File("root"); @@ -4053,7 +4053,7 @@ assertThat(new File(root, "sub-dir-1")).isNotEmptyDirectory(); These assertions are the equivalent of `hasMessageContaining` and `hasMessageNotContaining` but accepting multiple String parameters instead of only one. Example: -[source,java,indent=0] +[source,java] ---- Throwable throwableWithMessage = new IllegalArgumentException("wrong amount 123"); Throwable throwableWithoutMessage = new IllegalArgumentException(); @@ -4074,7 +4074,7 @@ assertThat(throwableWithMessage).hasMessageNotContainingAny("foo", "amount"); The same assertions have been added to `ThrowableAssertAlternative` with these names `withMessageContainingAll` and `withMessageNotContainingAny`: -[source,java,indent=0] +[source,java] ---- Throwable illegalArgumentException = new IllegalArgumentException("wrong amount 123"); @@ -4091,7 +4091,7 @@ assertThatExceptionOfType(Throwable.class) The new `check` method catches and collect assertion errors coming from standard and custom assertions. Example: -[source,java,indent=0] +[source,java] ---- SoftAssertions softly = new SoftAssertions(); @@ -4118,7 +4118,7 @@ This is the same assertion as `containsOnly(Map.Entry... entries)`, it simply ha Example : -[source,java,indent=0] +[source,java] ---- Map ringBearers = newLinkedHashMap(entry(oneRing, frodo), entry(nenya, galadriel), @@ -4153,7 +4153,7 @@ If the difference is equal to the offset, the assertion succeeds. Example with `LocalDateTime`: -[source,java,indent=0] +[source,java] ---- LocalDateTime actual = LocalDateTime.now(Clock.systemUTC()); @@ -4165,7 +4165,7 @@ assertThat(actual.plusSeconds(2)).isCloseToUtcNow(within(1, ChronoUnit.SECONDS)) ---- The same example works with `OffsetDateTime` by simply defining `actual` as: -[source,java,indent=0] +[source,java] ---- OffsetDateTime actual = OffsetDateTime.now(Clock.systemUTC()); ---- @@ -4179,7 +4179,7 @@ Here's an example of string following this format: `"2003-04-26T00:00:00.123+00: Example: -[source,java,indent=0] +[source,java] ---- // GIVEN SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS"); @@ -4197,7 +4197,7 @@ The recursive comparison added in 3.12.0 now compares `Optional` values recursiv Example: -[source,java,indent=0] +[source,java] ---- // Song constructor parameters: song, author and coAuthor (optional) Song song = new Song("I Can't Get No Satisfaction", new Author("Mick Jagger"), new Author("Keith Richards")); @@ -4209,7 +4209,7 @@ assertThat(song).usingRecursiveComparison() where `Song` and `Author` don't override `equals`: -[source,java,indent=0] +[source,java] ---- class Song { @@ -4244,7 +4244,7 @@ class Author { If we fail the test \... -[source,java,indent=0] +[source,java] ---- Song song = new Song("I Can't Get No Satisfaction", new Author("Mick Jagger"), new Author("Jimi Hendrix")); Song expectedSong = new Song("I Can't Get No Satisfaction", new Author("Mick Jagger"), new Author("Keith Richards")); @@ -4255,7 +4255,7 @@ assertThat(song).usingRecursiveComparison() \... here's the error reported: -[source,text,indent=0] +[source,text] ---- Expecting: @@ -4282,7 +4282,7 @@ The recursive comparison added in 3.12.0 can now ignore collection order in all Example: -[source,java,indent=0] +[source,java] ---- public class Person { String name; @@ -4314,7 +4314,7 @@ assertThat(sherlock1).usingRecursiveComparison() Example: -[source,java,indent=0] +[source,java] ---- // Old implementation assertThat(yoda).extracting(Jedi::getName) // ObjectAssert @@ -4363,7 +4363,7 @@ Pascal Schumacher, Erhard Pointl, Vladimir Chernikov, Sandra Parsick, Martin Tar WARNING: This removes the previously supported "`Iterable`" assertions (like `containsOnly`), call http://joel-costigliola.github.io/assertj/core-8/api/org/assertj/core/api/AbstractIteratorAssert.html#toIterable--[`IteratorAssert#toIterable`] to access them again, ex: -[source,java,indent=0] +[source,java] ---- Iterator bestBasketBallPlayers = getBestBasketBallPlayers(); diff --git a/src/docs/asciidoc/user-guide/assertj-core.adoc b/src/docs/asciidoc/user-guide/assertj-core.adoc index b9086b5..b8e5efa 100644 --- a/src/docs/asciidoc/user-guide/assertj-core.adoc +++ b/src/docs/asciidoc/user-guide/assertj-core.adoc @@ -15,7 +15,7 @@ http://www.javadoc.io/doc/org.assertj/assertj-core/ is the latest version of Ass Here are a few examples of AssertJ assertions: -[source,java,indent=0] +[source,java] ---- // entry point for all assertThat methods and utility methods (e.g. entry) import static org.assertj.core.api.Assertions.*; diff --git a/src/docs/asciidoc/user-guide/assertj-db-quickstart.adoc b/src/docs/asciidoc/user-guide/assertj-db-quickstart.adoc index a3e32e8..2e19e14 100644 --- a/src/docs/asciidoc/user-guide/assertj-db-quickstart.adoc +++ b/src/docs/asciidoc/user-guide/assertj-db-quickstart.adoc @@ -19,7 +19,7 @@ To quickly start using DataBase assertions, follow the steps below. ===== Maven -[source,xml,indent=0,subs=attributes+] +[source,xml,subs=attributes+] ---- org.assertj @@ -33,7 +33,7 @@ To quickly start using DataBase assertions, follow the steps below. For Gradle users (using the Maven Central Repository) -[source,java,indent=0,subs=attributes+] +[source,java,subs=attributes+] ---- testCompile("org.assertj:assertj-db:{assertj-db-version}") ---- @@ -48,7 +48,7 @@ Check this page to find the relevant http://search.maven.org/#artifactdetails|or Example from {assertj-examples-repo}/blob/main/assertions-examples/src/test/java/org/assertj/examples/db/TableAssertionExamples.java[TableAssertionExamples.java] : -[source,java,indent=0] +[source,java] ---- include::{testDir}/example/db/TableAssertionExamples.java[tags=user_guide] ---- diff --git a/src/docs/asciidoc/user-guide/assertj-guava-quickstart.adoc b/src/docs/asciidoc/user-guide/assertj-guava-quickstart.adoc index 0e23b5f..fec3e0b 100644 --- a/src/docs/asciidoc/user-guide/assertj-guava-quickstart.adoc +++ b/src/docs/asciidoc/user-guide/assertj-guava-quickstart.adoc @@ -15,7 +15,7 @@ The AssertJ Guava artifact can be included directly using its link:#dependency-m ===== Maven -[source,xml,indent=0,subs=attributes+] +[source,xml,subs=attributes+] ---- org.assertj @@ -27,7 +27,7 @@ The AssertJ Guava artifact can be included directly using its link:#dependency-m ===== Gradle -[source,groovy,indent=0,subs=attributes+] +[source,groovy,subs=attributes+] ---- testImplementation("org.assertj:assertj-guava:{assertj-version}") ---- @@ -40,14 +40,14 @@ Check this page to find the relevant https://central.sonatype.dev/artifact/org.a The `org.assertj.guava.api.Assertions` class is the only class you need to start using AssertJ Guava. -[source,java,indent=0] +[source,java] ---- import static org.assertj.guava.api.Assertions.assertThat; ---- ==== Examples -[source,java,indent=0] +[source,java] ---- import static org.assertj.guava.api.Assertions.assertThat; import static org.assertj.guava.api.Assertions.entry; diff --git a/src/docs/asciidoc/user-guide/assertj-guava-release-notes.adoc b/src/docs/asciidoc/user-guide/assertj-guava-release-notes.adoc index 37fc402..ba1b7f2 100644 --- a/src/docs/asciidoc/user-guide/assertj-guava-release-notes.adoc +++ b/src/docs/asciidoc/user-guide/assertj-guava-release-notes.adoc @@ -154,7 +154,7 @@ Thanks to chrisly42 and Stefano Cordio for their contributions! Add factories for `ByteSource`, `Multimap`, `Multiset`, `Optional` (guava) and `Table` to allow to chain specific type assertions from a value initially declared as a less specific type. Let's start with the problem `asInstanceOf` is solving: in the following example we would like to call `Table` assertions but this is not possible since `value` is declared as an `Object` thus only `Object` assertions are accessible. -[source,java,indent=0] +[source,java] ---- // Given a Table declared as an Object Object actual = HashBasedTable. create(); @@ -166,7 +166,7 @@ assertThat(actual).isEmpty(); // this does not compile ! Thanks to `asInstanceOf` we can now tell AssertJ to consider `value` as a `Table` in order to call `Table` assertions. + To do so we need to pass an `InstanceOfAssertFactory` that can build a `TableAssert`, fortunately you don't have to write it, it is already available in `InstanceOfAssertFactories`! -[source,java,indent=0] +[source,java] ---- // Given a Table declared as an Object Object actual = HashBasedTable. create(); diff --git a/src/docs/asciidoc/user-guide/assertj-joda-quickstart.adoc b/src/docs/asciidoc/user-guide/assertj-joda-quickstart.adoc index 170c225..ccfe0f5 100644 --- a/src/docs/asciidoc/user-guide/assertj-joda-quickstart.adoc +++ b/src/docs/asciidoc/user-guide/assertj-joda-quickstart.adoc @@ -18,7 +18,7 @@ AssertJ Joda Time major versions depend on different Java versions: ===== Maven -[source,xml,indent=0,subs=attributes+] +[source,xml,subs=attributes+] ---- org.assertj @@ -33,14 +33,14 @@ AssertJ Joda Time major versions depend on different Java versions: For Gradle users (using the Maven Central Repository) -[source,java,indent=0,subs=attributes+] +[source,java,subs=attributes+] ---- testImplementation("org.assertj:assertj-joda-time:{assertj-joda-time-version}") ---- Or version 1.1.0 for Java 7 projects -[source,java,indent=0] +[source,java] ---- testImplementation("org.assertj:assertj-joda-time:1.1.0") ---- @@ -53,14 +53,14 @@ Check this page to find the relevant https://search.maven.org/artifact/org.asser The `org.assertj.jodatime.api.Assertions` class is the only class you need to start using AssertJ Joda Time. -[source,java,indent=0] +[source,java] ---- import static org.assertj.jodatime.api.Assertions.assertThat; ---- ==== Examples -[source,java,indent=0] +[source,java] ---- assertThat(dateTime).isBefore(firstDateTime); assertThat(dateTime).isAfterOrEqualTo(secondDateTime); @@ -77,7 +77,7 @@ assertThat(dateTime1).isEqualToIgnoringSeconds(dateTime2); For `DateTime` assertions, comparison is performed in the `DateTimeZone` of `DateTime` to test, consequently the following assertion passes: -[source,java,indent=0] +[source,java] ---- DateTime utcTime = new DateTime(2013, 6, 10, 0, 0, DateTimeZone.UTC); DateTime cestTime = new DateTime(2013, 6, 10, 2, 0, DateTimeZone.forID("Europe/Berlin")); diff --git a/src/docs/asciidoc/user-guide/assertj-joda-release-notes.adoc b/src/docs/asciidoc/user-guide/assertj-joda-release-notes.adoc index 777015f..6edbbf2 100644 --- a/src/docs/asciidoc/user-guide/assertj-joda-release-notes.adoc +++ b/src/docs/asciidoc/user-guide/assertj-joda-release-notes.adoc @@ -38,7 +38,7 @@ Add `LocalDate` assertions providing the following ones (Eugene Strepetov): The assertions taking `String` parameter(s) can be used with `LocalDate` String representation: `yyyy-MM-dd`. Examples: -[source,java,indent=0] +[source,java] ---- LocalDate localDate = new LocalDate(2000, 1, 1); @@ -92,7 +92,7 @@ Add `LocalDateTime` assertions providing the following ones (John Killmer): - `hasMillisOfSecond`: Verifies that the milliseconds of the actual LocalDateTime is equal to the given milliseconds Examples: -[source,java,indent=0] +[source,java] ---- DateTime dateTime = new DateTime(1999, 12, 31, 23, 59, 59, 999, DateTimeZone.UTC);