### Custom Configuration Output Example Source: https://assertj.github.io/doc/#assertj-swing An example of the output displayed by AssertJ when interacting with the system after applying the custom configuration. This shows the applied settings. ```text Applying configuration example.core.CustomConfiguration - representation .................................. = BinaryRepresentation - comparingPrivateFieldsEnabled ................... = false - extractingPrivateFieldsEnabled ................... = true - bareNamePropertyExtractionEnabled ............... = false - lenientDateParsingEnabled ....................... = true - additionnal date formats ........................ = [yyyy_MM_dd, yyyy|MM|dd] - maxLengthForSingleLineDescription ............... = 150 - maxElementsForPrinting .......................... = 2000 - removeAssertJRelatedElementsFromStackTraceEnabled = true ``` -------------------------------- ### AssertJ Configuration Output Example Source: https://assertj.github.io/doc/index.html An example of the output generated by AssertJ when a custom configuration is applied, showing the applied configuration class and its settings. ```text Applying configuration example.core.CustomConfiguration - representation .................................. = BinaryRepresentation - comparingPrivateFieldsEnabled ................... = false - extractingPrivateFieldsEnabled .................. = true - bareNamePropertyExtractionEnabled ............... = false - lenientDateParsingEnabled ....................... = true - additionnal date formats ........................ = [yyyy_MM_dd, yyyy|MM|dd] - maxLengthForSingleLineDescription ............... = 150 - maxElementsForPrinting .......................... = 2000 - removeAssertJRelatedElementsFromStackTraceEnabled = true ``` -------------------------------- ### Navigate to value at start point of a column Source: https://assertj.github.io/doc/#assertj-swing Use `valueAtStartPoint()` when the origin is a column to navigate to the value at the start of that column's context. ```java assertThat(changes).change().column().valueAtStartPoint()... ``` -------------------------------- ### IDE Code Completion Example Source: https://assertj.github.io/doc/#assertj-swing Illustrates how to use IDE code completion after typing 'assertThat(objectUnderTest).' to discover available assertions. ```java assertThat(objectUnderTest). __**(1)** ``` -------------------------------- ### Mockito and AssertJ Integration Example Source: https://assertj.github.io/doc/#assertj-swing Demonstrates how to use AssertJ's `and.then()` in conjunction with Mockito's `then()` to avoid naming conflicts. ```java Person person = mock(Person.class); // WHEN person.ride(bike); person.ride(bike); // THEN // mockito then() then(person).should(times(2)).ride(bike); // use AssertJ and.then(person) as then(person) would clash with mockito then(person) and.then(person.hasBike()).isTrue(); ``` -------------------------------- ### Example Usage of Custom Soft Assertions Entry Point Source: https://assertj.github.io/doc/index.html Demonstrates how to use a custom soft assertions entry point for TolkienCharacter assertions. This requires a pre-defined TolkienSoftAssertions class. ```java TolkienSoftAssertions softly = new TolkienSoftAssertions(); softly.assertThat(frodo).hasRace(HOBBIT) .hasName("Frodo"); ``` -------------------------------- ### Failing Assertion with Custom Example Type Source: https://assertj.github.io/doc/#assertj-swing Demonstrates a failing assertion where the custom representation formats an 'Example' object. ```java assertThat(new Example()).isNull(); ``` -------------------------------- ### Custom Configuration Class Example Source: https://assertj.github.io/doc/#assertj-swing Example of a custom AssertJ Configuration class that overrides default behaviors for representation, field extraction, date parsing, and printing limits. This class should be placed in your project's source code. ```java package example.core; import static org.assertj.core.presentation.BinaryRepresentation.BINARY_REPRESENTATION; import static org.assertj.core.util.Lists.list; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.List; import org.assertj.core.configuration.Configuration; import org.assertj.core.presentation.Representation; class CustomConfiguration extends Configuration { private static final SimpleDateFormat DATE_FORMAT1 = new SimpleDateFormat("yyyy_MM_dd"); private static final SimpleDateFormat DATE_FORMAT2 = new SimpleDateFormat("yyyy|MM|dd"); // we keep the default behavior for extractingPrivateFieldsEnabled since it is not overridden @Override public Representation representation() { return BINARY_REPRESENTATION; } @Override public boolean bareNamePropertyExtractionEnabled() { return false; } @Override public boolean comparingPrivateFieldsEnabled() { return false; } @Override public boolean lenientDateParsingEnabled() { return true; } @Override public List additionalDateFormats() { return list(DATE_FORMAT1, DATE_FORMAT2); } @Override public int maxElementsForPrinting() { return 2000; } @Override public int maxLengthForSingleLineDescription() { return 150; } } ``` -------------------------------- ### Custom Soft Assertions Entry Point Example Source: https://assertj.github.io/doc/#assertj-swing Define custom soft assertion entry points by extending SoftAssertionsProvider and providing default assertThat methods for your custom assertion classes. ```java public interface TolkienSoftAssertionsProvider extends SoftAssertionsProvider { // custom assertions default TolkienCharacterAssert assertThat(TolkienCharacter actual) { return proxy(TolkienCharacterAssert.class, TolkienCharacter.class, actual); } } // let's add a Game of Thrones entry point public interface GoTSoftAssertionsProvider extends SoftAssertionsProvider { // custom assertions default GoTCharacterAssert assertThat(GoTCharacter actual) { return proxy(GoTCharacterAssert.class, GoTCharacter.class, actual); } } ``` -------------------------------- ### Navigate to Row Start and End Points Source: https://assertj.github.io/doc/#assertj-swing Use `rowAtStartPoint()` to navigate to the beginning of a row and `rowAtEndPoint()` to navigate to the end. These methods can be chained. ```java assertThat(changes).change().rowAtStartPoint()... ``` ```java assertThat(changes).change().rowAtStartPoint().rowAtEndPoint()... ``` -------------------------------- ### Navigate to the first value from a row Source: https://assertj.github.io/doc/#assertj-swing Use `value()` to navigate to the first value when starting from a row. This is the initial call in a sequence. ```java assertThat(changes).change().rowAtEndPoint().value()... ``` -------------------------------- ### Custom Assertions Entry Point Class Source: https://assertj.github.io/doc/#assertj-swing Create a class with static `assertThat` methods for each custom assertion type to provide easy access. This example shows how to provide assertions for `TolkienCharacter` and `Race`. ```java public class MyProjectAssertions { // give access to TolkienCharacter assertion public static TolkienCharacterAssert assertThat(TolkienCharacter actual) { return new TolkienCharacterAssert(actual); } // give access to TolkienCharacter Race assertion public static RaceAssert assertThat(Race actual) { return new RaceAssert(actual); } } ``` -------------------------------- ### Failing Directory Content Assertions Source: https://assertj.github.io/doc/#assertj-swing Examples of directory content assertions that are expected to fail, demonstrating incorrect usage. ```java File root = new File("root"); // The following assertions fail: assertThat(root).isDirectoryContaining(file -> file.getName().startsWith("dir")); assertThat(root).isDirectoryContaining(file -> file.getName().endsWith(".bin")); assertThat(root).isDirectoryContaining("glob:**dir"); assertThat(root).isDirectoryContaining("glob:**.bin"); ``` -------------------------------- ### Navigate Column from Row Source: https://assertj.github.io/doc/#assertj-swing Navigate to the first column starting from a specific row. ```java assertThat(tableOrRequest).row(2).column()... ``` -------------------------------- ### Assertion Example with Custom Representations Source: https://assertj.github.io/doc/#assertj-swing Demonstrates an assertion that fails due to different custom representations for Hobbit and Jedi objects. ```java Hobbit frodo = new Hobbit(); frodo.name = "Frodo"; frodo.age = "33"; Jedi luke = new Jedi(); luke.name = "Luke"; luke.age = "23"; assertThat(frodo).isEqualTo(luke); ``` -------------------------------- ### AssertJ DB Database Assertions Example Source: https://assertj.github.io/doc/#assertj-swing Demonstrates checking column values and row values using AssertJ-DB. Requires static import of assertThat and creation of an AssertDbConnection. ```java // From v3.0.2 import static org.assertj.core.api.Assertions.assertThat; // For versions <= 3.0.1 : // import static org.assertj.db.api.Assertions.assertThat; import org.assertj.db.type.AssertDbConnection; import org.assertj.db.type.AssertDbConnectionFactory; import org.assertj.db.type.DateValue; import org.assertj.db.type.Table; private AssertDbConnection assertDbConnection = AssertDbConnectionFactory.of("jdbc:h2:mem:test", "sa", "").create(); Table table = assertDbConnection.table("members").build(); // Check column "name" values assertThat(table).column("name") .value().isEqualTo("Hewson") .value().isEqualTo("Evans") .value().isEqualTo("Clayton") .value().isEqualTo("Mullen"); // Check row at index 1 (the second row) values assertThat(table).row(1) .value().isEqualTo(2) .value().isEqualTo("Evans") .value().isEqualTo("David Howell") .value().isEqualTo("The Edge") .value().isEqualTo(DateValue.of(1961, 8, 8)) .value().isEqualTo(1.77); ``` -------------------------------- ### Basic AssertJ Joda Time Assertions Source: https://assertj.github.io/doc/#assertj-swing Examples of basic AssertJ Joda Time assertions for comparing `DateTime` objects. ```java assertThat(dateTime).isBefore(firstDateTime); assertThat(dateTime).isAfterOrEqualTo(secondDateTime); ``` -------------------------------- ### Equivalent Navigation to Creation Change Source: https://assertj.github.io/doc/#assertj-swing Demonstrates an equivalent way to navigate to the first creation change within deletion changes by explicitly including 'ofAll'. ```java assertThat(changes).ofDeletion().ofAll().changeOfCreation()... ``` -------------------------------- ### Getting Optional Value with `as(InstanceOfAssertFactories.STRING)` Source: https://assertj.github.io/doc/#assertj-swing Asserts an Optional contains a String and chains assertions on the value using `get(as(InstanceOfAssertFactories.STRING))`. ```java Optional optional = Optional.of("Frodo"); // The following assertion will succeed: assertThat(optional).get(as(InstanceOfAssertFactories.STRING)) .startsWith("Fro"); // The following assertion will fail as the value is not an Integer: ``` -------------------------------- ### Using Combined Soft Assertions Source: https://assertj.github.io/doc/#assertj-swing Instantiate the concrete entry point class and use its methods to perform custom and standard soft assertions, followed by a call to assertAll() to verify all collected assertions. ```java FantasySoftAssertions softly = new FantasySoftAssertions(); // custom TolkienCharacter assertions softly.assertThat(frodo).hasRace(HOBBIT); // custom GoTCharacter assertions softly.assertThat(nedStark).isDead(); // standard assertions softly.assertThat("Games of Thrones").startsWith("Games") .endsWith("Thrones"); // verify assertions softly.assertAll(); ``` -------------------------------- ### Assert column values for a change (start and end) Source: https://assertj.github.io/doc/#assertj-swing Verifies the values of a column within a change, specifying the expected values at the start and end points of the change. ```java assertThat(changes).change().column().hasValues(false, true); ``` -------------------------------- ### Equivalent Row Navigation Sequences Source: https://assertj.github.io/doc/index.html Demonstrates equivalent navigation sequences, showing how `returnToChange()` can be implicitly handled when chaining `rowAtStartPoint()` and `rowAtEndPoint()`. ```java // Navigate to the first change // Navigate to the row at start point // Return to the change from this column // Navigate to the row at end point assertThat(changes).change().rowAtStartPoint().returnToChange().rowAtEndPoint()... ``` ```java // The same thing is done but the return to the change is implicit assertThat(changes).change().rowAtStartPoint().rowAtEndPoint()... ``` -------------------------------- ### Recursive Field Assertion Example Source: https://assertj.github.io/doc/#assertj-swing Demonstrates using `allFieldsSatisfy` to recursively check if all fields in an object graph are non-null. This example sets up Author and Book objects and asserts that all their fields are not null. ```java class Author { String name; String email; List books = new ArrayList<>(); Author(String name, String email) { this.name = name; this.email = email; } } class Book { String title; Author[] authors; Book(String title, Author[] authors) { this.title = title; this.authors = authors; } } Author pramodSadalage = new Author("Pramod Sadalage", "p.sadalage@recursive.test"); Author martinFowler = new Author("Martin Fowler", "m.fowler@recursive.test"); Author kentBeck = new Author("Kent Beck", "k.beck@recursive.test"); Book noSqlDistilled = new Book("NoSql Distilled", new Author[] {pramodSadalage, martinFowler}); pramodSadalage.books.add(noSqlDistilled); martinFowler.books.add(noSqlDistilled); Book refactoring = new Book("Refactoring", new Author[] {martinFowler, kentBeck}); martinFowler.books.add(refactoring); kentBeck.books.add(refactoring); // assertion succeeds assertThat(pramodSadalage).usingRecursiveAssertion() .allFieldsSatisfy(field -> field != null); ``` -------------------------------- ### Concrete Entry Point Combining Custom Assertions Source: https://assertj.github.io/doc/#assertj-swing Create a concrete entry point class that implements multiple custom SoftAssertionsProvider interfaces and extends AbstractSoftAssertions (or SoftAssertions for standard assertions) to combine all assertion types. ```java // we extend SoftAssertions to get standard soft assertions public class FantasySoftAssertions extends SoftAssertions implements TolkienSoftAssertionsProvider, GoTSoftAssertionsProvider { // we can even add more assertions here public HumanAssert assertThat(Human actual) { return proxy(HumanAssert.class, Human.class, actual); } } ``` -------------------------------- ### Class static assertions Source: https://assertj.github.io/doc/#assertj-swing Asserts whether a class is static or not. No specific setup is required. ```java class MyClass { static class MyStaticClass {} } assertThat(MyClass.class).isNotStatic(); assertThat(MyStaticClass.class).isStatic(); ``` -------------------------------- ### Assert Row Existence in Change Source: https://assertj.github.io/doc/#assertj-swing Verify the existence of a row at the start or end point of a change. ```java assertThat(changes).change().rowAtStartPoint().exists(); ``` ```java assertThat(changes).change().rowAtEndPoint().doesNotExist(); ``` -------------------------------- ### Navigate Column by Index from Row Source: https://assertj.github.io/doc/#assertj-swing Navigate to a specific column by index starting from a specific row. ```java assertThat(tableOrRequest).row(2).column(3)... ``` -------------------------------- ### Navigate to Next Change Source: https://assertj.github.io/doc/#assertj-swing Use `change()` to navigate to the next change. It can be chained to move through subsequent changes. ```java assertThat(changes).change()... ``` ```java assertThat(changes).change().change()... ``` -------------------------------- ### Get Integer from Optional Assertion Source: https://assertj.github.io/doc/#assertj-swing Retrieves an Integer from an Optional and asserts it is zero. Requires AssertJ Core. ```java assertThat(optional).get(as(InstanceOfAssertFactories.INTEGER)) .isZero(); ``` -------------------------------- ### Using `as(InstanceOfAssertFactory)` with Jedi Object Extraction Source: https://assertj.github.io/doc/#assertj-swing Demonstrates using the `as(InstanceOfAssertFactory)` syntax sugar for fluent assertions on extracted Jedi properties. ```java Jedi yoda = new Jedi("Yoda", "Green"); assertThat(yoda).extracting(Jedi::getName, as(InstanceOfAssertFactories.STRING)) .startsWith("Yo"); ``` -------------------------------- ### Table Assertions Source: https://assertj.github.io/doc/index.html Examples for asserting properties of Guava Table, such as size, row/column counts, and specific cell values. ```java // Table assertions Table bestMovies = HashBasedTable.create(); bestMovies.put(1970, "Palme d'Or", "M.A.S.H"); bestMovies.put(1994, "Palme d'Or", "Pulp Fiction"); bestMovies.put(2008, "Palme d'Or", "Entre les murs"); bestMovies.put(2000, "Best picture Oscar", "American Beauty"); bestMovies.put(2011, "Goldener Bär", "A Separation"); assertThat(bestMovies).hasRowCount(5).hasColumnCount(3).hasSize(5) .containsValues("American Beauty", "A Separation", "Pulp Fiction") .containsCell(1994, "Palme d'Or", "Pulp Fiction") .containsColumns("Palme d'Or", "Best picture Oscar", "Goldener Bär") .containsRows(1970, 1994, 2000, 2008, 2011); ``` -------------------------------- ### Navigate to All Changes Source: https://assertj.github.io/doc/#assertj-swing Use `ofAll()` to access all recorded changes, regardless of table or type. ```java assertThat(changes).ofAll()... ``` -------------------------------- ### Output Table Content as HTML Source: https://assertj.github.io/doc/#assertj-swing Changes the output type for a table to HTML. This is an example of customizing the output format. ```java // Change the output of the table to be HTML output(table).withType(OutputType.HTML).....; ``` -------------------------------- ### Output Table Content to Console and File Source: https://assertj.github.io/doc/#assertj-swing Demonstrates fluent chaining to output table content as plain text to the console and as HTML to a file. Shows flexibility in combining output types and destinations. ```java // Display the content of the table with plain text in the console // and with HTML output in the file output(table).toConsole().withType(OutputType.HTML).toFile("test.html"); ``` -------------------------------- ### Failing Directory Not Containing Assertions Source: https://assertj.github.io/doc/#assertj-swing Examples of directory not containing assertions that are expected to fail, demonstrating incorrect usage. ```java File root = new File("root"); // The following assertions fail: assertThat(root).isDirectoryContaining(file -> file.getName().startsWith("dir")); assertThat(root).isDirectoryContaining(file -> file.getName().endsWith(".bin")); assertThat(root).isDirectoryNotContaining("glob:**sub-dir*"); assertThat(root).isDirectoryNotContaining("regex:.*ext"); assertThat(root).isDirectoryNotContaining("glob:**.{ext,bin"); ``` -------------------------------- ### Basic String Assertions Source: https://assertj.github.io/doc/#assertj-swing Demonstrates basic string assertions like isNotNull, startsWith, contains, and endsWith. Statically import assertThat for use. Assertions can be chained. ```java import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; public class SimpleAssertionsExample { @Test void a_few_simple_assertions() { assertThat("The Lord of the Rings").isNotNull() .startsWith("The") .contains("Lord") .endsWith("Rings"); } } ``` -------------------------------- ### Asserting Future Success Source: https://assertj.github.io/doc/#assertj-swing Asserts that a future completes successfully within a specified time and starts with a given string. ```java assertThat(future).succeedsWithin(100, TimeUnit.MILLISECONDS, STRING) .startsWith("oo"); ``` -------------------------------- ### Chain Navigation to All Changes Source: https://assertj.github.io/doc/#assertj-swing Chain `ofCreation()` and `ofAll()` to first filter by creation changes and then retrieve all of them. ```java assertThat(changes).ofCreation().ofAll()... ``` -------------------------------- ### Integer Even/Odd Assertions Source: https://assertj.github.io/doc/#assertj-swing Verifies if a byte, short, int, or long is even or odd. No specific setup is required. ```java assertThat(12).isEven(); assertThat(-46).isEven(); assertThat(3).isOdd(); assertThat(-17).isOdd(); ``` -------------------------------- ### Configure AssertDbConnection with Custom LetterCase Source: https://assertj.github.io/doc/#assertj-swing Demonstrates creating two equivalent AssertDbConnection instances. The second instance is configured with custom LetterCase settings for table, column, and primary key names, showing how to override default behavior. ```java AssertDbConnection jdbcConnection = AssertDbConnectionFactory.of("jdbc:h2:mem:test", "sa", "").create(); Table table = jdbcConnection.table("members").build(); LetterCase tableLetterCase = LetterCase.getLetterCase(CaseConversions.NO, CaseComparisons.IGNORE); LetterCase columnLetterCase = LetterCase.getLetterCase(CaseConversions.UPPER, CaseComparisons.IGNORE); LetterCase pkLetterCase = LetterCase.getLetterCase(CaseConversions.UPPER, CaseComparisons.IGNORE); AssertDbConnection connectionWithLC = AssertDbConnectionFactory.of("jdbc:h2:mem:test", "sa", "") .letterCase(tableLetterCase, columnLetterCase, pkLetterCase) .create(); Table tableWithLC = connectionWithLC.table("members").build(); ``` -------------------------------- ### Navigate to Row at Start/End Point Source: https://assertj.github.io/doc/index.html Use `rowAtStartPoint()` to navigate to the row at the beginning of a change and `rowAtEndPoint()` for the row at the end. These methods can be chained. ```java // Navigate to the row at the start point assertThat(changes).change().rowAtStartPoint()... ``` ```java // Navigate to the row at the end point (note that the methods can be chained) assertThat(changes).change().rowAtStartPoint().rowAtEndPoint()... ``` -------------------------------- ### Asserting Exception Type Mismatch Source: https://assertj.github.io/doc/index.html This example demonstrates a failing assertion where the thrown exception type does not match the expected RuntimeException. ```java assertThatRuntimeException().isThrownBy(() -> { throw new IOException(); }) ``` -------------------------------- ### Navigate to Creation Changes Source: https://assertj.github.io/doc/#assertj-swing Use `ofCreation()` to access changes related to the creation of entities. ```java assertThat(changes).ofCreation()... ``` -------------------------------- ### Implicit Return to Change Navigation Source: https://assertj.github.io/doc/#assertj-swing Demonstrates equivalent navigation paths, showing that returning to the change can be implicit when chaining row navigation methods. ```java assertThat(changes).change().rowAtStartPoint().returnToChange().rowAtEndPoint()... ``` ```java assertThat(changes).change().rowAtStartPoint().rowAtEndPoint()... ``` -------------------------------- ### Executing Migration Script with Custom Pattern Source: https://assertj.github.io/doc/#assertj-swing Shows how to specify a custom file pattern as an argument to the assertion migration script, allowing it to process files other than the default `*Test.java`. ```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" ``` -------------------------------- ### Start Assertion on Table or Request Source: https://assertj.github.io/doc/#assertj-swing Use assertThat(tableOrRequest) to begin an assertion on a Table or Request. This is the entry point for all navigation. ```java assertThat(tableOrRequest)... ``` -------------------------------- ### Navigate to Next Change of Creation Source: https://assertj.github.io/doc/#assertj-swing Use `changeOfCreation()` to navigate to the next change of creation. Chaining is supported. ```java assertThat(changes).changeOfCreation()... ``` ```java assertThat(changes).changeOfCreation().changeOfCreation()... ``` -------------------------------- ### Chain various navigation methods including by column name Source: https://assertj.github.io/doc/#assertj-swing Demonstrates chaining multiple navigation methods, including `value(String columnName)` and `value()` and `value(int index)`, to reach a desired value. ```java assertThat(changes).change().rowAtEndPoint().value("surname").value().value(6).value("id")... ``` -------------------------------- ### Navigate to first element with strongly typed String assertions Source: https://assertj.github.io/doc/#assertj-swing Use `first(as(STRING))` to navigate to the first element and apply strongly typed String assertions. Requires `InstanceOfAssertFactories.STRING`. ```java // strongly typed String assertions after navigation Iterable hobbitsName = list("frodo", "sam", "pippin"); // STRING is an InstanceOfAssertFactory from org.assertj.core.api.InstanceOfAssertFactories.STRING // as() is just synthetic sugar for readability assertThat(hobbitsName).first(as(STRING)) .startsWith("fro") .endsWith("do"); ``` -------------------------------- ### Equivalent Navigation with Implicit Return Source: https://assertj.github.io/doc/#assertj-swing Shows an equivalent navigation sequence where returning to the origin changes is implicit. This simplifies chained navigation calls. ```java assertThat(changes).change().change()... ``` -------------------------------- ### Import AssertJ Guava Assertions Class Source: https://assertj.github.io/doc/#assertj-swing Import the static Assertions class from AssertJ Guava to start using its assertion methods. ```java import static org.assertj.guava.api.Assertions.assertThat; ``` -------------------------------- ### Combine AssertJ Conditions Source: https://assertj.github.io/doc/#assertj-swing Shows how to combine multiple conditions using logical AND (allOf) and OR (anyOf), and how to negate conditions using 'not'. ```java List SITHS = list("Sidious", "Vader", "Plagueis"); Condition sith = new Condition<>(SITHS::contains, "sith"); assertThat("Vader").is(anyOf(jedi, sith)); assertThat("Solo").is(allOf(not(jedi), not(sith))); ``` -------------------------------- ### Get LetterCase Instance Source: https://assertj.github.io/doc/#assertj-swing Creates a LetterCase instance with specified CaseConversion and CaseComparison modes. This is used to define how database object names are handled. ```java LetterCase letterCase = LetterCase.getLetterCase(CaseConversions.NO, CaseComparisons.IGNORE); ``` -------------------------------- ### Import Assertions Class for AssertJ Joda Time Source: https://assertj.github.io/doc/#assertj-swing Import the `Assertions` class from `org.assertj.jodatime.api` to start using AssertJ Joda Time assertions. ```java import static org.assertj.jodatime.api.Assertions.assertThat; ``` -------------------------------- ### Build a Table Object Source: https://assertj.github.io/doc/#assertj-swing Construct a Table object representing a database table using the table builder. This is the basic setup for interacting with a table. ```java // Prepare the connection AssertDbConnection connection = ... // Declare the "members" table by using a AssertDbConnection table builder Table table1 = connection.table("members").build(); ``` -------------------------------- ### Instantiating Current Date, Time, and DateTime Values with 'now' Source: https://assertj.github.io/doc/#assertj-swing Use the 'now' static methods (since 1.1.0) to create DateValue, TimeValue, and DateTimeValue instances representing the current date, time, or date/time. ```java DateValue dateValue = DateValue.now(); // The current date TimeValue timeValue = TimeValue.now(); // The current time DateTimeValue dateTimeValue = DateTimeValue.now(); // The current date/time ``` -------------------------------- ### META-INF/services Configuration File Source: https://assertj.github.io/doc/#assertj-swing The content of the 'org.assertj.core.configuration.Configuration' file within the 'META-INF/services' directory. This file tells AssertJ which custom configuration class to load. ```properties example.core.CustomConfiguration ``` -------------------------------- ### Root Assertion on Changes Source: https://assertj.github.io/doc/#assertj-swing Use this to start assertions on database changes. Import `assertThat` from `org.assertj.core.api.Assertions` for versions 3.0.2 and later, or from `org.assertj.db.api.Assertions` for earlier versions. ```java // From v3.0.2 import static org.assertj.core.api.Assertions.assertThat; // For versions <= 3.0.1 : // import static org.assertj.db.api.Assertions.assertThat; assertThat(changes)... ``` -------------------------------- ### Using BDDAssertions for BDD Style Source: https://assertj.github.io/doc/#assertj-swing Utilize BDDAssertions with the 'then' entry point for Behavior-Driven Development style assertions. Requires a static import for 'then'. ```java import static org.assertj.core.api.BDDAssertions.then; public class BDDAssertionsExamples extends AbstractAssertionsExamples { // the data used are initialized in AbstractAssertionsExamples. @Test public void withAssertions_examples() { // then methods come from BDDAssertions.then static then(frodo.age).isEqualTo(33); then(frodo.getName()).isEqualTo("Frodo").isNotEqualTo("Frodon"); then(frodo).isIn(fellowshipOfTheRing); then(frodo).isIn(sam, frodo, pippin); then(sauron).isNotIn(fellowshipOfTheRing); then(frodo).matches(p -> p.age > 30 && p.getRace() == HOBBIT); then(frodo.age).matches(p -> p > 30); } } ``` -------------------------------- ### Root Assertion on Request Source: https://assertj.github.io/doc/#assertj-swing Use this to start assertions on a database request. Import `assertThat` from `org.assertj.core.api.Assertions` for versions 3.0.2 and later, or from `org.assertj.db.api.Assertions` for earlier versions. ```java // From v3.0.2 import static org.assertj.core.api.Assertions.assertThat; // For versions <= 3.0.1 : // import static org.assertj.db.api.Assertions.assertThat; assertThat(request)... ``` -------------------------------- ### Instantiating Date, Time, and DateTime Values with 'parse' Source: https://assertj.github.io/doc/#assertj-swing Use the 'parse' static methods to create DateValue, TimeValue, and DateTimeValue instances by parsing String representations. This method can throw a ParseException. ```java DateValue dateValue = DateValue.parse("2007-12-23"); // With hours and minutes only TimeValue timeValue1 = TimeValue.parse("09:01"); // With seconds additional TimeValue timeValue2 = TimeValue.parse("09:01:06"); // With nanoseconds additional TimeValue timeValue3 = TimeValue.parse("09:01:06.000000003"); // With date only (so hour is midnight) DateTimeValue dateTimeValue1 = DateTimeValue.parse("2007-12-23"); // With date and time (hours and minutes only) DateTimeValue dateTimeValue2 = DateTimeValue.parse("2007-12-23T09:01"); // With date and time (seconds additional) DateTimeValue dateTimeValue2 = DateTimeValue.parse("2007-12-23T09:01:06"); // With date and time (nanoseconds additional) DateTimeValue dateTimeValue2 = DateTimeValue.parse("2007-12-23T09:01:06.000000003"); ``` -------------------------------- ### Root Assertion on Table Source: https://assertj.github.io/doc/#assertj-swing Use this to start assertions on a database table. Import `assertThat` from `org.assertj.core.api.Assertions` for versions 3.0.2 and later, or from `org.assertj.db.api.Assertions` for earlier versions. ```java // From v3.0.2 import static org.assertj.core.api.Assertions.assertThat; // For versions <= 3.0.1 : // import static org.assertj.db.api.Assertions.assertThat; assertThat(table)... ``` -------------------------------- ### Return to Request from Column Source: https://assertj.github.io/doc/#assertj-swing Use `returnToRequest()` to navigate back to the request origin from a column. ```java assertThat(request).column().returnToRequest()... ``` -------------------------------- ### CharSequence startsWithIgnoringCase assertion Source: https://assertj.github.io/doc/#assertj-swing Checks if a CharSequence starts with a specified prefix, ignoring case differences. This is one of several new ignoring case variants. ```java assertThat("Gandalf the grey").startsWithIgnoringCase("gandalf") ``` -------------------------------- ### Custom Assertion Construct with assertWith Source: https://assertj.github.io/doc/#assertj-swing Uses a given instance as the object under test for all assertions within a Consumer. This helps avoid repeating the setup for the instance being tested. ```java assertWith(team.getPlayers().get(0).getStats(), stats -> { assertThat(stats.pointPerGame).isGreaterThan(25.7); assertThat(stats.assistsPerGame).isGreaterThan(7.2); assertThat(stats.reboundsPerGame).isBetween(9, 12); }); ``` -------------------------------- ### Navigate to Change by Index Source: https://assertj.github.io/doc/#assertj-swing Use `change(int index)` to navigate to a specific change by its index. Chaining is supported. ```java assertThat(changes).change().change(2)... ``` ```java assertThat(changes).change(6).change()... ``` -------------------------------- ### Navigate to a value using column name from a row Source: https://assertj.github.io/doc/#assertj-swing Use `value(String columnName)` to navigate to the value within the column identified by its name. Case-insensitivity is implied by the example. ```java assertThat(changes).change().rowAtEndPoint().value("surname")... ``` -------------------------------- ### isEmptyFile and isNotEmptyFile Assertions Source: https://assertj.github.io/doc/#assertj-swing Verifies if a Path points to an empty or non-empty regular file. The Path must exist and be a regular file for these assertions to work correctly. ```java Path withoutContent = Paths.get("/root/sub-dir-1/file-1.ext"); Path withContent = Paths.get("/root/sub-dir-1/file-2.ext"); // The following assertions succeed: assertThat(withoutContent).isEmptyFile(); assertThat(withContent).isNotEmptyFile(); // The following assertions fail: assertThat(withoutContent).isNotEmptyFile(); assertThat(withContent).isEmptyFile(); ``` -------------------------------- ### Future Assertion: failsWithin with Duration Source: https://assertj.github.io/doc/#assertj-swing Asserts that a Future completes within a specified duration, failing the test if it does not. This example shows a case where the future completes within the timeout. ```java // fails as the future is completed within 200ms assertThat(future).failsWithin(Duration.ofMillis(200)); ``` -------------------------------- ### Recursive Comparison Failure Example Source: https://assertj.github.io/doc/#assertj-swing Demonstrates the error message when a recursive comparison fails due to differences in nested fields. The output clearly indicates which fields differ and their values. ```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")); // FAIL assertThat(song).usingRecursiveComparison() .isEqualTo(expectedSong); ``` ```text Expecting: to be equal to: when recursively comparing field by field, but found the following difference: field/property 'coAuthor.value.name' differ: - actual value : "Jimi Hendrix" - expected value : "Keith Richards" The recursive comparison was performed with this configuration: - overridden equals methods were used in the comparison - these types were compared with the following comparators: - java.lang.Double -> DoubleComparator[precision=1.0E-15] - java.lang.Float -> FloatComparator[precision=1.0E-6] - actual and expected objects and their fields were compared field by field recursively even if they were not of the same type, this allows for example to compare a Person to a PersonDto (call strictTypeChecking(true) to change that behavior). ``` -------------------------------- ### Build Table with Column Ordering Source: https://assertj.github.io/doc/#assertj-swing Create a Table object that specifies the order of columns for retrieval. This ensures data is returned in a predictable sequence. ```java // Get the data from "members" table and order on "name" column in ascending order Table table7 = connection.table("members").columnsToOrder(new Order[] { Order.asc("name") }).build(); ``` -------------------------------- ### Combine Index and Next Column Navigation Source: https://assertj.github.io/doc/#assertj-swing Combine `column(int index)` with `column()` to navigate to a specific column and then to the next one. ```java assertThat(tableOrRequest).column(2).column()... ```