diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 94673dce139..2982bf6dc76 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -3,14 +3,15 @@ # # You may wish to alter this file to override the set of languages analyzed, # or to provide custom queries or build logic. +# name: "CodeQL" on: push: - branches: [main] + branches: [ main ] pull_request: # The branches below must be a subset of the branches above - branches: [main] + branches: [ main ] schedule: - cron: '0 8 * * 0' @@ -18,59 +19,48 @@ jobs: analyze: name: Analyze runs-on: ubuntu-latest + permissions: + actions: read + contents: read + security-events: write strategy: fail-fast: false matrix: - # Override automatic language detection by changing the below list - # Supported options are ['csharp', 'cpp', 'go', 'java', 'javascript', 'python'] - language: ['java'] - # Learn more... - # https://docs.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#overriding-automatic-language-detection + language: [ 'java' ] + # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] + # Learn more: + # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed steps: - - name: Checkout repository - uses: actions/checkout@v2 - with: - # We must fetch at least the immediate parents so that if this is - # a pull request then we can checkout the head. - fetch-depth: 2 - - # If this run was triggered by a pull request event, then checkout - # the head of the pull request instead of the merge commit. - - run: git checkout HEAD^2 - if: ${{ github.event_name == 'pull_request' }} - - - name: Setup Java - uses: actions/setup-java@v1 - with: - java-version: 11 + - name: Checkout repository + uses: actions/checkout@v2 - # Initializes the CodeQL tools for scanning. - - name: Initialize CodeQL - uses: github/codeql-action/init@v1 - with: - languages: ${{ matrix.language }} - # If you wish to specify custom queries, you can do so here or in a config file. - # By default, queries listed here will override any specified in a config file. - # Prefix the list here with "+" to use these queries and those in the config file. - # queries: ./path/to/local/query, your-org/your-repo/queries@main + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v1 + with: + languages: ${{ matrix.language }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + # queries: ./path/to/local/query, your-org/your-repo/queries@main - # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). - # If this step fails, then you should remove it and run the build manually (see below) - - name: Autobuild - uses: github/codeql-action/autobuild@v1 + # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). + # If this step fails, then you should remove it and run the build manually (see below) + - name: Autobuild + uses: github/codeql-action/autobuild@v1 - # ℹ️ Command-line programs to run using the OS shell. - # 📚 https://git.io/JvXDl + # ℹ️ Command-line programs to run using the OS shell. + # 📚 https://git.io/JvXDl - # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines - # and modify them (or add more) to build your code if your project - # uses a compiled language + # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines + # and modify them (or add more) to build your code if your project + # uses a compiled language - #- run: | - # make bootstrap - # make release + #- run: | + # make bootstrap + # make release - - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v1 + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v1 diff --git a/.github/workflows/cross-version.yml b/.github/workflows/cross-version.yml index da01957fd88..d6dfa72a8f6 100644 --- a/.github/workflows/cross-version.yml +++ b/.github/workflows/cross-version.yml @@ -9,13 +9,14 @@ jobs: strategy: fail-fast: false matrix: - java: [14, 15, 16-ea, 17-ea] + java: [16, 17-ea] runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Setup Java - uses: actions/setup-java@v1 + uses: actions/setup-java@v2 with: + distribution: 'zulu' java-version: ${{ matrix.java }} - name: Cache Maven Repository uses: actions/cache@v2 diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index dcd10b03be1..9ba9388574b 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -14,8 +14,9 @@ jobs: steps: - uses: actions/checkout@v2 - name: Setup Java - uses: actions/setup-java@v1 + uses: actions/setup-java@v2 with: + distribution: 'zulu' java-version: 11 - name: Cache Maven Repository uses: actions/cache@v2 @@ -35,8 +36,9 @@ jobs: with: fetch-depth: 0 - name: Setup Java - uses: actions/setup-java@v1 + uses: actions/setup-java@v2 with: + distribution: 'zulu' java-version: 11 - name: Cache Maven Repository uses: actions/cache@v2 @@ -46,8 +48,7 @@ jobs: restore-keys: ${{ runner.os }}-maven - name: Test with Sonar run: > - ./mvnw -V --no-transfer-progress -e clean verify javadoc:javadoc - org.sonarsource.scanner.maven:sonar-maven-plugin:3.7.0.1746:sonar + ./mvnw -V --no-transfer-progress -e clean verify javadoc:javadoc sonar:sonar -Dsonar.host.url=https://sonarcloud.io -Dsonar.organization=assertj -Dsonar.projectKey=joel-costigliola_assertj-core diff --git a/.github/workflows/pitest-receive-pr.yml b/.github/workflows/pitest-receive-pr.yml new file mode 100644 index 00000000000..a4ac9fee377 --- /dev/null +++ b/.github/workflows/pitest-receive-pr.yml @@ -0,0 +1,53 @@ +# +# Part one of two stage process to update PRs with pitest data when accepting PRs from untrusted forks. +# +# The jobs will run the mutation analysis, but the token supplied by gtihub does not have write access. +# The results are therefore stored as an artifact which will be used to update the PR in the second stage. +# +# Projects where PRs come from the same repo can use a simpler single stage process. +# +# see https://blog.pitest.org/pitest-pr-setup/ +# +name: Receive + +# read-only repo token +# no access to secrets +on: + pull_request: + +jobs: + store-pitest-feedback: + # Only run on forked repos. + if: github.event.pull_request.head.repo.full_name != github.repository + runs-on: ubuntu-latest + + steps: + - name: Checkout project + uses: actions/checkout@v2 + with: + # important to set a fetch depth of 2. By default the checkout action make no history available + fetch-depth: 2 + + - name: Cache local Maven repository + uses: actions/cache@v2 + with: + path: ~/.m2/repository + key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} + restore-keys: ${{ runner.os }}-maven- + - name: Setup Java + uses: actions/setup-java@v2 + with: + distribution: 'zulu' + java-version: 11 + - name: run pitest + # pitest has been bound to a profile called pitest for normal running + # we add config to analyse only changes made within a PR and treat surviving mutants as check errors + # failWhenNoMutations is unset in the pom, as otherwise PRs that do not affect java code would fail + run: mvn -e -B -Ppitest -Dfeatures="+GIT(from[HEAD~1]), +gitci" test + - name: aggregate files + run: mvn -e -B -Ppitest pitest-git:aggregate + - name: upload results + uses: actions/upload-artifact@v2 + with: + name: pitest + path: target/pit-reports-ci/ diff --git a/.github/workflows/pitest-updated-pr.yml b/.github/workflows/pitest-updated-pr.yml new file mode 100644 index 00000000000..68168a6e6f4 --- /dev/null +++ b/.github/workflows/pitest-updated-pr.yml @@ -0,0 +1,45 @@ +# +# Part two of two stage process for updating PRs with pitest results when accepting PRs from untrusted forks. +# +# The version of this file that runs is the version in the main/master branch, NOT the version in the PR. It must therefore +# be committed to main/master before the process can run for the first time. +# +# This workflow takes an artifact containing pitest results generated in part one, and updated the PR. It runs with +# write access. +# +# See https://blog.pitest.org/oss-pitest-pr/ + +name: Comment on the pull request + +# read-write repo token +# access to secrets +on: + workflow_run: + workflows: ["Receive"] + types: + - completed + +jobs: + pitest-update-pr: + if: ${{ github.event.workflow_run.conclusion == 'success' }} + runs-on: ubuntu-latest + steps: + - name: debug + uses: hmarr/debug-action@v2 + - name: Setup Java + uses: actions/setup-java@v2 + with: + distribution: 'zulu' + java-version: 11 + - name: Download artifact + uses: dawidd6/action-download-artifact@v2 + with: + workflow: ${{ github.event.workflow_run.workflow_id }} + name: pitest + path: target/pit-reports-ci + workflow_conclusion: success + - name: update pull request + # The updatePR maven goal is used here with an explicit version. This allows us to upload without checking out + # the code, but does mean the version here must be maintained. An alternative would be to checkout the code and use + # the github goal. This will work as long as the artifact is extracted to the maven target directory + run: mvn -Ppitest -DrepoToken=${{ secrets.GITHUB_TOKEN }} com.groupcdg:pitest-github-maven-plugin:0.0.10:updatePR diff --git a/.gitignore b/.gitignore index f64944915f3..bc6eab1bfd3 100644 --- a/.gitignore +++ b/.gitignore @@ -14,7 +14,8 @@ out /expected.txt #jEnv configuration .java-version -/bin/ /dependency-reduced-pom.xml /bin/ .mvn/wrapper/maven-wrapper.jar +# macOS specific files +.DS_Store diff --git a/.mvn/wrapper/MavenWrapperDownloader.java b/.mvn/wrapper/MavenWrapperDownloader.java old mode 100755 new mode 100644 diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties old mode 100755 new mode 100644 index 642d572ce90..ffdc10e59f8 --- a/.mvn/wrapper/maven-wrapper.properties +++ b/.mvn/wrapper/maven-wrapper.properties @@ -1,2 +1,2 @@ -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.1/apache-maven-3.8.1-bin.zip wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 12512a2e4ac..75e3ae94ad6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -5,6 +5,7 @@ Thank you for your interest in contributing to AssertJ! We appreciate your effort and to make sure that your pull request is easy to review, we ask you to note the following guidelines including legal contributor agreement: +* Use JDK 11 or newer to build the project * Use **[AssertJ code Eclipse formatting preferences](src/ide-support/assertj-eclipse-formatter.xml)** (for IntelliJ IDEA users, you can import it with the 'Eclipse Code Formatter' Plugin) * Write complete Javadocs for each assertion method and include a code example (succeeding and failing assertion(s)). * As we use JUnit 5, favor `package-private` visibility for both test classes and test methods. @@ -12,15 +13,14 @@ We appreciate your effort and to make sure that your pull request is easy to rev * Use `@DisplayName` on the test class - see `OptionalAssert_containsInstanceOf_Test` as an example. * Write unit test assertions with AssertJ! Let's eat our own dog food. * Unit tests method naming convention is underscore-based (like python) and not camel-case, we find it is much readable for long test names! -* Successful assertion unit test method names should start with: `should_pass_...`. -* Failing assertion unit test method names should start with: `should_fail_...`. - -* Put GIVEN WHEN THEN steps in each test, favoring `BDDAssertions.then` instead of `Assertions.assertThat` for assertions in the THEN step. Steps can be combined or omitted if a separate step does not provide much benefit to test readability, just ensure that the WHEN step (either single or combined) contains the test target. -* Use `AssertionUtil.expectAssertionError` for tests expecting to get an `AssertionError` - see `OptionalAssert_containsInstanceOf_Test` as an example.. +* Successful assertion unit test method names should start with: `should_pass_xxx` (if you find a better test name, use your best judgment and go for it!) +* Failing assertion unit test method names should start with: `should_fail_xxx`. (if you find a better test name, use your best judgment and go for it!) +* Put `GIVEN` `WHEN` `THEN` steps in each test, prefer `BDDAssertions.then` over `Assertions.assertThat` for assertions in the `THEN` step. Steps can be combined or omitted if a separate step does not provide much benefit to test readability, just ensure that the WHEN step (either single or combined) contains the test target. +* Use `AssertionUtil.expectAssertionError` for tests expecting to get an `AssertionError` - see `OptionalAssert_containsInstanceOf_Test` below for an example. * Use static import when it makes the code more readable. * If possible, add a (fun) code example in [assertj-examples](https://github.com/assertj/assertj-examples) and use it in the javadoc. -A good unit test to use as a reference is `OptionalAssert_containsInstanceOf_Test`. Here's a sample below: +A good unit test to use as a reference is `OptionalAssert_containsInstanceOf_Test`, here's a sample below: ```java import static org.assertj.core.api.BDDAssertions.then; @@ -51,13 +51,13 @@ class OptionalAssert_containsInstanceOf_Test extends BaseTest { } ``` -It's ok not to follow some of the rules described above if you have a good reason not to (use your best judgement) +It's ok not to follow some rules described above if you have a good reason not to (use your best judgement) -[assertj-examples](https://github.com/assertj/assertj-examples) shows how to efficiently use AssertJ through fun unit test examples, it can be seen as AssertJs living documentation. +[assertj-examples](https://github.com/assertj/assertj-examples) shows how to efficiently use AssertJ through fun unit test examples, it is a kind of living documentation. ## Rebase your PR on main (no merge!) -We prefer integrating PR by squashing all the commits and rebase it to main, if you PR has diverged and needs to integrate with main, please rebase on main but do not merge as it will prevent rebasing later on. +We prefer integrating PR by squashing all the commits and rebase it to `main`, if your PR has diverged and needs to get the newer `main` commits, please rebase on `main` but **do not merge `main` in your PR branch** as it will prevent rebasing later on. ## Naming conventions with some examples: @@ -102,6 +102,26 @@ A good javadoc example taken from [`AbstractCharSequenceAssert.containsSequence` */ ``` +Note that to get a good HTML rendering for the code examples, the code should start at the same line and one space after `
`.
+
+Good:
+```text
+ * 
 String book = "{ 'title':'A Game of Thrones', 'author':'George Martin'}";
+```
+
+BAD! (missing space)
+```text
+ * 
String book = "{ 'title':'A Game of Thrones', 'author':'George Martin'}";
+```
+
+BAD! (not in the same line)
+```text
+ * 

+ * String book = "{ 'title':'A Game of Thrones', 'author':'George Martin'}";
+```
+
+To be sure of what the javadoc actually looks, simply generate it and read it in your browser.
+
 ## Legal stuff:
 
 Project license(s): Apache License Version 2.0
diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md
index bfa9253c0e7..8862e1eec97 100644
--- a/PULL_REQUEST_TEMPLATE.md
+++ b/PULL_REQUEST_TEMPLATE.md
@@ -1,6 +1,7 @@
 #### Check List:
-* Fixes #???
+* Fixes #??? (ignore if not applicable)
 * Unit tests : YES / NO / NA
 * Javadoc with a code example (on API only) : YES / NO / NA
+* PR meets the [contributing guidelines](https://github.com/assertj/assertj-core/blob/main/CONTRIBUTING.md)
 
-
+Following the [contributing guidelines](https://github.com/assertj/assertj-core/blob/main/CONTRIBUTING.md) will make it easier for us to review and accept your PR.
diff --git a/README.md b/README.md
index 5987fa00850..a3739095b67 100644
--- a/README.md
+++ b/README.md
@@ -9,63 +9,36 @@
 AssertJ provides a rich and intuitive set of strongly-typed assertions to use for unit testing (with JUnit, TestNG or any other test framework).
 
 * [AssertJ's goals](#goals)
-* [Quick start](#quickstart)
-* [Latest News](#news)
-* AssertJ web site contains the [**AssertJ Core documentation**](https://assertj.github.io/doc/#assertj-core-assertions-guide).
-* [Assertions for custom types](http://joel-costigliola.github.io/assertj/assertj-core-custom-assertions.html) (still in the old site but will soon be available in the [new site](https://assertj.github.io/doc/#overview))
-* [Replacing JUnit assertions with AssertJ Assertions](#junit-to-assertj-assertions)
+* [Quick start](https://assertj.github.io/doc/#assertj-core-quick-start)
+* [Latest releases](https://assertj.github.io/doc/#assertj-core-release-notes)
+* [Documentation](https://assertj.github.io/doc/#assertj-core)
 * [Contributing](#contributing)
 
-
 You can ask questions in [**stackoverflow (assertj tag)**](https://stackoverflow.com/questions/tagged/assertj?mixed=1) and make suggestions by simply creating an issue.
 
-## AssertJ's goals
+## AssertJ's goals
 
 AssertJ's ambition is to provide a rich and intuitive set of strongly-typed assertions for unit testing.
 
-The idea is that disposal assertions should be specific to the type of the objects we are checking when writing unit tests. If you're checking the value of a `String`, you use String-specific assertions. Checking the value of
-a `Map`? Use Map-specific assertions to easily check the contents of the map.
+The idea is that disposal assertions should be specific to the type of the objects we are checking when writing unit tests. If you're checking the value of a `String`, you use String-specific assertions. Checking the value of a `Map`? Use Map-specific assertions to easily check the contents of the map.
+
+AssertJ's assertions are super easy to use: just type **`assertThat(underTest).`** and use code completion to show you all assertions available.
+
+Assertion missing? Please [create an issue](https://github.com/assertj/assertj-core/issues) to discuss it and even better [contribute to the project](https://github.com/assertj/assertj-core/blob/main/CONTRIBUTING.md)!
+
 
 AssertJ is composed of several modules:
 * A core module (this one) to provide assertions for JDK types (`String`, `Iterable`, `Stream`, `Path`, `File`, `Map`...) - see [AssertJ Core documentation](https://assertj.github.io/doc/#assertj-core-assertions-guide) and [javadoc](https://www.javadoc.io/doc/org.assertj/assertj-core/latest/index.html).
-* A **[Guava module](https://github.com/assertj/assertj-guava#readme)** to provide assertions for Guava types (`Multimap`, `Optional`...) - see [AssertJ Guava documentation](https://assertj.github.io/doc/#assertj-guava) and  [javadoc](https://www.javadoc.io/doc/org.assertj/assertj-guava/latest/index.html).
+* A **[Guava module](https://github.com/assertj/assertj-guava#readme)** to provide assertions for Guava types (`Multimap`, `Optional`...) - see [AssertJ Guava documentation](https://assertj.github.io/doc/#assertj-guava) and [javadoc](https://www.javadoc.io/doc/org.assertj/assertj-guava/latest/index.html).
 * A **[Joda Time module](https://github.com/assertj/assertj-joda-time#readme)** to provide assertions for Joda Time types (`DateTime`, `LocalDateTime`) - see [AssertJ Joda Time documentation](http://joel-costigliola.github.io/assertj/assertj-joda-time.html) and  [javadoc](https://www.javadoc.io/doc/org.assertj/assertj-joda-time/latest/index.html).
 * A **[Neo4J module](https://github.com/assertj/assertj-neo4j#readme)** to provide assertions for Neo4J types (`Path`, `Node`, `Relationship`...) - see [AssertJ Neo4J documentation](http://joel-costigliola.github.io/assertj/assertj-neo4j.html) and [javadoc](https://www.javadoc.io/doc/org.assertj/assertj-neo4j/latest/index.html).
 * A **[DB module](https://github.com/assertj/assertj-db#readme)** to provide assertions for relational database types (`Table`, `Row`, `Column`...) - see [AssertJ DB documentation](https://assertj.github.io/doc/#assertj-db) and [javadoc](https://www.javadoc.io/doc/org.assertj/assertj-db/latest/index.html).
 * A **[Swing module](https://github.com/assertj/assertj-swing#readme)** provides a simple and intuitive API for functional testing of Swing user interfaces - see [AssertJ Swing documentation](http://joel-costigliola.github.io/assertj/assertj-swing.html) and [javadoc](https://www.javadoc.io/doc/org.assertj/assertj-swing/latest/index.html).
 
-Assertion missing? Please [create an issue](https://github.com/assertj/assertj-core/issues)!
-
-AssertJ's assertions are super easy to use: just type **```assertThat```** followed by the actual value in parentheses and a dot,
-then any Java IDE will show you all assertions available for the type of the object. No more confusion about the
-order of "expected" and "actual" value.
-
-AssertJ's assertions are very close to plain English.
-
-A lot of effort has been spent to provide intuitive failure messages showing clearly why the assertion failed.
-
-Note that AssertJ 3.x requires at least Java 8 and AssertJ 2.x requires at least Java 7.
-
-## Quickstart
-
-It is easy to start using AssertJ, just follow the [**one minute starting guide**](https://assertj.github.io/doc/#assertj-core-quick-start).
-
-## Latest News
-
-To read details on the latest releases, please go to [**AssertJ Core latest news**](https://assertj.github.io/doc/#assertj-core).
-
-## Assertions for custom types
-
-Having assertions for common types like `List` is great, but you might want some assertions specific to your own types. It is simple to [write assertions for your custom types](http://joel-costigliola.github.io/assertj/assertj-core-custom-assertions.html) with AssertJ because it is easily extensible.  
-
-Moreover, to ease your work, we provide assertions generator that can take a set of custom types and create specific assertions. The tools provided are:
-* A **[CLI assertions generator](http://joel-costigliola.github.io/assertj/assertj-assertions-generator.html)**
-* A **[Maven plugin assertions generator](http://joel-costigliola.github.io/assertj/assertj-assertions-generator-maven-plugin.html)**  
 
-## Replacing JUnit assertions with AssertJ Assertions
 
-To help you [**replace JUnit assertions**](https://assertj.github.io/doc/#assertj-migration) with AssertJ ones, you can use a [**script**](https://assertj.github.io/doc/#assertj-migration-using-scripts) or do regexp search and replace manually as described [**here**](https://assertj.github.io/doc/#assertj-migration-using-regexes).
+## Want to contribute?
 
-## Want to contribute?
+You are encouraged to contribute any missing useful assertions. 
 
-You are encouraged to contribute any missing, useful assertions. To do so, please read the [contributing section](https://github.com/assertj/assertj-core/blob/main/CONTRIBUTING.md).
+Please read the [contributing section](https://github.com/assertj/assertj-core/blob/main/CONTRIBUTING.md) and raise a PR!
diff --git a/cdg-pitest-licence.txt b/cdg-pitest-licence.txt
new file mode 100644
index 00000000000..b78b9a825c6
--- /dev/null
+++ b/cdg-pitest-licence.txt
@@ -0,0 +1,7 @@
+#Licence file for pitest git plugin
+#Tue May 04 09:26:47 BST 2021
+expires=04/05/2023
+keyVersion=1
+signature=D1RXTdu1ITmJhlRqssvVts6xi5xeyobnq4QCOeLHRuggH1sk4FECLCMPXPtAe0mkUPFI3kuioxmQcnGpm4Xol/Q3YnhI3bKZWjNNgl1XdW3SiGzKqYg/mzwXZeWPPSBQ5pl3Bf0SvcvcZaQaLzAWtgRtjRWqyuBGegASqDOqwGc\=
+packages=org.assertj.*
+type=OSSS
diff --git a/mvnw.cmd b/mvnw.cmd
old mode 100755
new mode 100644
diff --git a/pom.xml b/pom.xml
index 447916d84ca..3a958507fbb 100644
--- a/pom.xml
+++ b/pom.xml
@@ -2,7 +2,7 @@
 
   4.0.0
   assertj-core
-  3.19.0
+  3.20.0
   jar
   AssertJ fluent assertions
   Rich and fluent assertions for testing for Java
@@ -16,7 +16,7 @@
     scm:git:git@github.com:assertj/assertj-core.git
     scm:git:git@github.com:assertj/assertj-core.git
     git@github.com:assertj/assertj-core
-    assertj-core-3.19.0
+    assertj-core-3.20.0
   
   
     github
@@ -25,15 +25,16 @@
 
   
     -html5 --allow-script-in-comments --no-module-directories
-    1.10.19
+    1.11.2
     1.2.0
-    5.2.0
+    5.3.0
     
-    4.13.1
-    5.6.3
-    3.7.7
+    4.13.2
+    5.7.2
+    3.11.1
     
-    0.8.6
+    0.8.7
+    0.0.10
   
 
   
@@ -132,7 +133,7 @@
     
       com.fasterxml.jackson.core
       jackson-databind
-      2.12.1
+      2.12.3
       test
     
     
       
@@ -233,6 +262,7 @@
         
           
           
+            bytebuddy
             package
             
               shade
@@ -559,7 +589,7 @@
       
         org.apache.maven.plugins
         maven-invoker-plugin
-        3.2.1
+        3.2.2
         
           ${project.build.directory}/it
           src/it/settings.xml
@@ -579,9 +609,36 @@
           
         
       
+      
+        org.pitest
+        pitest-maven
+        1.6.7
+        
+          
+            org.pitest
+            pitest-junit5-plugin
+            0.14
+          
+          
+            com.groupcdg
+            pitest-git-plugin
+            ${cdg.pitest.version}
+          
+        
+        
+          3
+          false
+          false
+        
+      
     
     
       
+        
+          org.sonarsource.scanner.maven
+          sonar-maven-plugin
+          3.9.0.2155
+        
         
           net.alchim31.maven
           yuicompressor-maven-plugin
@@ -617,43 +674,6 @@
     
   
   
-    
-      java9+
-      
-        [9,)
-      
-      
-        
-          
-            
-              org.apache.maven.plugins
-              maven-compiler-plugin
-              
-                
-                  jdk9
-                  
-                    compile
-                  
-                  
-                    9
-                    
-                      ${project.basedir}/src/main/java9
-                    
-                    ${project.build.outputDirectory}/META-INF/versions/9
-                    
-                      --patch-module
-                      org.assertj.core=${project.build.outputDirectory}
-                      --module-version
-                      ${project.version}
-                    
-                  
-                
-              
-            
-          
-        
-      
-    
     
       java13+
       
@@ -669,9 +689,39 @@
         [16,)
       
       
-        -Dnet.bytebuddy.experimental=true --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.util=ALL-UNNAMED --add-opens=java.base/java.math=ALL-UNNAMED --add-opens=java.base/sun.nio.fs=ALL-UNNAMED
+        -Dnet.bytebuddy.experimental=true --add-opens=java.base/java.lang=ALL-UNNAMED
+          --add-opens=java.base/java.util=ALL-UNNAMED --add-opens=java.base/java.math=ALL-UNNAMED
+          --add-opens=java.base/sun.nio.fs=ALL-UNNAMED
       
     
+    
+      pitest
+      
+        
+          
+            org.pitest
+            pitest-maven
+            
+              
+                pitest
+                test-compile
+                
+                  mutationCoverage
+                
+              
+            
+          
+          
+          
+            com.groupcdg
+            pitest-git-maven-plugin
+            ${cdg.pitest.version}
+          
+        
+      
+    
   
 
 
diff --git a/src/main/java/org/assertj/core/api/AbstractArrayAssert.java b/src/main/java/org/assertj/core/api/AbstractArrayAssert.java
index c07d99d3a0f..d22927240cd 100644
--- a/src/main/java/org/assertj/core/api/AbstractArrayAssert.java
+++ b/src/main/java/org/assertj/core/api/AbstractArrayAssert.java
@@ -32,7 +32,7 @@ protected AbstractArrayAssert(final ACTUAL actual, final Class selfType) {
   }
 
   static void requireNonNullParameter(Object parameter, String parameterName) {
-    requireNonNull(parameter, shouldNotBeNull(parameterName).create());
+    requireNonNull(parameter, shouldNotBeNull(parameterName)::create);
   }
 
 }
diff --git a/src/main/java/org/assertj/core/api/AbstractAssert.java b/src/main/java/org/assertj/core/api/AbstractAssert.java
index c133a6180f6..dfa42db1708 100644
--- a/src/main/java/org/assertj/core/api/AbstractAssert.java
+++ b/src/main/java/org/assertj/core/api/AbstractAssert.java
@@ -82,13 +82,15 @@ public abstract class AbstractAssert,
   protected final ACTUAL actual;
   protected final SELF myself;
 
+  @VisibleForTesting
   // = ConfigurationProvider.CONFIGURATION_PROVIDER.representation(); ?
-  private static Representation customRepresentation = null;
+  static Representation customRepresentation = null;
 
   @VisibleForTesting
   AssertionErrorCreator assertionErrorCreator;
 
-  private static boolean printAssertionsDescription;
+  @VisibleForTesting
+  static boolean printAssertionsDescription;
 
   private static Consumer descriptionConsumer;
 
@@ -462,7 +464,7 @@ public SELF satisfies(Condition condition) {
   @Override
   @CheckReturnValue
   public > ASSERT asInstanceOf(InstanceOfAssertFactory instanceOfAssertFactory) {
-    requireNonNull(instanceOfAssertFactory, shouldNotBeNull("instanceOfAssertFactory").create());
+    requireNonNull(instanceOfAssertFactory, shouldNotBeNull("instanceOfAssertFactory")::create);
     objects.assertIsInstanceOf(info, actual, instanceOfAssertFactory.getType());
     return (ASSERT) instanceOfAssertFactory.createAssert(actual).withAssertionState(myself);
   }
@@ -834,107 +836,30 @@ public SELF satisfies(Consumer requirements) {
    *
    * Consumer<TolkienCharacter> isHobbit = tolkienCharacter -> assertThat(tolkienCharacter.getRace()).isEqualTo(HOBBIT);
    * Consumer<TolkienCharacter> isElf = tolkienCharacter -> assertThat(tolkienCharacter.getRace()).isEqualTo(ELF);
+   * Consumer<TolkienCharacter> isDwarf = tolkienCharacter -> assertThat(tolkienCharacter.getRace()).isEqualTo(DWARF);
    *
    * // assertion succeeds:
-   * assertThat(frodo).satisfiesAnyOf(isElf, isHobbit);
-   *
-   * // assertion fails:
-   * TolkienCharacter boromir = new TolkienCharacter("Boromir", MAN);
-   * assertThat(boromir).satisfiesAnyOf(isHobbit, isElf);
- * - * @param assertions1 the first group of assertions to run against the object under test - must not be null. - * @param assertions2 the second group of assertions to run against the object under test - must not be null. - * @return this assertion object. - * - * @throws IllegalArgumentException if any given assertions group is null - * @since 3.12.0 - */ - // Does not take a Consumer... to avoid to use @SafeVarargs to suppress the generic array type safety warning. - // @SafeVarargs requires methods to be final which breaks the proxying mechanism used by soft assertions and assumptions - public SELF satisfiesAnyOf(Consumer assertions1, Consumer assertions2) { - return satisfiesAnyOfAssertionsGroups(assertions1, assertions2); - } - - /** - * Verifies that the actual object under test satisfies at least one of the given assertions group expressed as {@link Consumer}s. - *

- * This allows users to perform OR like assertions since only one the assertions group has to be met. - *

- * {@link #overridingErrorMessage(String, Object...) Overriding error message} is not supported as it would prevent from - * getting the error messages of the failing assertions, these are valuable to figure out what went wrong.
- * Describing the assertion is supported (for example with {@link #as(String, Object...)}). - *

- * Example: - *

 TolkienCharacter frodo = new TolkienCharacter("Frodo", HOBBIT);
-   *
-   * Consumer<TolkienCharacter> isHobbit = tolkienCharacter -> assertThat(tolkienCharacter.getRace()).isEqualTo(HOBBIT);
-   * Consumer<TolkienCharacter> isElf = tolkienCharacter -> assertThat(tolkienCharacter.getRace()).isEqualTo(ELF);
-   * Consumer<TolkienCharacter> isOrc = tolkienCharacter -> assertThat(tolkienCharacter.getRace()).isEqualTo(ORC);
-   *
-   * // assertion succeeds:
-   * assertThat(frodo).satisfiesAnyOf(isElf, isHobbit, isOrc);
+   * assertThat(frodo).satisfiesAnyOf(isElf, isHobbit, isDwarf);
    *
    * // assertion fails:
    * TolkienCharacter boromir = new TolkienCharacter("Boromir", MAN);
-   * assertThat(boromir).satisfiesAnyOf(isHobbit, isElf, isOrc);
+ * assertThat(boromir).satisfiesAnyOf(isHobbit, isElf, isDwarf);
* - * @param assertions1 the first group of assertions to run against the object under test - must not be null. - * @param assertions2 the second group of assertions to run against the object under test - must not be null. - * @param assertions3 the third group of assertions to run against the object under test - must not be null. + * @param assertions the group of assertions to run against the object under test - must not be null. * @return this assertion object. * * @throws IllegalArgumentException if any given assertions group is null * @since 3.12.0 */ - // Does not take a Consumer... to avoid to use @SafeVarargs to suppress the generic array type safety warning. - // @SafeVarargs requires methods to be final which breaks the proxying mechanism used by soft assertions and assumptions - public SELF satisfiesAnyOf(Consumer assertions1, Consumer assertions2, Consumer assertions3) { - return satisfiesAnyOfAssertionsGroups(assertions1, assertions2, assertions3); - } - - /** - * Verifies that the actual object under test satisfies at least one of the given assertions group expressed as {@link Consumer}s. - *

- * This allows users to perform OR like assertions since only one the assertions group has to be met. - *

- * {@link #overridingErrorMessage(String, Object...) Overriding error message} is not supported as it would prevent from - * getting the error messages of the failing assertions, these are valuable to figure out what went wrong.
- * Describing the assertion is supported (for example with {@link #as(String, Object...)}). - *

- * Example: - *

 TolkienCharacter smaug = new TolkienCharacter("Smaug", DRAGON);
-   *
-   * Consumer<TolkienCharacter> isHobbit = tolkienCharacter -> assertThat(tolkienCharacter.getRace()).isEqualTo(HOBBIT);
-   * Consumer<TolkienCharacter> isElf = tolkienCharacter -> assertThat(tolkienCharacter.getRace()).isEqualTo(ELF);
-   * Consumer<TolkienCharacter> isOrc = tolkienCharacter -> assertThat(tolkienCharacter.getRace()).isEqualTo(ORC);
-   * Consumer<TolkienCharacter> isDragon = tolkienCharacter -> assertThat(tolkienCharacter.getRace()).isEqualTo(DRAGON);
-   *
-   * // assertion succeeds:
-   * assertThat(smaug).satisfiesAnyOf(isElf, isHobbit, isOrc, isDragon);
-   *
-   * // assertion fails:
-   * TolkienCharacter boromir = new TolkienCharacter("Boromir", MAN);
-   * assertThat(boromir).satisfiesAnyOf(isHobbit, isElf, isOrc, isDragon);
- * - * @param assertions1 the first group of assertions to run against the object under test - must not be null. - * @param assertions2 the second group of assertions to run against the object under test - must not be null. - * @param assertions3 the third group of assertions to run against the object under test - must not be null. - * @param assertions4 the third group of assertions to run against the object under test - must not be null. - * @return this assertion object. - * - * @throws IllegalArgumentException if any given assertions group is null - * @since 3.16.0 - */ - // Does not take a Consumer... to avoid to use @SafeVarargs to suppress the generic array type safety warning. - // @SafeVarargs requires methods to be final which breaks the proxying mechanism used by soft assertions and assumptions - public SELF satisfiesAnyOf(Consumer assertions1, Consumer assertions2, Consumer assertions3, - Consumer assertions4) { - return satisfiesAnyOfAssertionsGroups(assertions1, assertions2, assertions3, assertions4); + @SafeVarargs + public final SELF satisfiesAnyOf(Consumer... assertions) { + return satisfiesAnyOfForProxy(assertions); } - // can be final as it is not proxied - @SafeVarargs - private final SELF satisfiesAnyOfAssertionsGroups(Consumer... assertionsGroups) throws AssertionError { + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF satisfiesAnyOfForProxy(Consumer[] assertionsGroups) throws AssertionError { checkArgument(stream(assertionsGroups).allMatch(java.util.Objects::nonNull), "No assertions group should be null"); if (stream(assertionsGroups).anyMatch(this::satisfiesAssertions)) return myself; // none of the assertions group was met! let's report all the errors @@ -950,7 +875,7 @@ private AssertionError multipleAssertionsError(List assertionErr private boolean satisfiesAssertions(Consumer assertions) { try { assertions.accept(actual); - } catch (AssertionError e) { + } catch (@SuppressWarnings("unused") AssertionError e) { return false; } return true; @@ -1000,15 +925,12 @@ public SELF doesNotHaveSameHashCodeAs(Object other) { } /** - * Create a {@link AbstractListAssert}. - *

- * Implementations need to redefine either to be proxy friendly (i.e. no final assertion methods like {@link ProxyableListAssert}) - * or generic vararg friendly (to use {@link SafeVarargs} annotation which requires final method)like {@link ListAssert}. + * Create a {@link AbstractListAssert} from the given list. *

- * The default implementation will assume that this concrete implementation is NOT a soft assertion. + * this method avoids code duplication when features like extracting/asList need to create a new list assertions. * * @param the type of elements. - * @param newActual new value + * @param newActual new list under test * @return a new {@link AbstractListAssert}. */ protected AbstractListAssert, E, ObjectAssert> newListAssertInstance(List newActual) { @@ -1063,8 +985,8 @@ protected RecursiveComparisonAssert usingRecursiveComparison() { @CheckReturnValue protected > ASSERT extracting(String propertyOrField, AssertFactory assertFactory) { - requireNonNull(propertyOrField, shouldNotBeNull("propertyOrField").create()); - requireNonNull(assertFactory, shouldNotBeNull("assertFactory").create()); + requireNonNull(propertyOrField, shouldNotBeNull("propertyOrField")::create); + requireNonNull(assertFactory, shouldNotBeNull("assertFactory")::create); Object value = byName(propertyOrField).apply(actual); String extractedPropertyOrFieldDescription = extractedDescriptionOf(propertyOrField); String description = mostRelevantDescription(info.description(), extractedPropertyOrFieldDescription); @@ -1089,8 +1011,8 @@ protected RecursiveComparisonAssert usingRecursiveComparison() { @CheckReturnValue protected > ASSERT extracting(Function extractor, AssertFactory assertFactory) { - requireNonNull(extractor, shouldNotBeNull("extractor").create()); - requireNonNull(assertFactory, shouldNotBeNull("assertFactory").create()); + requireNonNull(extractor, shouldNotBeNull("extractor")::create); + requireNonNull(assertFactory, shouldNotBeNull("assertFactory")::create); T extractedValue = extractor.apply(actual); return (ASSERT) assertFactory.createAssert(extractedValue).withAssertionState(myself); } diff --git a/src/main/java/org/assertj/core/api/AbstractCharSequenceAssert.java b/src/main/java/org/assertj/core/api/AbstractCharSequenceAssert.java index d4da48b3f85..9a8fb90975c 100644 --- a/src/main/java/org/assertj/core/api/AbstractCharSequenceAssert.java +++ b/src/main/java/org/assertj/core/api/AbstractCharSequenceAssert.java @@ -820,6 +820,31 @@ public SELF containsIgnoringCase(CharSequence sequence) { return myself; } + /** + * Verifies that the actual {@code CharSequence} contains all the given values, ignoring whitespace differences. + *

+ * You can use one or several {@code CharSequence}s as in this example: + *

 // assertions succeed:
+   * assertThat("Gandalf the grey").containsIgnoringWhitespaces("alf")
+   *                               .containsIgnoringWhitespaces("alf", "grey")
+   *                               .containsIgnoringWhitespaces("thegrey")
+   *                               .containsIgnoringWhitespaces("thegr  ey")
+   *                               .containsIgnoringWhitespaces("t h e g r\t\r\n ey");
+   * // assertion fails:
+   * assertThat("Gandalf the grey").containsIgnoringWhitespaces("alF")
+ * + * @param values the Strings to look for. + * @return {@code this} assertion object. + * @throws NullPointerException if the given list of values is {@code null}. + * @throws IllegalArgumentException if the list of given values is empty. + * @throws AssertionError if the actual {@code CharSequence} is {@code null}. + * @throws AssertionError if the actual {@code CharSequence} does not contain all the given strings. + */ + public SELF containsIgnoringWhitespaces(CharSequence... values) { + strings.assertContainsIgnoringWhitespaces(info, actual, values); + return myself; + } + /** * Verifies that the actual {@code CharSequence} does not contain any of the given values. *

diff --git a/src/main/java/org/assertj/core/api/AbstractClassAssert.java b/src/main/java/org/assertj/core/api/AbstractClassAssert.java index 5609d04df45..7d898fbb462 100644 --- a/src/main/java/org/assertj/core/api/AbstractClassAssert.java +++ b/src/main/java/org/assertj/core/api/AbstractClassAssert.java @@ -12,6 +12,8 @@ */ package org.assertj.core.api; +import static org.assertj.core.util.Arrays.array; + import java.lang.annotation.Annotation; import org.assertj.core.internal.Classes; @@ -317,7 +319,15 @@ public SELF isPackagePrivate() { * @throws AssertionError if {@code actual} is {@code null}. * @throws AssertionError if the actual {@code Class} doesn't contains all of these annotations. */ - public SELF hasAnnotations(@SuppressWarnings("unchecked") Class... annotations) { + @SafeVarargs + public final SELF hasAnnotations(Class... annotations) { + return hasAnnotationsForProxy(annotations); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF hasAnnotationsForProxy(Class[] annotations) { classes.assertContainsAnnotations(info, actual, annotations); return myself; } @@ -343,9 +353,8 @@ public SELF hasAnnotations(@SuppressWarnings("unchecked") Class annotation) { - classes.assertContainsAnnotations(info, actual, annotation); + classes.assertContainsAnnotations(info, actual, array(annotation)); return myself; } diff --git a/src/main/java/org/assertj/core/api/AbstractDateAssert.java b/src/main/java/org/assertj/core/api/AbstractDateAssert.java index 88233e375b8..5d66cdf7178 100644 --- a/src/main/java/org/assertj/core/api/AbstractDateAssert.java +++ b/src/main/java/org/assertj/core/api/AbstractDateAssert.java @@ -72,12 +72,13 @@ public abstract class AbstractDateAssert> /** * the default DateFormat used to parse any String date representation. */ - private static final List DEFAULT_DATE_FORMATS = list(newIsoDateTimeWithMsAndIsoTimeZoneFormat(), - newIsoDateTimeWithMsFormat(), - newTimestampDateFormat(), - newIsoDateTimeWithIsoTimeZoneFormat(), - newIsoDateTimeFormat(), - newIsoDateFormat()); + @VisibleForTesting + static final List DEFAULT_DATE_FORMATS = list(newIsoDateTimeWithMsAndIsoTimeZoneFormat(), + newIsoDateTimeWithMsFormat(), + newTimestampDateFormat(), + newIsoDateTimeWithIsoTimeZoneFormat(), + newIsoDateTimeFormat(), + newIsoDateFormat()); private static final String DATE_FORMAT_PATTERN_SHOULD_NOT_BE_NULL = "Given date format pattern should not be null"; private static final String DATE_FORMAT_SHOULD_NOT_BE_NULL = "Given date format should not be null"; diff --git a/src/main/java/org/assertj/core/api/AbstractDoubleAssert.java b/src/main/java/org/assertj/core/api/AbstractDoubleAssert.java index 8d705dbda51..fd85d6b23c6 100644 --- a/src/main/java/org/assertj/core/api/AbstractDoubleAssert.java +++ b/src/main/java/org/assertj/core/api/AbstractDoubleAssert.java @@ -42,6 +42,7 @@ * @author Joel Costigliola * @author Mikhail Mazursky * @author Nicolas François + * @author Jack Gough */ public abstract class AbstractDoubleAssert> extends AbstractComparableAssert implements FloatingPointNumberAssert { @@ -463,8 +464,10 @@ public SELF isNotCloseTo(double expected, Percentage percentage) { */ public SELF isEqualTo(double expected) { if (noCustomComparatorSet()) { + // check for null first to avoid casting a null to primitive + isNotNull(); // use primitive comparison since the parameter is a primitive. - if (expected == actual.doubleValue()) return myself; + if (expected == actual) return myself; // At this point we know that the assertion failed, if actual and expected are Double.NaN we want to // give a clear error message (we need to use equals to check that as Double.NaN != Double.NaN) if (Double.valueOf(expected).equals(Double.NaN) && actual.equals(Double.NaN)) @@ -580,8 +583,10 @@ public SELF isEqualTo(double expected, Offset offset) { */ public SELF isNotEqualTo(double other) { if (noCustomComparatorSet()) { + // check for null first to avoid casting a null to primitive + isNotNull(); // use primitive comparison since the parameter is a primitive. - if (other != actual.doubleValue()) return myself; + if (other != actual) return myself; throw Failures.instance().failure(info, shouldNotBeEqual(actual, other)); } doubles.assertNotEqual(info, actual, other); @@ -666,7 +671,7 @@ public SELF isLessThan(double other) { public SELF isLessThanOrEqualTo(double other) { if (noCustomComparatorSet()) { // use primitive comparison since the parameter is a primitive. - if (actual.doubleValue() <= other) return myself; + if (actual <= other) return myself; throw Failures.instance().failure(info, shouldBeLessOrEqual(actual, other)); } doubles.assertLessThanOrEqualTo(info, actual, other); @@ -748,7 +753,7 @@ public SELF isGreaterThan(double other) { public SELF isGreaterThanOrEqualTo(double other) { if (noCustomComparatorSet()) { // use primitive comparison since the parameter is a primitive. - if (actual.doubleValue() >= other) return myself; + if (actual >= other) return myself; throw Failures.instance().failure(info, shouldBeGreaterOrEqual(actual, other)); } doubles.assertGreaterThanOrEqualTo(info, actual, other); @@ -842,12 +847,12 @@ public SELF usingDefaultComparator() { } private void assertIsPrimitiveZero() { - if (actual.doubleValue() == 0.0) return; + if (actual == 0.0) return; throw Failures.instance().failure(info, shouldBeEqual(actual, 0.0, info.representation())); } private void assertIsPrimitiveNonZero() { - if (actual.doubleValue() != 0.0) return; + if (actual != 0.0) return; throw Failures.instance().failure(info, shouldNotBeEqual(actual, 0.0)); } @@ -858,7 +863,7 @@ private boolean noCustomComparatorSet() { /** * Verifies that the double value is a finite floating-point value. *

- * Examples: + * Example: *

 // assertion succeeds
    * assertThat(1.0d).isFinite();
    *
@@ -870,7 +875,10 @@ private boolean noCustomComparatorSet() {
    * @return this assertion object.
    * @throws AssertionError if the actual value is not a finite floating-point value.
    * @throws AssertionError if the actual value is null.
+   * @see #isNotFinite()
    * @see #isInfinite()
+   * @see #isNaN()
+   * @see java.lang.Double#isFinite(double)
    * @since 3.19.0
    */
   @Override
@@ -879,6 +887,35 @@ public SELF isFinite() {
     return myself;
   }
 
+  /**
+   * Verifies that the double value is not a finite floating-point value.
+   * 

+ * Note that 'not finite' is not equivalent to infinite as `NaN` is neither finite or infinite. + *

+ * Example: + *

 // assertions succeed
+   * assertThat(Double.POSITIVE_INFINITY).isNotFinite();
+   * assertThat(Double.NEGATIVE_INFINITY).isNotFinite();
+   * assertThat(Double.NaN).isNotFinite();
+   *
+   * // assertion fails
+   * assertThat(1.0).isNotFinite();
+ * + * @return this assertion object. + * @throws AssertionError if the actual value is a finite floating-point value. + * @throws AssertionError if the actual value is null. + * @see #isFinite() + * @see #isInfinite() + * @see #isNaN() + * @see java.lang.Double#isFinite(double) + * @since 3.20.0 + */ + @Override + public SELF isNotFinite() { + doubles.assertIsNotFinite(info, actual); + return myself; + } + /** * Verifies that the double value represents positive infinity or negative infinity. *

@@ -892,8 +929,12 @@ public SELF isFinite() { * assertThat(Double.NaN).isInfinite();

* * @return this assertion object. - * @throws AssertionError if the actual value doesn't represent the positive infinity nor negative infinity. + * @throws AssertionError if the actual value represents neither positive infinity nor negative infinity. * @throws AssertionError if the actual value is null. + * @see #isNotInfinite() + * @see #isFinite() + * @see #isNaN() + * @see java.lang.Double#isInfinite(double) * @since 3.19.0 */ @Override @@ -901,4 +942,31 @@ public SELF isInfinite() { doubles.assertIsInfinite(info, actual); return myself; } + + /** + * Verifies that the double value represents neither positive infinity nor negative infinity. + *

+ * Examples: + *

 // assertions succeed
+   * assertThat(1.0).isNotInfinite();
+   * assertThat(Double.NaN).isNotInfinite();
+   *
+   * // assertions fail
+   * assertThat(Double.POSITIVE_INFINITY).isNotInfinite();
+   * assertThat(Double.NEGATIVE_INFINITY).isNotInfinite();
+ * + * @return this assertion object. + * @throws AssertionError if the actual value represents positive infinity or negative infinity. + * @throws AssertionError if the actual value is null. + * @see #isInfinite() + * @see #isFinite() + * @see #isNaN() + * @see java.lang.Double#isInfinite(double) + * @since 3.20.0 + */ + @Override + public SELF isNotInfinite() { + doubles.assertIsNotInfinite(info, actual); + return myself; + } } diff --git a/src/main/java/org/assertj/core/api/AbstractFloatAssert.java b/src/main/java/org/assertj/core/api/AbstractFloatAssert.java index 7d2745d7c62..ca5a5d8f3d2 100644 --- a/src/main/java/org/assertj/core/api/AbstractFloatAssert.java +++ b/src/main/java/org/assertj/core/api/AbstractFloatAssert.java @@ -102,12 +102,12 @@ public SELF isZero() { } private void assertIsPrimitiveZero() { - if (actual.floatValue() == 0.0f) return; + if (actual == 0.0f) return; throw Failures.instance().failure(info, shouldBeEqual(actual, 0.0f, info.representation())); } private void assertIsPrimitiveNonZero() { - if (actual.floatValue() != 0.0f) return; + if (actual != 0.0f) return; throw Failures.instance().failure(info, shouldNotBeEqual(actual, 0.0f)); } @@ -199,7 +199,7 @@ public SELF isNotPositive() { public SELF isEqualTo(float expected) { if (noCustomComparatorSet()) { // use primitive comparison since the parameter is a primitive. - if (expected == actual.floatValue()) return myself; + if (expected == actual) return myself; // at this point we know that the assertion failed, if actual and expected are Float.NaN first we want // to give a clear error message (we need to use equals to check that as Float.NaN != Float.NaN) if (Float.valueOf(expected).equals(Float.NaN) && actual.equals(Float.NaN)) @@ -695,7 +695,7 @@ public SELF isLessThan(float other) { public SELF isLessThanOrEqualTo(float other) { if (noCustomComparatorSet()) { // use primitive comparison since the parameter is a primitive. - if (actual.floatValue() <= other) return myself; + if (actual <= other) return myself; throw Failures.instance().failure(info, shouldBeLessOrEqual(actual, other)); } floats.assertLessThanOrEqualTo(info, actual, other); @@ -776,7 +776,7 @@ public SELF isGreaterThan(float other) { public SELF isGreaterThanOrEqualTo(float other) { if (noCustomComparatorSet()) { // use primitive comparison since the parameter is a primitive. - if (actual.floatValue() >= other) return myself; + if (actual >= other) return myself; throw Failures.instance().failure(info, shouldBeGreaterOrEqual(actual, other)); } floats.assertGreaterThanOrEqualTo(info, actual, other); @@ -888,7 +888,10 @@ private boolean noCustomComparatorSet() { * @return this assertion object. * @throws AssertionError if the actual value is not a finite floating-point value. * @throws AssertionError if the actual value is null. + * @see #isNotFinite() * @see #isInfinite() + * @see #isNaN() + * @see java.lang.Float#isFinite(float) * @since 3.19.0 */ @Override @@ -897,6 +900,35 @@ public SELF isFinite() { return myself; } + /** + * Verifies that the float value is not a finite floating-point value. + *

+ * Note that 'not finite' is not equivalent to infinite as `NaN` is neither finite or infinite. + *

+ * Example: + *

 // assertions succeed
+   * assertThat(Float.POSITIVE_INFINITY).isNotFinite();
+   * assertThat(Float.NEGATIVE_INFINITY).isNotFinite();
+   * assertThat(Float.NaN).isNotFinite();
+   *
+   * // assertion fails
+   * assertThat(1.0f).isNotFinite();
+ * + * @return this assertion object. + * @throws AssertionError if the actual value is a finite floating-point value. + * @throws AssertionError if the actual value is null. + * @see #isFinite() + * @see #isInfinite() + * @see #isNaN() + * @see java.lang.Float#isFinite(float) + * @since 3.20.0 + */ + @Override + public SELF isNotFinite() { + floats.assertIsNotFinite(info, actual); + return myself; + } + /** * Verifies that the float value represents positive infinity or negative infinity. *

@@ -910,8 +942,12 @@ public SELF isFinite() { * assertThat(Float.NaN).isInfinite();

* * @return this assertion object. - * @throws AssertionError if the actual value doesn't represent the positive infinity nor negative infinity. + * @throws AssertionError if the actual value represents neither positive infinity nor negative infinity. * @throws AssertionError if the actual value is null. + * @see #isNotInfinite() + * @see #isFinite() + * @see #isNaN() + * @see java.lang.Float#isInfinite(float) * @since 3.19.0 */ @Override @@ -919,4 +955,31 @@ public SELF isInfinite() { floats.assertIsInfinite(info, actual); return myself; } + + /** + * Verifies that the float value represents neither positive infinity nor negative infinity. + *

+ * Examples: + *

 // assertions succeed
+   * assertThat(1.0f).isNotInfinite();
+   * assertThat(Float.NaN).isNotInfinite();
+   *
+   * // assertions fail
+   * assertThat(Float.POSITIVE_INFINITY).isNotInfinite();
+   * assertThat(Float.NEGATIVE_INFINITY).isNotInfinite();
+ * + * @return this assertion object. + * @throws AssertionError if the actual value represents positive infinity or negative infinity. + * @throws AssertionError if the actual value is null. + * @see #isInfinite() + * @see #isFinite() + * @see #isNaN() + * @see java.lang.Float#isInfinite(float) + * @since 3.20.0 + */ + @Override + public SELF isNotInfinite() { + floats.assertIsNotInfinite(info, actual); + return myself; + } } diff --git a/src/main/java/org/assertj/core/api/AbstractInputStreamAssert.java b/src/main/java/org/assertj/core/api/AbstractInputStreamAssert.java index 207eb715532..295c29cd32e 100644 --- a/src/main/java/org/assertj/core/api/AbstractInputStreamAssert.java +++ b/src/main/java/org/assertj/core/api/AbstractInputStreamAssert.java @@ -12,11 +12,18 @@ */ package org.assertj.core.api; +import static java.util.Objects.requireNonNull; +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; import java.io.InputStream; +import java.nio.charset.Charset; import java.security.MessageDigest; import org.assertj.core.internal.InputStreams; import org.assertj.core.internal.InputStreamsException; +import org.assertj.core.util.CheckReturnValue; import org.assertj.core.util.VisibleForTesting; /** @@ -28,6 +35,7 @@ * * @author Matthieu Baechler * @author Mikhail Mazursky + * @author Stefan Birkner */ public abstract class AbstractInputStreamAssert, ACTUAL extends InputStream> extends AbstractAssert { @@ -39,6 +47,36 @@ protected AbstractInputStreamAssert(ACTUAL actual, Class selfType) { super(actual, selfType); } + /** + * Converts the content of the actual {@link InputStream} to a {@link String} by decoding its bytes using the given charset + * and returns assertions for the computed String allowing String specific assertions from this call. + *

+ * Example : + *

 InputStream abcInputStream = new ByteArrayInputStream("abc".getBytes());
+   *
+   * // assertion succeeds
+   * assertThat(abcInputStream).asString(UTF_8)
+   *                           .startsWith("a");
+   *
+   * // assertion fails
+   * assertThat(abcInputStream).asString(UTF_8)
+   *                           .startsWith("e");
+ * + * @param charset the {@link Charset} to interpret the {@code InputStream}'s content to a String + * @return a string assertion object. + * @throws NullPointerException if the given {@code Charset} is {@code null}. + * @throws AssertionError if the actual {@code InputStream} is {@code null}. + * @throws InputStreamsException if an I/O error occurs. + * @since 3.20.0 + */ + @CheckReturnValue + public AbstractStringAssert asString(Charset charset) { + requireNonNull(charset, "The charset for converting to a String must not be null"); + objects.assertNotNull(info, actual); + String actualAsString = readString(charset); + return assertThat(actualAsString); + } + /** * Verifies that the content of the actual {@code InputStream} is equal to the content of the given one. * @@ -298,4 +336,19 @@ public SELF hasDigest(String algorithm, String expected) { inputStreams.assertHasDigest(info, actual, algorithm, expected); return myself; } + + private String readString(Charset charset) { + try { + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + int read; + byte[] data = new byte[1024]; + while ((read = actual.read(data, 0, data.length)) != -1) { + buffer.write(data, 0, read); + } + buffer.flush(); + return new String(buffer.toByteArray(), charset); + } catch (IOException e) { + throw new InputStreamsException("Unable to read contents of InputStreams actual", e); + } + } } diff --git a/src/main/java/org/assertj/core/api/AbstractIterableAssert.java b/src/main/java/org/assertj/core/api/AbstractIterableAssert.java index 61851834e7e..0e92b8c8887 100644 --- a/src/main/java/org/assertj/core/api/AbstractIterableAssert.java +++ b/src/main/java/org/assertj/core/api/AbstractIterableAssert.java @@ -69,7 +69,6 @@ import org.assertj.core.internal.ObjectArrays; import org.assertj.core.internal.Objects; import org.assertj.core.internal.OnFieldsComparator; -import org.assertj.core.internal.RecursiveFieldByFieldComparator; import org.assertj.core.internal.TypeComparators; import org.assertj.core.presentation.PredicateDescription; import org.assertj.core.util.CheckReturnValue; @@ -100,6 +99,8 @@ * @author Marko Bekhta */ //@format:off +// suppression of deprecation works in Eclipse to hide warning for the deprecated classes in the imports +@SuppressWarnings("deprecation") public abstract class AbstractIterableAssert, ACTUAL extends Iterable, ELEMENT, @@ -345,7 +346,15 @@ public SELF hasSameSizeAs(Iterable other) { * {@inheritDoc} */ @Override - public SELF contains(@SuppressWarnings("unchecked") ELEMENT... values) { + @SafeVarargs + public final SELF contains(ELEMENT... values) { + return containsForProxy(values); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF containsForProxy(ELEMENT[] values) { iterables.assertContains(info, actual, values); return myself; } @@ -354,7 +363,15 @@ public SELF contains(@SuppressWarnings("unchecked") ELEMENT... values) { * {@inheritDoc} */ @Override - public SELF containsOnly(@SuppressWarnings("unchecked") ELEMENT... values) { + @SafeVarargs + public final SELF containsOnly(ELEMENT... values) { + return containsOnlyForProxy(values); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF containsOnlyForProxy(ELEMENT[] values) { iterables.assertContainsOnly(info, actual, values); return myself; } @@ -363,7 +380,15 @@ public SELF containsOnly(@SuppressWarnings("unchecked") ELEMENT... values) { * {@inheritDoc} */ @Override - public SELF containsOnlyOnce(@SuppressWarnings("unchecked") ELEMENT... values) { + @SafeVarargs + public final SELF containsOnlyOnce(ELEMENT... values) { + return containsOnlyOnceForProxy(values); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF containsOnlyOnceForProxy(ELEMENT[] values) { iterables.assertContainsOnlyOnce(info, actual, values); return myself; } @@ -381,14 +406,30 @@ public SELF containsOnlyNulls() { * {@inheritDoc} */ @Override - public SELF containsExactly(@SuppressWarnings("unchecked") ELEMENT... values) { + @SafeVarargs + public final SELF containsExactly(ELEMENT... values) { + return containsExactlyForProxy(values); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF containsExactlyForProxy(ELEMENT[] values) { iterables.assertContainsExactly(info, actual, values); return myself; } /** {@inheritDoc} */ @Override - public SELF containsExactlyInAnyOrder(@SuppressWarnings("unchecked") ELEMENT... values) { + @SafeVarargs + public final SELF containsExactlyInAnyOrder(ELEMENT... values) { + return containsExactlyInAnyOrderForProxy(values); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF containsExactlyInAnyOrderForProxy(ELEMENT[] values) { iterables.assertContainsExactlyInAnyOrder(info, actual, values); return myself; } @@ -414,7 +455,15 @@ public SELF isSubsetOf(Iterable values) { * {@inheritDoc} */ @Override - public SELF isSubsetOf(@SuppressWarnings("unchecked") ELEMENT... values) { + @SafeVarargs + public final SELF isSubsetOf(ELEMENT... values) { + return isSubsetOfForProxy(values); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF isSubsetOfForProxy(ELEMENT[] values) { iterables.assertIsSubsetOf(info, actual, Arrays.asList(values)); return myself; } @@ -423,7 +472,15 @@ public SELF isSubsetOf(@SuppressWarnings("unchecked") ELEMENT... values) { * {@inheritDoc} */ @Override - public SELF containsSequence(@SuppressWarnings("unchecked") ELEMENT... sequence) { + @SafeVarargs + public final SELF containsSequence(ELEMENT... sequence) { + return containsSequenceForProxy(sequence); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF containsSequenceForProxy(ELEMENT[] sequence) { iterables.assertContainsSequence(info, actual, sequence); return myself; } @@ -442,7 +499,15 @@ public SELF containsSequence(Iterable sequence) { * {@inheritDoc} */ @Override - public SELF doesNotContainSequence(@SuppressWarnings("unchecked") ELEMENT... sequence) { + @SafeVarargs + public final SELF doesNotContainSequence(ELEMENT... sequence) { + return doesNotContainSequenceForProxy(sequence); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF doesNotContainSequenceForProxy(ELEMENT[] sequence) { iterables.assertDoesNotContainSequence(info, actual, sequence); return myself; } @@ -461,7 +526,15 @@ public SELF doesNotContainSequence(Iterable sequence) { * {@inheritDoc} */ @Override - public SELF containsSubsequence(@SuppressWarnings("unchecked") ELEMENT... subsequence) { + @SafeVarargs + public final SELF containsSubsequence(ELEMENT... subsequence) { + return containsSubsequenceForProxy(subsequence); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF containsSubsequenceForProxy(ELEMENT[] subsequence) { iterables.assertContainsSubsequence(info, actual, subsequence); return myself; } @@ -480,7 +553,15 @@ public SELF containsSubsequence(Iterable subsequence) { * {@inheritDoc} */ @Override - public SELF doesNotContainSubsequence(@SuppressWarnings("unchecked") ELEMENT... subsequence) { + @SafeVarargs + public final SELF doesNotContainSubsequence(ELEMENT... subsequence) { + return doesNotContainSubsequenceForProxy(subsequence); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF doesNotContainSubsequenceForProxy(ELEMENT[] subsequence) { iterables.assertDoesNotContainSubsequence(info, actual, subsequence); return myself; } @@ -496,7 +577,15 @@ public SELF doesNotContainSubsequence(Iterable subsequence) { } @Override - public SELF doesNotContain(@SuppressWarnings("unchecked") ELEMENT... values) { + @SafeVarargs + public final SELF doesNotContain(ELEMENT... values) { + return doesNotContainForProxy(values); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF doesNotContainForProxy(ELEMENT[] values) { iterables.assertDoesNotContain(info, actual, values); return myself; } @@ -520,7 +609,15 @@ public SELF doesNotHaveDuplicates() { * {@inheritDoc} */ @Override - public SELF startsWith(@SuppressWarnings("unchecked") ELEMENT... sequence) { + @SafeVarargs + public final SELF startsWith(ELEMENT... sequence) { + return startsWithForProxy(sequence); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF startsWithForProxy(ELEMENT[] sequence) { iterables.assertStartsWith(info, actual, sequence); return myself; } @@ -529,7 +626,15 @@ public SELF startsWith(@SuppressWarnings("unchecked") ELEMENT... sequence) { * {@inheritDoc} */ @Override - public SELF endsWith(ELEMENT first, @SuppressWarnings("unchecked") ELEMENT... rest) { + @SafeVarargs + public final SELF endsWith(ELEMENT first, ELEMENT... rest) { + return endsWithForProxy(first, rest); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF endsWithForProxy(ELEMENT first, ELEMENT[] rest) { iterables.assertEndsWith(info, actual, first, rest); return myself; } @@ -758,6 +863,13 @@ public SELF hasOnlyElementsOfTypes(Class... types) { return myself; } + /** {@inheritDoc} */ + @Override + public SELF hasExactlyElementsOfTypes(Class... types) { + ObjectArrays.instance().assertHasExactlyElementsOfTypes(info, toArray(actual), types); + return myself; + } + /** * {@inheritDoc} */ @@ -821,7 +933,15 @@ public SELF usingDefaultElementComparator() { * @since 2.9.0 / 3.9.0 */ @Override - public SELF containsAnyOf(@SuppressWarnings("unchecked") ELEMENT... values) { + @SafeVarargs + public final SELF containsAnyOf(ELEMENT... values) { + return containsAnyOfForProxy(values); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF containsAnyOfForProxy(ELEMENT[] values) { iterables.assertContainsAnyOf(info, actual, values); return myself; } @@ -1391,8 +1511,7 @@ public AbstractListAssert, /* * Should be used after any methods changing the elements type like {@link #extracting(Function)} as it will propagate the - * correct - * assertions state, that is everything but the element comparator (since the element type has changed). + * correct assertions state, that is everything but the element comparator (since the element type has changed). */ private AbstractListAssert, V, ObjectAssert> newListAssertInstanceForMethodsChangingElementType(List values) { if (actual instanceof SortedSet) { @@ -1582,8 +1701,9 @@ private AbstractListAssert, V, ObjectAssert> doFlatE * @return a new assertion object whose object under test is a flattened list of all extracted values. */ @CheckReturnValue - public AbstractListAssert, Object, ObjectAssert> flatExtracting(@SuppressWarnings("unchecked") Function... extractors) { - return doFlaExtracting(extractors); + @SafeVarargs + public final AbstractListAssert, Object, ObjectAssert> flatExtracting(Function... extractors) { + return flatExtractingForProxy(extractors); } /** @@ -1613,12 +1733,15 @@ public AbstractListAssert, Object, ObjectAssert, Object, ObjectAssert> flatMap(@SuppressWarnings("unchecked") Function... mappers) { - return doFlaExtracting(mappers); + @SafeVarargs + public final AbstractListAssert, Object, ObjectAssert> flatMap(Function... mappers) { + return flatExtractingForProxy(mappers); } - @SafeVarargs - private final AbstractListAssert, Object, ObjectAssert> doFlaExtracting(Function... extractors) { + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected AbstractListAssert, Object, ObjectAssert> flatExtractingForProxy(Function[] extractors) { Stream actualStream = stream(actual.spliterator(), false); List result = actualStream.flatMap(element -> Stream.of(extractors).map(extractor -> extractor.apply(element))) .collect(toList()); @@ -1661,8 +1784,9 @@ private final AbstractListAssert, Object, ObjectAssert * @since 3.7.0 */ @CheckReturnValue - public AbstractListAssert, Object, ObjectAssert> flatExtracting(@SuppressWarnings("unchecked") ThrowingExtractor... extractors) { - return doFlatExtracting(extractors); + @SafeVarargs + public final AbstractListAssert, Object, ObjectAssert> flatExtracting(ThrowingExtractor... extractors) { + return flatExtractingForProxy(extractors); } /** @@ -1701,16 +1825,9 @@ public AbstractListAssert AbstractListAssert, Object, ObjectAssert> flatMap(@SuppressWarnings("unchecked") ThrowingExtractor... mappers) { - return doFlatExtracting(mappers); - } - @SafeVarargs - private final AbstractListAssert, Object, ObjectAssert> doFlatExtracting(ThrowingExtractor... mappers) { - Stream actualStream = stream(actual.spliterator(), false); - List result = actualStream.flatMap(element -> Stream.of(mappers).map(extractor -> extractor.apply(element))) - .collect(toList()); - return newListAssertInstanceForMethodsChangingElementType(result); + public final AbstractListAssert, Object, ObjectAssert> flatMap(ThrowingExtractor... mappers) { + return flatExtractingForProxy(mappers); } /** @@ -1816,12 +1933,15 @@ public AbstractListAssert, Object, ObjectAssert, Tuple, ObjectAssert> extracting(@SuppressWarnings("unchecked") Function... extractors) { - return doExtracting(extractors); + @SafeVarargs + public final AbstractListAssert, Tuple, ObjectAssert> extracting(Function... extractors) { + return extractingForProxy(extractors); } - @SafeVarargs - private final AbstractListAssert, Tuple, ObjectAssert> doExtracting(Function... extractors) { + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected AbstractListAssert, Tuple, ObjectAssert> extractingForProxy(Function[] extractors) { // combine all extractors into one function Function tupleExtractor = objectToExtractValueFrom -> new Tuple(Stream.of(extractors) .map(extractor -> extractor.apply(objectToExtractValueFrom)) @@ -1880,8 +2000,9 @@ private final AbstractListAssert, Tuple, ObjectAssert, Tuple, ObjectAssert> map(@SuppressWarnings("unchecked") Function... mappers) { - return doExtracting(mappers); + @SafeVarargs + public final AbstractListAssert, Tuple, ObjectAssert> map(Function... mappers) { + return extractingForProxy(mappers); } /** @@ -1950,6 +2071,8 @@ public SELF hasSameElementsAs(Iterable iterable) { } /** + * Deprecated javadoc + *

* Allows to set a comparator to compare properties or fields of elements with the given names. * A typical usage is for comparing fields of numeric type at a given precision. *

@@ -1958,7 +2081,6 @@ public SELF hasSameElementsAs(Iterable iterable) { *

  • {@link #usingFieldByFieldElementComparator}
  • *
  • {@link #usingElementComparatorOnFields}
  • *
  • {@link #usingElementComparatorIgnoringFields}
  • - *
  • {@link #usingRecursiveFieldByFieldElementComparator}
  • * *

    * Comparators specified by this method have precedence over comparators specified by @@ -2010,7 +2132,22 @@ public SELF hasSameElementsAs(Iterable iterable) { * @param elementPropertyOrFieldNames the names of the properties and/or fields of the elements the comparator should be used for * @return {@code this} assertions object * @since 2.5.0 / 3.5.0 + * @deprecated This method is used with {@link #usingFieldByFieldElementComparator()} which is deprecated in favor of + * {@link #usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration)} or {@link #usingRecursiveComparison()}. + *

    + * When using {@link #usingRecursiveComparison()} the equivalent is: + *

      + *
    • {@link RecursiveComparisonAssert#withEqualsForFields(java.util.function.BiPredicate, String...)}
    • + *
    • {@link RecursiveComparisonAssert#withComparatorForFields(Comparator, String...)}
    • + *
    + *

    + * and when using {@link RecursiveComparisonConfiguration}: + *

      + *
    • {@link RecursiveComparisonConfiguration.Builder#withEqualsForFields(java.util.function.BiPredicate, String...)}
    • + *
    • {@link RecursiveComparisonConfiguration.Builder#withComparatorForFields(Comparator, String...)}
    • + *
    */ + @Deprecated @CheckReturnValue public SELF usingComparatorForElementFieldsWithNames(Comparator comparator, String... elementPropertyOrFieldNames) { @@ -2021,6 +2158,8 @@ public SELF usingComparatorForElementFieldsWithNames(Comparator comparato } /** + * Deprecated javadoc + *

    * Allows to set a specific comparator to compare properties or fields of elements with the given type. * A typical usage is for comparing fields of numeric type at a given precision. *

    @@ -2029,7 +2168,6 @@ public SELF usingComparatorForElementFieldsWithNames(Comparator comparato *

  • {@link #usingFieldByFieldElementComparator}
  • *
  • {@link #usingElementComparatorOnFields}
  • *
  • {@link #usingElementComparatorIgnoringFields}
  • - *
  • {@link #usingRecursiveFieldByFieldElementComparator}
  • * *

    * Comparators specified by {@link #usingComparatorForElementFieldsWithNames(Comparator, String...) usingComparatorForElementFieldsWithNames} @@ -2079,7 +2217,22 @@ public SELF usingComparatorForElementFieldsWithNames(Comparator comparato * @param type the {@link java.lang.Class} of the type of the element fields the comparator should be used for * @return {@code this} assertions object * @since 2.5.0 / 3.5.0 + * @deprecated This method is used with {@link #usingFieldByFieldElementComparator()} which is deprecated in favor of + * {@link #usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration)} or {@link #usingRecursiveComparison()}. + *

    + * When using {@link #usingRecursiveComparison()} the equivalent is: + *

      + *
    • {@link RecursiveComparisonAssert#withEqualsForType(java.util.function.BiPredicate, Class)}
    • + *
    • {@link RecursiveComparisonAssert#withComparatorForType(Comparator, Class)}
    • + *
    + *

    + * and when using {@link RecursiveComparisonConfiguration}: + *

      + *
    • {@link RecursiveComparisonConfiguration.Builder#withEqualsForType(java.util.function.BiPredicate, Class)}
    • + *
    • {@link RecursiveComparisonConfiguration.Builder#withComparatorForType(Comparator, Class)}
    • + *
    */ + @Deprecated @CheckReturnValue public SELF usingComparatorForElementFieldsWithType(Comparator comparator, Class type) { getComparatorsForElementPropertyOrFieldTypes().put(type, comparator); @@ -2096,7 +2249,6 @@ public SELF usingComparatorForElementFieldsWithType(Comparator comparator *
  • {@link #usingFieldByFieldElementComparator}
  • *
  • {@link #usingElementComparatorOnFields}
  • *
  • {@link #usingElementComparatorIgnoringFields}
  • - *
  • {@link #usingRecursiveFieldByFieldElementComparator}
  • * *

    * Example: @@ -2126,6 +2278,8 @@ public SELF usingComparatorForType(Comparator comparator, Class type) } /** + * Deprecated javadoc + *

    * Use field/property by field/property comparison (including inherited fields/properties) instead of relying on * actual type A equals method to compare group elements for incoming assertion checks. Private fields * are included but this can be disabled using {@link Assertions#setAllowExtractingPrivateFields(boolean)}. @@ -2150,61 +2304,99 @@ public SELF usingComparatorForType(Comparator comparator, Class type) * assertThat(newArrayList(frodo)).usingFieldByFieldElementComparator().contains(frodoClone); * * @return {@code this} assertion object. + * @deprecated This method is deprecated because it performs a shallow field by field comparison, i.e. elements are compared + * field by field but the fields are compared with equals, use {@link #usingRecursiveFieldByFieldElementComparator()} + * or {@link #usingRecursiveComparison()} instead to perform a true recursive comparison. + *
    See https://assertj.github.io/doc/#assertj-core-recursive-comparison */ @CheckReturnValue + @Deprecated public SELF usingFieldByFieldElementComparator() { return usingExtendedByTypesElementComparator(new FieldByFieldComparator(comparatorsForElementPropertyOrFieldNames, getComparatorsForElementPropertyOrFieldTypes())); } /** - * Use a recursive field/property by field/property comparison (including inherited fields/properties) - * instead of relying on actual type equals method to compare group elements for incoming - * assertion checks. This can be useful if actual's {@code equals} implementation does not suit you. + * Enable using a recursive field by field comparison strategy similar to {@link #usingRecursiveComparison()} but contrary to the latter you can chain any iterable assertions after this method (this is why this method exists). *

    - * The recursive property/field comparison is not applied on fields having a custom {@code equals} - * implementation, i.e. the overridden {@code equals} method will be used instead of a field/property by field/property - * comparison. + * This method uses the default {@link RecursiveComparisonConfiguration}, if you need to customize it use {@link #usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration)} instead. *

    - * The recursive comparison handles cycles. + * Breaking change: since 3.20.0 the comparison won't use any comparators set with: + *

      + *
    • {@link #usingComparatorForType(Comparator, Class)}
    • + *
    • {@link #withTypeComparators(TypeComparators)}
    • + *
    • {@link #usingComparatorForElementFieldsWithType(Comparator, Class)}
    • + *
    • {@link #withComparatorsForElementPropertyOrFieldTypes(TypeComparators)}
    • + *
    • {@link #usingComparatorForElementFieldsWithNames(Comparator, String...)}
    • + *
    • {@link #withComparatorsForElementPropertyOrFieldNames(Map)}
    • + *
    *

    - * You can specify a custom comparator per (nested) name or type of element field with - * {@link #usingComparatorForElementFieldsWithNames(Comparator, String...) usingComparatorForElementFieldsWithNames} - * and {@link #usingComparatorForElementFieldsWithType(Comparator, Class) usingComparatorForElementFieldsWithType}. + * These features (and many more) are provided through {@link #usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration)} with a customized {@link RecursiveComparisonConfiguration} where there methods are called: + *

      + *
    • {@link RecursiveComparisonConfiguration#registerComparatorForType(Comparator, Class) registerComparatorForType(Comparator, Class)} / {@link RecursiveComparisonConfiguration.Builder#withComparatorForType(Comparator, Class) withComparatorForType(Comparator, Class)} (using {@link RecursiveComparisonConfiguration.Builder})
    • + *
    • {@link RecursiveComparisonConfiguration#registerEqualsForType(java.util.function.BiPredicate, Class) registerEqualsForType(BiPredicate, Class)} / {@link RecursiveComparisonConfiguration.Builder#withComparatorForType(Comparator, Class) withComparatorForType(Comparator, Class)} (using {@link RecursiveComparisonConfiguration.Builder})
    • + *
    • {@link RecursiveComparisonConfiguration#registerComparatorForFields(Comparator, String...) registerComparatorForFields(Comparator comparator, String... fields)} / {@link RecursiveComparisonConfiguration.Builder#withComparatorForFields(Comparator, String...) withComparatorForField(Comparator comparator, String... fields)} (using {@link RecursiveComparisonConfiguration.Builder})
    • + *
    *

    - * The objects to compare can be of different types but must have the same properties/fields. For example if actual - * object has a {@code name} String field, the other object must also have one. + * There are differences between this approach and {@link #usingRecursiveComparison()}: + *

      + *
    • contrary to {@link RecursiveComparisonAssert}, you can chain any iterable assertions after this method.
    • + *
    • no comparators registered with {@link AbstractIterableAssert#usingComparatorForType(Comparator, Class)} will be used, you need to register them in the configuration object.
    • + *
    • the assertion errors won't be as detailed as {@link RecursiveComparisonAssert#isEqualTo(Object)} which shows the field differences.
    • + *
    *

    - * If an object has a field and a property with the same name, the property value will be used over the field. + * This last point makes sense, take the {@link #contains(Object...)} assertion, it would not be relevant to report the differences of all the iterable's elements differing from the values to look for. *

    * Example: - *

     TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);
    -   * TolkienCharacter pippin = new TolkienCharacter("Pippin", 28, HOBBIT);
    -   * frodo.setFriend(pippin);
    -   * pippin.setFriend(frodo);
    +   * 
     public class Person {
    +   *   String name;
    +   *   boolean hasPhd;
    +   * }
        *
    -   * TolkienCharacter frodoClone = new TolkienCharacter("Frodo", 33, HOBBIT);
    -   * TolkienCharacter pippinClone = new TolkienCharacter("Pippin", 28, HOBBIT);
    -   * frodoClone.setFriend(pippinClone);
    -   * pippinClone.setFriend(frodoClone);
    +   * public class Doctor {
    +   *  String name;
    +   *  boolean hasPhd;
    +   * }
    +   *
    +   * Doctor drSheldon = new Doctor("Sheldon Cooper", true);
    +   * Doctor drLeonard = new Doctor("Leonard Hofstadter", true);
    +   * Doctor drRaj = new Doctor("Raj Koothrappali", true);
    +   *
    +   * Person sheldon = new Person("Sheldon Cooper", true);
    +   * Person leonard = new Person("Leonard Hofstadter", true);
    +   * Person raj = new Person("Raj Koothrappali", true);
    +   * Person howard = new Person("Howard Wolowitz", true);
        *
    -   * List<TolkienCharacter> hobbits = Arrays.asList(frodo, pippin);
    +   * List<Doctor> doctors = list(drSheldon, drLeonard, drRaj);
    +   * List<Person> people = list(sheldon, leonard, raj);
        *
    -   * // fails if equals has not been overridden in TolkienCharacter as it would compares object references
    -   * assertThat(hobbits).contains(frodoClone, pippinClone);
    +   * // assertion succeeds as both lists contains equivalent items in order.
    +   * assertThat(doctors).usingRecursiveFieldByFieldElementComparator()
    +   *                    .contains(sheldon);
        *
    -   * // frodo/frodoClone and pippin/pippinClone are equals when doing a recursive property/field by property/field comparison
    -   * assertThat(hobbits).usingRecursiveFieldByFieldElementComparator()
    -   *                    .contains(frodoClone, pippinClone);
    -   * 
    + * // assertion fails because leonard names are different. + * leonard.setName("Leonard Ofstater"); + * assertThat(doctors).usingRecursiveFieldByFieldElementComparator() + * .contains(leonard); + * + * // assertion fails because howard is missing and leonard is not expected. + * people = list(howard, sheldon, raj) + * assertThat(doctors).usingRecursiveFieldByFieldElementComparator() + * .contains(howard);
    + *

    + * Another point worth mentioning: elements order does matter if the expected iterable is ordered, for example comparing a {@code Set} to a {@code List} fails as {@code List} is ordered and {@code Set} is not.
    + * The ordering can be ignored by calling {@link RecursiveComparisonAssert#ignoringCollectionOrder ignoringCollectionOrder} allowing ordered/unordered iterable comparison, note that {@link RecursiveComparisonAssert#ignoringCollectionOrder ignoringCollectionOrder} is applied recursively on any nested iterable fields, if this behavior is too generic, + * use the more fine grained {@link RecursiveComparisonAssert#ignoringCollectionOrderInFields(String...) ignoringCollectionOrderInFields} or + * {@link RecursiveComparisonAssert#ignoringCollectionOrderInFieldsMatchingRegexes(String...) ignoringCollectionOrderInFieldsMatchingRegexes}. * * @return {@code this} assertion object. - * @since 2.5.0 / 3.5.0 + * @since 2.5.0 / 3.5.0 - breaking change in 3.20.0 + * @see RecursiveComparisonConfiguration + * @see usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration) */ @CheckReturnValue public SELF usingRecursiveFieldByFieldElementComparator() { - return usingExtendedByTypesElementComparator(new RecursiveFieldByFieldComparator(comparatorsForElementPropertyOrFieldNames, - getComparatorsForElementPropertyOrFieldTypes())); + return usingRecursiveFieldByFieldElementComparator(new RecursiveComparisonConfiguration()); } /** @@ -2384,9 +2576,10 @@ public SELF usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfi * * @return a new {@link RecursiveComparisonAssert} instance * @see RecursiveComparisonConfiguration RecursiveComparisonConfiguration + * @since 3.15.0 */ - @Override @Beta + @Override public RecursiveComparisonAssert usingRecursiveComparison() { // overridden for javadoc and to make this method public return super.usingRecursiveComparison(); @@ -2400,13 +2593,17 @@ public RecursiveComparisonAssert usingRecursiveComparison() { * @param recursiveComparisonConfiguration the {@link RecursiveComparisonConfiguration} used in the chained {@link RecursiveComparisonAssert#isEqualTo(Object) isEqualTo} assertion. * * @return a new {@link RecursiveComparisonAssert} instance built with the given {@link RecursiveComparisonConfiguration}. + * @since 3.15.0 */ + @Beta @Override public RecursiveComparisonAssert usingRecursiveComparison(RecursiveComparisonConfiguration recursiveComparisonConfiguration) { return super.usingRecursiveComparison(recursiveComparisonConfiguration).withTypeComparators(comparatorsByType); } /** + * Deprecated javadoc + *

    * Use field/property by field/property comparison on the given fields/properties only (including inherited * fields/properties) instead of relying on actual type A equals method to compare group elements for * incoming assertion checks. Private fields are included but this can be disabled using @@ -2433,7 +2630,13 @@ public RecursiveComparisonAssert usingRecursiveComparison(RecursiveComparison * * @param fields the fields/properties to compare using element comparators * @return {@code this} assertion object. + * @see #usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration) + * @see https://assertj.github.io/doc/#assertj-core-recursive-comparison + * @deprecated This method is deprecated because it performs a shallow field by field comparison, i.e. elements are + * compared field by field but the fields are compared with equals, use {@link #usingRecursiveFieldByFieldElementComparatorOnFields(String...)} instead. + *
    See https://assertj.github.io/doc/#assertj-core-recursive-comparison */ + @Deprecated @CheckReturnValue public SELF usingElementComparatorOnFields(String... fields) { return usingExtendedByTypesElementComparator(new OnFieldsComparator(comparatorsForElementPropertyOrFieldNames, @@ -2441,12 +2644,63 @@ public SELF usingElementComparatorOnFields(String... fields) { fields)); } + /** + * The assertions chained after this method will use a recursive field by field comparison on the given fields (including + * inherited fields) instead of relying on the element equals method. + * This is handy when the element equals method is not overridden or implemented as you expect. + *

    + * Nested fields are supported and are expressed like: {@code name.first} + *

    + * The comparison is recursive: elements are compared field by field, if a field type has fields they are also compared + * field by field (and so on). + *

    + * Example: + *

     Player derrickRose = new Player(new Name("Derrick", "Rose"), "Chicago Bulls");
    +   * derrickRose.nickname = new Name("Crazy", "Dunks");
    +   *
    +   * Player jalenRose = new Player(new Name("Jalen", "Rose"), "Chicago Bulls");
    +   * jalenRose.nickname = new Name("Crazy", "Defense");
    +   *
    +   * // assertion succeeds as all compared fields match
    +   * assertThat(list(derrickRose)).usingRecursiveFieldByFieldElementComparatorOnFields("name.last", "team", "nickname.first")
    +   *                              .contains(jalenRose);
    +   *
    +   * // assertion fails, name.first values differ
    +   * assertThat(list(derrickRose)).usingRecursiveFieldByFieldElementComparatorOnFields("name")
    +   *                              .contains(jalenRose);
    + *

    + * This method is actually a shortcut of {@link #usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration)} + * with a configuration comparing only the given fields, the previous example can be written as: + *

     RecursiveComparisonConfiguration configuration = RecursiveComparisonConfiguration.builder()
    +   *                                                                                  .withComparedFields("name.last", "team", "nickname.first")
    +   *                                                                                  .build();
    +   *
    +   * assertThat(list(derrickRose)).usingRecursiveFieldByFieldElementComparator(configuration)
    +   *                              .contains(jalenRose);
    + * The recursive comparison is documented here: https://assertj.github.io/doc/#assertj-core-recursive-comparison + *

    + * @param fields the field names to exclude in the elements comparison. + * @return {@code this} assertion object. + * @since 3.20.0 + * @see #usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration) + * @see https://assertj.github.io/doc/#assertj-core-recursive-comparison + */ + @CheckReturnValue + public SELF usingRecursiveFieldByFieldElementComparatorOnFields(String... fields) { + RecursiveComparisonConfiguration recursiveComparisonConfiguration = RecursiveComparisonConfiguration.builder() + .withComparedFields(fields) + .build(); + return usingRecursiveFieldByFieldElementComparator(recursiveComparisonConfiguration); + } + protected SELF usingComparisonStrategy(ComparisonStrategy comparisonStrategy) { iterables = new Iterables(comparisonStrategy); return myself; } /** + * Deprecated javadoc + *

    * Use field/property by field/property comparison on all fields/properties except the given ones (including inherited * fields/properties) instead of relying on actual type A equals method to compare group elements for * incoming assertion checks. Private fields are included but this can be disabled using @@ -2471,9 +2725,15 @@ protected SELF usingComparisonStrategy(ComparisonStrategy comparisonStrategy) { * // ... but not when comparing both name and race * assertThat(newArrayList(frodo)).usingElementComparatorIgnoringFields("age").contains(sam); // FAIL * - * @param fields the fields/properties to compare using element comparators + * @param fields the field names to exclude in the elements comparison. * @return {@code this} assertion object. + * @see #usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration) + * @see https://assertj.github.io/doc/#assertj-core-recursive-comparison + * @deprecated This method is deprecated because it performs a shallow field by field comparison, i.e. elements are + * compared field by field but the fields are compared with equals, use {@link #usingRecursiveFieldByFieldElementComparatorIgnoringFields(String...)} instead. + *
    See https://assertj.github.io/doc/#assertj-core-recursive-comparison */ + @Deprecated @CheckReturnValue public SELF usingElementComparatorIgnoringFields(String... fields) { return usingExtendedByTypesElementComparator(new IgnoringFieldsComparator(comparatorsForElementPropertyOrFieldNames, @@ -2481,6 +2741,55 @@ public SELF usingElementComparatorIgnoringFields(String... fields) { fields)); } + /** + * The assertions chained after this method will use a recursive field by field comparison on all fields (including inherited + * fields) except the given ones instead of relying on the element equals method. + * This is handy when the element equals method is not overridden or implemented as you expect. + *

    + * Nested fields are supported and are expressed like: {@code name.first} + *

    + * The comparison is recursive: elements are compared field by field, if a field type has fields they are also compared + * field by field (and so on). + *

    + * Example: + *

     Player derrickRose = new Player(new Name("Derrick", "Rose"), "Chicago Bulls");
    +   * derrickRose.nickname = new Name("Crazy", "Dunks");
    +   *
    +   * Player jalenRose = new Player(new Name("Jalen", "Rose"), "Chicago Bulls");
    +   * jalenRose.nickname = new Name("Crazy", "Defense");
    +   *
    +   * // assertion succeeds
    +   * assertThat(list(derrickRose)).usingRecursiveFieldByFieldElementComparatorIgnoringFields("name.first", "nickname.last")
    +   *                              .contains(jalenRose);
    +   *
    +   * // assertion fails, names are ignored but nicknames are not and nickname.last values differ
    +   * assertThat(list(derrickRose)).usingRecursiveFieldByFieldElementComparatorIgnoringFields("name")
    +   *                              .contains(jalenRose);
    + *

    + * This method is actually a shortcut of {@link #usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration)} + * with a configuration ignoring the given fields, the previous example can be written as: + *

     RecursiveComparisonConfiguration configuration = RecursiveComparisonConfiguration.builder()
    +   *                                                                                  .withIgnoredFields("name.first", "nickname.last")
    +   *                                                                                  .build();
    +   *
    +   * assertThat(list(derrickRose)).usingRecursiveFieldByFieldElementComparator(configuration)
    +   *                              .contains(jalenRose);
    + * The recursive comparison is documented here: https://assertj.github.io/doc/#assertj-core-recursive-comparison + *

    + * @param fields the field names to exclude in the elements comparison. + * @return {@code this} assertion object. + * @since 3.20.0 + * @see #usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration) + * @see https://assertj.github.io/doc/#assertj-core-recursive-comparison + */ + @CheckReturnValue + public SELF usingRecursiveFieldByFieldElementComparatorIgnoringFields(String... fields) { + RecursiveComparisonConfiguration recursiveComparisonConfiguration = RecursiveComparisonConfiguration.builder() + .withIgnoredFields(fields) + .build(); + return usingRecursiveFieldByFieldElementComparator(recursiveComparisonConfiguration); + } + /** * Enable hexadecimal representation of Iterable elements instead of standard representation in error messages. *

    @@ -3068,6 +3377,68 @@ public ELEMENT_ASSERT element(int index) { return internalElement(index); } + /** + * Allow to perform assertions on the elements corresponding to the given indices + * (the iterable {@link Iterable} under test is changed to an iterable with the selected elements). + *

    + * Example: + *

     Iterable<TolkienCharacter> hobbits = newArrayList(frodo, sam, pippin);
    +   *
    +   * // assertion succeeds
    +   * assertThat(hobbits).elements(1, 2)
    +   *                    .hasSize(2)
    +   *                    .containsExactly(sam, pippin);
    +   *
    +   * // assertion fails
    +   * assertThat(hobbits).element(1, 2)
    +   *                    .containsExactly(frodo, pippin);
    + *

    + * + * @param indices the elements indices + * @return the assertion on the given elements + * @throws IllegalArgumentException if indices array is null or empty + * @throws AssertionError if one of the given indices is out of bound or if the actual is empty + * @since 3.20 + */ + @CheckReturnValue + public SELF elements(int... indices) { + isNotEmpty(); + assertIndicesIsNotNull(indices); + assertIndicesIsNotEmpty(indices); + + List indexedActual = newArrayList(actual); + + List filteredIterable = Arrays.stream(indices) + .peek(index -> checkIndexValidity(index, indexedActual)) + .mapToObj(indexedActual::get) + .collect(toList()); + // For soft assertions/assumptions, this must return a proxied iterable assert but we can't put "elements" in + // SoftProxies.METHODS_CHANGING_THE_OBJECT_UNDER_TEST because these methods are not proxied. + // We want to proxy elements(int... indices) to capture isNotEmpty and checkIndexValidity assertion errors. + // The solution is to introduce newAbstractIterableAssertForProxy which is going to be proxied as newAbstractIterableAssert + // was added to SoftProxies.METHODS_CHANGING_THE_OBJECT_UNDER_TEST list and SoftProxies.methodsChangingTheObjectUnderTestNamed + // will select newAbstractIterableAssertForProxy to be proxied. + return newAbstractIterableAssertForProxy(filteredIterable); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + protected SELF newAbstractIterableAssertForProxy(List filteredIterable) { + return newAbstractIterableAssert(filteredIterable).withAssertionState(myself); + } + + private static void assertIndicesIsNotNull(int[] indices) { + if (indices == null) throw new IllegalArgumentException("indices must not be null"); + } + + private static void assertIndicesIsNotEmpty(int[] indices) { + if (indices.length == 0) throw new IllegalArgumentException("indices must not be empty"); + } + + private void checkIndexValidity(int index, List indexedActual) { + assertThat(indexedActual).describedAs("check actual size is enough to get element[" + index + "]") + .hasSizeGreaterThan(index); + } + /** * Navigate and allow to perform assertions on the chosen element of the {@link Iterable} under test. *

    @@ -3370,13 +3741,29 @@ public SELF noneSatisfy(Consumer restrictions) { } @Override - public SELF satisfiesExactly(@SuppressWarnings("unchecked") Consumer... requirements) { + @SafeVarargs + public final SELF satisfiesExactly(Consumer... requirements) { + return satisfiesExactlyForProxy(requirements); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF satisfiesExactlyForProxy(Consumer[] requirements) { iterables.assertSatisfiesExactly(info, actual, requirements); return myself; } @Override - public SELF satisfiesExactlyInAnyOrder(@SuppressWarnings("unchecked") Consumer... requirements) { + @SafeVarargs + public final SELF satisfiesExactlyInAnyOrder(Consumer... requirements) { + return satisfiesExactlyInAnyOrderForProxy(requirements); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF satisfiesExactlyInAnyOrderForProxy(Consumer[] requirements) { iterables.assertSatisfiesExactlyInAnyOrder(info, actual, requirements); return myself; } diff --git a/src/main/java/org/assertj/core/api/AbstractMapAssert.java b/src/main/java/org/assertj/core/api/AbstractMapAssert.java index c426c2c073f..5250ef0b442 100644 --- a/src/main/java/org/assertj/core/api/AbstractMapAssert.java +++ b/src/main/java/org/assertj/core/api/AbstractMapAssert.java @@ -12,6 +12,7 @@ */ package org.assertj.core.api; +import static java.util.Collections.singleton; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.entry; @@ -455,23 +456,24 @@ public SELF hasSameSizeAs(Iterable other) { * Verifies that the actual map has the same size as the given {@link Map}. *

    * Examples: - *

     Map<Ring, TolkienCharacter> ringBearers = new HashMap<>();
    -   * ringBearers.put(nenya, galadriel);
    -   * ringBearers.put(narya, gandalf);
    -   * ringBearers.put(vilya, elrond);
    -   * ringBearers.put(oneRing, frodo);
    +   * 
     import static com.google.common.collect.ImmutableMap.of;
        *
    -   * // assertion will pass
    -   * assertThat(ringBearers).hasSameSizeAs(mapOf(entry(oneRing, frodo),
    -   *                                             entry(narya, gandalf),
    -   *                                             entry(nenya, galadriel),
    -   *                                             entry(vilya, elrond)));
    +   * Map<Ring, TolkienCharacter> ringBearers = ImmutableMap.of(nenya, galadriel,
    +   *                                                           narya, gandalf,
    +   *                                                           vilya, elrond,
    +   *                                                           oneRing, frodo);
        *
    -   * // assertions will fail
    -   * assertThat(elvesRingBearers).hasSameSizeAs(new HashMap());
    -   * Map<String, String> keyToValue = new HashMap();
    -   * keyToValue.put("key", "value");
    -   * assertThat(keyToValue).hasSameSizeAs(keyToValue);
    + * // assertion succeeds: + * assertThat(ringBearers).hasSameSizeAs(ImmutableMap.of(oneRing, frodo, + * narya, gandalf, + * nenya, galadriel, + * vilya, elrond)); + * + * // assertions fails: + * assertThat(ringBearers).hasSameSizeAs(Collections.emptyMap()); + * assertThat(ringBearers).hasSameSizeAs(ImmutableMap.of(nenya, galadriel, + * narya, gandalf, + * vilya, elrond));
    * * @param other the {@code Map} to compare size with actual map * @return {@code this} assertion object @@ -512,7 +514,15 @@ public SELF hasSameSizeAs(Map other) { * @throws AssertionError if the actual map is {@code null}. * @throws AssertionError if the actual map does not contain the given entries. */ - public SELF contains(@SuppressWarnings("unchecked") Map.Entry... entries) { + @SafeVarargs + public final SELF contains(Map.Entry... entries) { + return containsForProxy(entries); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF containsForProxy(Map.Entry[] entries) { maps.assertContains(info, actual, entries); return myself; } @@ -543,7 +553,15 @@ public SELF contains(@SuppressWarnings("unchecked") Map.Entry... entries) { + @SafeVarargs + public final SELF containsAnyOf(Map.Entry... entries) { + return containsAnyOfForProxy(entries); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF containsAnyOfForProxy(Map.Entry[] entries) { maps.assertContainsAnyOf(info, actual, entries); return myself; } @@ -563,10 +581,11 @@ public SELF containsAnyOf(@SuppressWarnings("unchecked") Map.Entry * * @param other the map with the given entries. @@ -577,7 +596,7 @@ public SELF containsAnyOf(@SuppressWarnings("unchecked") Map.Entry other) { - maps.assertContains(info, actual, toEntries(other)); + maps.assertContainsAllEntriesOf(info, actual, other); return myself; } @@ -956,7 +975,15 @@ public SELF hasValueSatisfying(Condition valueCondition) { * @throws AssertionError if the actual map is {@code null}. * @throws AssertionError if the actual map contains any of the given entries. */ - public SELF doesNotContain(@SuppressWarnings("unchecked") Map.Entry... entries) { + @SafeVarargs + public final SELF doesNotContain(Map.Entry... entries) { + return doesNotContainForProxy(entries); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF doesNotContainForProxy(Map.Entry[] entries) { maps.assertDoesNotContain(info, actual, entries); return myself; } @@ -1010,7 +1037,6 @@ public SELF doesNotContainEntry(K key, V value) { * @throws AssertionError if the actual map is {@code null}. * @throws AssertionError if the actual map does not contain the given key. */ - @SuppressWarnings("unchecked") public SELF containsKey(K key) { return containsKeys(key); } @@ -1037,7 +1063,15 @@ public SELF containsKey(K key) { * @throws AssertionError if the actual map does not contain the given key. * @throws IllegalArgumentException if the given argument is an empty array. */ - public SELF containsKeys(@SuppressWarnings("unchecked") K... keys) { + @SafeVarargs + public final SELF containsKeys(K... keys) { + return containsKeysForProxy(keys); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF containsKeysForProxy(K[] keys) { maps.assertContainsKeys(info, actual, keys); return myself; } @@ -1062,7 +1096,6 @@ public SELF containsKeys(@SuppressWarnings("unchecked") K... keys) { * @throws AssertionError if the actual map is {@code null}. * @throws AssertionError if the actual map contains the given key. */ - @SuppressWarnings("unchecked") public SELF doesNotContainKey(K key) { return doesNotContainKeys(key); } @@ -1088,14 +1121,26 @@ public SELF doesNotContainKey(K key) { * @throws AssertionError if the actual map is {@code null}. * @throws AssertionError if the actual map contains the given key. */ - public SELF doesNotContainKeys(@SuppressWarnings("unchecked") K... keys) { + @SafeVarargs + public final SELF doesNotContainKeys(K... keys) { + return doesNotContainKeysForProxy(keys); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF doesNotContainKeysForProxy(K[] keys) { maps.assertDoesNotContainKeys(info, actual, keys); return myself; } /** * Verifies that the actual map contains only the given keys and nothing else, in any order. - * + *

    + * The verification tries to honor the key comparison semantic of the underlying map implementation. + * The map under test has to be cloned to identify unexpected elements, but depending on the map implementation + * this may not always be possible. In case it is not possible, a regular map is used and the key comparison strategy + * may not be the same as the map under test. *

    * Examples : *

     Map<Ring, TolkienCharacter> ringBearers = new HashMap<>();
    @@ -1117,15 +1162,26 @@ public SELF doesNotContainKeys(@SuppressWarnings("unchecked") K... keys) {
        *           of the given keys, or the actual map contains more entries than the given ones.
        * @throws IllegalArgumentException if the given argument is an empty array.
        */
    +  @SafeVarargs
    +  public final SELF containsOnlyKeys(K... keys) {
    +    return containsOnlyKeysForProxy(keys);
    +  }
     
    -  public SELF containsOnlyKeys(@SuppressWarnings("unchecked") K... keys) {
    +  // This method is protected in order to be proxied for SoftAssertions / Assumptions.
    +  // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs
    +  // in order to avoid compiler warning in user code
    +  protected SELF containsOnlyKeysForProxy(K[] keys) {
         maps.assertContainsOnlyKeys(info, actual, keys);
         return myself;
       }
     
       /**
        * Verifies that the actual map contains only the given keys and nothing else, in any order.
    -   *
    +   * 

    + * The verification tries to honor the key comparison semantic of the underlying map implementation. + * The map under test has to be cloned to identify unexpected elements, but depending on the map implementation + * this may not always be possible. In case it is not possible, a regular map is used and the key comparison strategy + * may not be the same as the map under test. *

    * Examples : *

     Map<Ring, TolkienCharacter> ringBearers = new HashMap<>();
    @@ -1154,7 +1210,7 @@ public SELF containsOnlyKeys(Iterable keys) {
         if (keys instanceof Path) {
           // do not treat Path as an Iterable
           K path = (K) keys;
    -      maps.assertContainsOnlyKeys(info, actual, path);
    +      maps.assertContainsOnlyKeys(info, actual, singleton(path));
         } else {
           maps.assertContainsOnlyKeys(info, actual, keys);
         }
    @@ -1209,7 +1265,15 @@ public SELF containsValue(V value) {
        * @throws AssertionError if the actual map is {@code null}.
        * @throws AssertionError if the actual map does not contain the given values.
        */
    -  public SELF containsValues(@SuppressWarnings("unchecked") V... values) {
    +  @SafeVarargs
    +  public final SELF containsValues(V... values) {
    +    return containsValuesForProxy(values);
    +  }
    +
    +  // This method is protected in order to be proxied for SoftAssertions / Assumptions.
    +  // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs
    +  // in order to avoid compiler warning in user code
    +  protected SELF containsValuesForProxy(V[] values) {
         maps.assertContainsValues(info, actual, values);
         return myself;
       }
    @@ -1242,7 +1306,11 @@ public SELF doesNotContainValue(V value) {
     
       /**
        * Verifies that the actual map contains only the given entries and nothing else, in any order.
    -   *
    +   * 

    + * The verification tries to honor the key comparison semantic of the underlying map implementation. + * The map under test has to be cloned to identify unexpected elements, but depending on the map implementation + * this may not always be possible. In case it is not possible, a regular map is used and the key comparison strategy + * may not be the same as the map under test. *

    * Examples : *

     Map<Ring, TolkienCharacter> ringBearers = new HashMap<>();
    @@ -1251,8 +1319,13 @@ public SELF doesNotContainValue(V value) {
        * ringBearers.put(vilya, elrond);
        * ringBearers.put(oneRing, frodo);
        *
    -   * // assertion will pass
    -   * assertThat(ringBearers).containsOnly(entry(oneRing, frodo), entry(nenya, galadriel), entry(narya, gandalf), entry(vilya, elrond));
    +   * // assertions will pass
    +   * assertThat(ringBearers).containsOnly(entry(oneRing, frodo),
    +   *                                      entry(nenya, galadriel),
    +   *                                      entry(narya, gandalf),
    +   *                                      entry(vilya, elrond));
    +   *
    +   * assertThat(Collections.emptyMap()).containsOnly();
        *
        * // assertion will fail
        * assertThat(ringBearers).containsOnly(entry(oneRing, frodo), entry(nenya, galadriel));
    @@ -1265,7 +1338,15 @@ public SELF doesNotContainValue(V value) { * @throws AssertionError if the actual map does not contain the given entries, i.e. the actual map contains some or * none of the given entries, or the actual map contains more entries than the given ones. */ - public SELF containsOnly(@SuppressWarnings("unchecked") Map.Entry... entries) { + @SafeVarargs + public final SELF containsOnly(Map.Entry... entries) { + return containsOnlyForProxy(entries); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF containsOnlyForProxy(Map.Entry[] entries) { maps.assertContainsOnly(info, actual, entries); return myself; } @@ -1280,11 +1361,13 @@ public SELF containsOnly(@SuppressWarnings("unchecked") Map.Entry... entries) { + @SafeVarargs + public final SELF containsExactly(Map.Entry... entries) { + return containsExactlyForProxy(entries); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF containsExactlyForProxy(Map.Entry[] entries) { maps.assertContainsExactly(info, actual, entries); return myself; } @@ -1607,7 +1698,15 @@ public AbstractListAssert, Object, ObjectAssert> extracting(O * @since 3.14.0 */ @CheckReturnValue - public AbstractListAssert, V, ObjectAssert> extractingByKeys(@SuppressWarnings("unchecked") K... keys) { + @SafeVarargs + public final AbstractListAssert, V, ObjectAssert> extractingByKeys(K... keys) { + return extractingByKeysForProxy(keys); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected AbstractListAssert, V, ObjectAssert> extractingByKeysForProxy(K[] keys) { isNotNull(); List extractedValues = Stream.of(keys).map(actual::get).collect(toList()); String extractedPropertiesOrFieldsDescription = extractedDescriptionOf((Object[]) keys); @@ -1781,7 +1880,15 @@ public AbstractListAssert, Object, ObjectAssert> extractingFr * @since 3.12.0 */ @CheckReturnValue - public AbstractListAssert, Tuple, ObjectAssert> extractingFromEntries(@SuppressWarnings("unchecked") Function, Object>... extractors) { + @SafeVarargs + public final AbstractListAssert, Tuple, ObjectAssert> extractingFromEntries(Function, Object>... extractors) { + return extractingFromEntriesForProxy(extractors); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected AbstractListAssert, Tuple, ObjectAssert> extractingFromEntriesForProxy(Function, Object>[] extractors) { isNotNull(); // combine all extractors into one function Function, Tuple> tupleExtractor = objectToExtractValueFrom -> new Tuple(Stream.of(extractors) diff --git a/src/main/java/org/assertj/core/api/AbstractObjectArrayAssert.java b/src/main/java/org/assertj/core/api/AbstractObjectArrayAssert.java index 03c2682f2ac..0a754876390 100644 --- a/src/main/java/org/assertj/core/api/AbstractObjectArrayAssert.java +++ b/src/main/java/org/assertj/core/api/AbstractObjectArrayAssert.java @@ -57,6 +57,7 @@ import org.assertj.core.groups.Tuple; import org.assertj.core.internal.CommonErrors; import org.assertj.core.internal.ComparatorBasedComparisonStrategy; +import org.assertj.core.internal.ConfigurableRecursiveFieldByFieldComparator; import org.assertj.core.internal.ExtendedByTypesComparator; import org.assertj.core.internal.FieldByFieldComparator; import org.assertj.core.internal.IgnoringFieldsComparator; @@ -65,7 +66,6 @@ import org.assertj.core.internal.ObjectArrays; import org.assertj.core.internal.Objects; import org.assertj.core.internal.OnFieldsComparator; -import org.assertj.core.internal.RecursiveFieldByFieldComparator; import org.assertj.core.internal.TypeComparators; import org.assertj.core.presentation.PredicateDescription; import org.assertj.core.util.CheckReturnValue; @@ -88,6 +88,8 @@ * @author Mateusz Haligowski * @author Lovro Pandzic */ +// suppression of deprecation works in Eclipse to hide warning for the deprecated classes in the imports +@SuppressWarnings("deprecation") public abstract class AbstractObjectArrayAssert, ELEMENT> extends AbstractAssert implements IndexedObjectEnumerableAssert, ELEMENT>, @@ -344,7 +346,15 @@ public SELF hasSameSizeAs(Iterable other) { * @throws AssertionError if the actual array does not contain the given values. */ @Override - public SELF contains(@SuppressWarnings("unchecked") ELEMENT... values) { + @SafeVarargs + public final SELF contains(ELEMENT... values) { + return containsForProxy(values); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF containsForProxy(ELEMENT[] values) { arrays.assertContains(info, actual, values); return myself; } @@ -382,7 +392,15 @@ public SELF contains(@SuppressWarnings("unchecked") ELEMENT... values) { * or none of the given values, or the actual array contains more values than the given ones. */ @Override - public SELF containsOnly(@SuppressWarnings("unchecked") ELEMENT... values) { + @SafeVarargs + public final SELF containsOnly(ELEMENT... values) { + return containsOnlyForProxy(values); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF containsOnlyForProxy(ELEMENT[] values) { arrays.assertContainsOnly(info, actual, values); return myself; } @@ -542,7 +560,15 @@ public SELF hasSameElementsAs(Iterable iterable) { * or none of the given values, or the actual array contains more than once these values. */ @Override - public SELF containsOnlyOnce(@SuppressWarnings("unchecked") ELEMENT... values) { + @SafeVarargs + public final SELF containsOnlyOnce(ELEMENT... values) { + return containsOnlyOnceForProxy(values); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF containsOnlyOnceForProxy(ELEMENT[] values) { arrays.assertContainsOnlyOnce(info, actual, values); return myself; } @@ -576,7 +602,15 @@ public SELF containsOnlyOnceElementsOf(Iterable iterable) { * or values are the same but the order is not. */ @Override - public SELF containsExactly(@SuppressWarnings("unchecked") ELEMENT... values) { + @SafeVarargs + public final SELF containsExactly(ELEMENT... values) { + return containsExactlyForProxy(values); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF containsExactlyForProxy(ELEMENT[] values) { arrays.assertContainsExactly(info, actual, values); return myself; } @@ -602,7 +636,15 @@ public SELF containsExactly(@SuppressWarnings("unchecked") ELEMENT... values) { * contains some or none of the given values, or the actual array contains more values than the given ones. */ @Override - public SELF containsExactlyInAnyOrder(@SuppressWarnings("unchecked") ELEMENT... values) { + @SafeVarargs + public final SELF containsExactlyInAnyOrder(ELEMENT... values) { + return containsExactlyInAnyOrderForProxy(values); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF containsExactlyInAnyOrderForProxy(ELEMENT[] values) { arrays.assertContainsExactlyInAnyOrder(info, actual, values); return myself; } @@ -658,7 +700,15 @@ public SELF containsExactlyElementsOf(Iterable iterable) { * @throws AssertionError if the actual array does not contain the given sequence. */ @Override - public SELF containsSequence(@SuppressWarnings("unchecked") ELEMENT... sequence) { + @SafeVarargs + public final SELF containsSequence(ELEMENT... sequence) { + return containsSequenceForProxy(sequence); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF containsSequenceForProxy(ELEMENT[] sequence) { arrays.assertContainsSequence(info, actual, sequence); return myself; } @@ -715,7 +765,15 @@ public SELF containsSequence(Iterable sequence) { * @throws AssertionError if the actual array does not contain the given sequence. */ @Override - public SELF doesNotContainSequence(@SuppressWarnings("unchecked") ELEMENT... sequence) { + @SafeVarargs + public final SELF doesNotContainSequence(ELEMENT... sequence) { + return doesNotContainSequenceForProxy(sequence); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF doesNotContainSequenceForProxy(ELEMENT[] sequence) { arrays.assertDoesNotContainSequence(info, actual, sequence); return myself; } @@ -769,7 +827,15 @@ public SELF doesNotContainSequence(Iterable sequence) { * @throws AssertionError if the actual array does not contain the given subsequence. */ @Override - public SELF containsSubsequence(@SuppressWarnings("unchecked") ELEMENT... subsequence) { + @SafeVarargs + public final SELF containsSubsequence(ELEMENT... subsequence) { + return containsSubsequenceForProxy(subsequence); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF containsSubsequenceForProxy(ELEMENT[] subsequence) { arrays.assertContainsSubsequence(info, actual, subsequence); return myself; } @@ -821,7 +887,15 @@ public SELF containsSubsequence(Iterable subsequence) { * @throws AssertionError if the actual array contains the given subsequence. */ @Override - public SELF doesNotContainSubsequence(@SuppressWarnings("unchecked") ELEMENT... subsequence) { + @SafeVarargs + public final SELF doesNotContainSubsequence(ELEMENT... subsequence) { + return doesNotContainSubsequenceForProxy(subsequence); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF doesNotContainSubsequenceForProxy(ELEMENT[] subsequence) { arrays.assertDoesNotContainSubsequence(info, actual, subsequence); return myself; } @@ -912,6 +986,37 @@ public SELF hasOnlyElementsOfTypes(Class... types) { return myself; } + /** + * Verifies that the actual elements are of the given types in the given order, there should be as many expected types as there are actual elements. + *

    + * Example: + *

     Object[] objects = { 1, "a", "b", 1.00 };
    +   *
    +   * // assertion succeeds
    +   * assertThat(objects).hasExactlyElementsOfTypes(Integer.class, String.class, String.class, Double.class);
    +   *
    +   * // assertions fail
    +   * // missing second String type
    +   * assertThat(objects).hasExactlyElementsOfTypes(Integer.class, String.class, Double.class);
    +   * // no Float type in actual
    +   * assertThat(objects).hasExactlyElementsOfTypes(Float.class, String.class, String.class, Double.class);
    +   * // correct types but wrong order
    +   * assertThat(objects).hasExactlyElementsOfTypes(String.class, Integer.class, String.class, Double.class);
    +   * // actual has more elements than the specified expected types
    +   * assertThat(objects).hasExactlyElementsOfTypes(String.class);
    + * + * @param expectedTypes the expected types + * @return {@code this} assertion object. + * @throws NullPointerException if the given type array is {@code null}. + * @throws AssertionError if actual is {@code null}. + * @throws AssertionError if the actual elements types don't exactly match the given ones (in the given order). + */ + @Override + public SELF hasExactlyElementsOfTypes(Class... expectedTypes) { + arrays.assertHasExactlyElementsOfTypes(info, actual, expectedTypes); + return myself; + } + /** * Verifies that the actual array does not contain the given object at the given index. *

    @@ -963,7 +1068,15 @@ public SELF doesNotContain(ELEMENT value, Index index) { * @throws AssertionError if the actual array contains any of the given values. */ @Override - public SELF doesNotContain(@SuppressWarnings("unchecked") ELEMENT... values) { + @SafeVarargs + public final SELF doesNotContain(ELEMENT... values) { + return doesNotContainForProxy(values); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF doesNotContainForProxy(ELEMENT[] values) { arrays.assertDoesNotContain(info, actual, values); return myself; } @@ -1039,7 +1152,15 @@ public SELF doesNotHaveDuplicates() { * @throws AssertionError if the actual array does not start with the given sequence of objects. */ @Override - public SELF startsWith(@SuppressWarnings("unchecked") ELEMENT... sequence) { + @SafeVarargs + public final SELF startsWith(ELEMENT... sequence) { + return startsWithForProxy(sequence); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF startsWithForProxy(ELEMENT[] sequence) { arrays.assertStartsWith(info, actual, sequence); return myself; } @@ -1093,7 +1214,15 @@ public SELF endsWith(ELEMENT[] sequence) { * @throws AssertionError if the actual array does not end with the given sequence of objects. */ @Override - public SELF endsWith(ELEMENT first, @SuppressWarnings("unchecked") ELEMENT... sequence) { + @SafeVarargs + public final SELF endsWith(ELEMENT first, ELEMENT... sequence) { + return endsWithForProxy(first, sequence); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF endsWithForProxy(ELEMENT first, ELEMENT[] sequence) { arrays.assertEndsWith(info, actual, first, sequence); return myself; } @@ -1143,7 +1272,15 @@ public SELF isSubsetOf(Iterable values) { * @throws AssertionError if the actual {@code Iterable} is not subset of the given values. */ @Override - public SELF isSubsetOf(@SuppressWarnings("unchecked") ELEMENT... values) { + @SafeVarargs + public final SELF isSubsetOf(ELEMENT... values) { + return isSubsetOfForProxy(values); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF isSubsetOfForProxy(ELEMENT[] values) { arrays.assertIsSubsetOf(info, actual, Arrays.asList(values)); return myself; } @@ -1606,6 +1743,8 @@ public SELF usingDefaultElementComparator() { } /** + * Deprecated javadoc + *

    * Allows to set a comparator to compare properties or fields of elements with the given names. * A typical usage is for comparing fields of numeric type at a given precision. *

    @@ -1667,7 +1806,22 @@ public SELF usingDefaultElementComparator() { * @param elementPropertyOrFieldNames the names of the properties and/or fields of the elements the comparator should be used for * @return {@code this} assertions object * @since 2.5.0 / 3.5.0 + * @deprecated This method is used with {@link #usingFieldByFieldElementComparator()} which is deprecated in favor of + * {@link #usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration)} or {@link #usingRecursiveComparison()}. + *

    + * When using {@link #usingRecursiveComparison()} the equivalent is: + *

      + *
    • {@link RecursiveComparisonAssert#withEqualsForFields(java.util.function.BiPredicate, String...)}
    • + *
    • {@link RecursiveComparisonAssert#withComparatorForFields(Comparator, String...)}
    • + *
    + *

    + * and when using {@link RecursiveComparisonConfiguration}: + *

      + *
    • {@link RecursiveComparisonConfiguration.Builder#withEqualsForFields(java.util.function.BiPredicate, String...)}
    • + *
    • {@link RecursiveComparisonConfiguration.Builder#withComparatorForFields(Comparator, String...)}
    • + *
    */ + @Deprecated @CheckReturnValue public SELF usingComparatorForElementFieldsWithNames(Comparator comparator, String... elementPropertyOrFieldNames) { @@ -1678,15 +1832,16 @@ public SELF usingComparatorForElementFieldsWithNames(Comparator comparato } /** + * Deprecated javadoc + *

    * Allows to set a specific comparator to compare properties or fields of elements with the given type. * A typical usage is for comparing fields of numeric type at a given precision. *

    * To be used, comparators need to be specified by this method before calling any of: *

      - *
    • {@link #usingFieldByFieldElementComparator}
    • - *
    • {@link #usingElementComparatorOnFields}
    • - *
    • {@link #usingElementComparatorIgnoringFields}
    • - *
    • {@link #usingRecursiveFieldByFieldElementComparator}
    • + *
    • {@link #usingFieldByFieldElementComparator()}
    • + *
    • {@link #usingElementComparatorOnFields(String...)}
    • + *
    • {@link #usingElementComparatorIgnoringFields(String...)}
    • *
    *

    * Comparators specified by {@link #usingComparatorForElementFieldsWithNames(Comparator, String...) usingComparatorForElementFieldsWithNames} @@ -1746,7 +1901,22 @@ public SELF usingComparatorForElementFieldsWithNames(Comparator comparato * @param type the {@link java.lang.Class} of the type of the element fields the comparator should be used for * @return {@code this} assertions object * @since 2.5.0 / 3.5.0 + * @deprecated This method is used with {@link #usingFieldByFieldElementComparator()} which is deprecated in favor of + * {@link #usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration)} or {@link #usingRecursiveComparison()}. + *

    + * When using {@link #usingRecursiveComparison()} the equivalent is: + *

      + *
    • {@link RecursiveComparisonAssert#withEqualsForType(java.util.function.BiPredicate, Class)}
    • + *
    • {@link RecursiveComparisonAssert#withComparatorForType(Comparator, Class)}
    • + *
    + *

    + * and when using {@link RecursiveComparisonConfiguration}: + *

      + *
    • {@link RecursiveComparisonConfiguration.Builder#withEqualsForType(java.util.function.BiPredicate, Class)}
    • + *
    • {@link RecursiveComparisonConfiguration.Builder#withComparatorForType(Comparator, Class)}
    • + *
    */ + @Deprecated @CheckReturnValue public SELF usingComparatorForElementFieldsWithType(Comparator comparator, Class type) { getComparatorsForElementPropertyOrFieldTypes().put(type, comparator); @@ -1760,10 +1930,9 @@ public SELF usingComparatorForElementFieldsWithType(Comparator comparator *

    * Usage of this method affects comparators set by the following methods: *

      - *
    • {@link #usingFieldByFieldElementComparator}
    • - *
    • {@link #usingElementComparatorOnFields}
    • - *
    • {@link #usingElementComparatorIgnoringFields}
    • - *
    • {@link #usingRecursiveFieldByFieldElementComparator}
    • + *
    • {@link #usingFieldByFieldElementComparator()}
    • + *
    • {@link #usingElementComparatorOnFields(String...)}
    • + *
    • {@link #usingElementComparatorIgnoringFields(String...)}
    • *
    *

    * Example: @@ -1792,6 +1961,8 @@ public SELF usingComparatorForType(Comparator comparator, Class type) } /** + * Deprecated javadoc + *

    * Use field/property by field/property comparison (including inherited fields/properties) instead of relying on * actual type A equals method to compare group elements for incoming assertion checks. Private fields * are included but this can be disabled using {@link Assertions#setAllowExtractingPrivateFields(boolean)}. @@ -1816,7 +1987,12 @@ public SELF usingComparatorForType(Comparator comparator, Class type) * assertThat(array(frodo)).usingFieldByFieldElementComparator().contains(frodoClone); * * @return {@code this} assertion object. + * @deprecated This method is deprecated because it performs a shallow field by field comparison, i.e. elements are compared + * field by field but the fields are compared with equals, use {@link #usingRecursiveFieldByFieldElementComparator()} + * or {@link #usingRecursiveComparison()} instead to perform a true recursive comparison. + *
    See https://assertj.github.io/doc/#assertj-core-recursive-comparison */ + @Deprecated @CheckReturnValue public SELF usingFieldByFieldElementComparator() { return usingExtendedByTypesElementComparator(new FieldByFieldComparator(comparatorsForElementPropertyOrFieldNames, @@ -1824,55 +2000,182 @@ public SELF usingFieldByFieldElementComparator() { } /** - * Use a recursive field/property by field/property comparison (including inherited fields/properties) - * instead of relying on actual type A equals method to compare group elements for incoming - * assertion checks. This can be useful if actual's {@code equals} implementation does not suit you. + * Enable using a recursive field by field comparison strategy similar to {@link #usingRecursiveComparison()} but contrary to the latter you can chain any iterable assertions after this method (this is why this method exists). *

    - * The recursive property/field comparison is not applied on fields having a custom {@code equals} - * implementation, i.e. the overridden {@code equals} method will be used instead of a field/property by field/property comparison. + * This method uses the default {@link RecursiveComparisonConfiguration}, if you need to customize it use {@link #usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration)} instead. *

    - * You can specify a custom comparator per (nested) name or type of element field with - * {@link #usingComparatorForElementFieldsWithNames(Comparator, String...) usingComparatorForElementFieldsWithNames} - * and {@link #usingComparatorForElementFieldsWithType(Comparator, Class) usingComparatorForElementFieldsWithType}. + * Breaking change: since 3.20.0 the comparison won't use any comparators set with: + *

      + *
    • {@link #usingComparatorForType(Comparator, Class)}
    • + *
    • {@link #withTypeComparators(TypeComparators)}
    • + *
    • {@link #usingComparatorForElementFieldsWithType(Comparator, Class)}
    • + *
    • {@link #withComparatorsForElementPropertyOrFieldTypes(TypeComparators)}
    • + *
    • {@link #usingComparatorForElementFieldsWithNames(Comparator, String...)}
    • + *
    • {@link #withComparatorsForElementPropertyOrFieldNames(Map)}
    • + *
    *

    - * The recursive comparison handles cycles. + * These features (and many more) are provided through {@link #usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration)} with a customized {@link RecursiveComparisonConfiguration} where there methods are called: + *

      + *
    • {@link RecursiveComparisonConfiguration#registerComparatorForType(Comparator, Class) registerComparatorForType(Comparator, Class)} / {@link RecursiveComparisonConfiguration.Builder#withComparatorForType(Comparator, Class) withComparatorForType(Comparator, Class)} (using {@link RecursiveComparisonConfiguration.Builder})
    • + *
    • {@link RecursiveComparisonConfiguration#registerEqualsForType(java.util.function.BiPredicate, Class) registerEqualsForType(BiPredicate, Class)} / {@link RecursiveComparisonConfiguration.Builder#withComparatorForType(Comparator, Class) withComparatorForType(Comparator, Class)} (using {@link RecursiveComparisonConfiguration.Builder})
    • + *
    • {@link RecursiveComparisonConfiguration#registerComparatorForFields(Comparator, String...) registerComparatorForFields(Comparator comparator, String... fields)} / {@link RecursiveComparisonConfiguration.Builder#withComparatorForFields(Comparator, String...) withComparatorForField(Comparator comparator, String... fields)} (using {@link RecursiveComparisonConfiguration.Builder})
    • + *
    *

    - * The objects to compare can be of different types but must have the same properties/fields. For example if actual object has a - * {@code name} String field, the other object must also have one. + * There are differences between this approach and {@link #usingRecursiveComparison()}: + *

      + *
    • contrary to {@link RecursiveComparisonAssert}, you can chain any iterable assertions after this method.
    • + *
    • no comparators registered with {@link AbstractIterableAssert#usingComparatorForType(Comparator, Class)} will be used, you need to register them in the configuration object.
    • + *
    • the assertion errors won't be as detailed as {@link RecursiveComparisonAssert#isEqualTo(Object)} which shows the field differences.
    • + *
    *

    - * If an object has a field and a property with the same name, the property value will be used over the field. + * This last point makes sense, take the {@link #contains(Object...)} assertion, it would not be relevant to report the differences of all the iterable's elements differing from the values to look for. *

    * Example: + *

     public class Person {
    +   *   String name;
    +   *   boolean hasPhd;
    +   * }
        *
    -   * 
     TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);
    -   * TolkienCharacter pippin = new TolkienCharacter("Pippin", 28, HOBBIT);
    -   * frodo.setFriend(pippin);
    -   * pippin.setFriend(frodo);
    +   * public class Doctor {
    +   *  String name;
    +   *  boolean hasPhd;
    +   * }
        *
    -   * TolkienCharacter frodoClone = new TolkienCharacter("Frodo", 33, HOBBIT);
    -   * TolkienCharacter pippinClone = new TolkienCharacter("Pippin", 28, HOBBIT);
    -   * frodoClone.setFriend(pippinClone);
    -   * pippinClone.setFriend(frodoClone);
    +   * Doctor drSheldon = new Doctor("Sheldon Cooper", true);
    +   * Doctor drLeonard = new Doctor("Leonard Hofstadter", true);
    +   * Doctor drRaj = new Doctor("Raj Koothrappali", true);
    +   *
    +   * Person sheldon = new Person("Sheldon Cooper", true);
    +   * Person leonard = new Person("Leonard Hofstadter", true);
    +   * Person raj = new Person("Raj Koothrappali", true);
    +   * Person howard = new Person("Howard Wolowitz", true);
        *
    -   * TolkienCharacter[] hobbits = new TolkienCharacter[] {frodo, pippin};
    +   * Doctor[] doctors = array(drSheldon, drLeonard, drRaj);
    +   * Person[] people = array(sheldon, leonard, raj);
        *
    -   * // fails if equals has not been overridden in TolkienCharacter as it would compares object references
    -   * assertThat(hobbits).contains(frodoClone, pippinClone);
    +   * // assertion succeeds as both lists contains equivalent items in order.
    +   * assertThat(doctors).usingRecursiveFieldByFieldElementComparator()
    +   *                    .contains(sheldon);
        *
    -   * // frodo/frodoClone and pippin/pippinClone are equals when doing a recursive property/field by property/field comparison
    -   * assertThat(hobbits).usingRecursiveFieldByFieldElementComparator()
    -   *                    .contains(frodoClone, pippinClone);
    + * // assertion fails because leonard names are different. + * leonard.setName("Leonard Ofstater"); + * assertThat(doctors).usingRecursiveFieldByFieldElementComparator() + * .contains(leonard); + * + * // assertion fails because howard is missing and leonard is not expected. + * people = list(howard, sheldon, raj) + * assertThat(doctors).usingRecursiveFieldByFieldElementComparator() + * .contains(howard);
    + *

    + * Another point worth mentioning: elements order does matter if the expected iterable is ordered, for example comparing a {@code Set} to a {@code List} fails as {@code List} is ordered and {@code Set} is not.
    + * The ordering can be ignored by calling {@link RecursiveComparisonAssert#ignoringCollectionOrder ignoringCollectionOrder} allowing ordered/unordered iterable comparison, note that {@link RecursiveComparisonAssert#ignoringCollectionOrder ignoringCollectionOrder} is applied recursively on any nested iterable fields, if this behavior is too generic, + * use the more fine grained {@link RecursiveComparisonAssert#ignoringCollectionOrderInFields(String...) ignoringCollectionOrderInFields} or + * {@link RecursiveComparisonAssert#ignoringCollectionOrderInFieldsMatchingRegexes(String...) ignoringCollectionOrderInFieldsMatchingRegexes}. * * @return {@code this} assertion object. - * @since 2.5.0 / 3.5.0 + * @since 2.5.0 / 3.5.0 - breaking change in 3.20.0 + * @see RecursiveComparisonConfiguration + * @see usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration) */ @CheckReturnValue public SELF usingRecursiveFieldByFieldElementComparator() { - return usingExtendedByTypesElementComparator(new RecursiveFieldByFieldComparator(comparatorsForElementPropertyOrFieldNames, - getComparatorsForElementPropertyOrFieldTypes())); + return usingRecursiveFieldByFieldElementComparator(new RecursiveComparisonConfiguration()); } /** + * Enable using a recursive field by field comparison strategy similar to {@link #usingRecursiveComparison()} but contrary to the latter you can chain any iterable assertions after this method (this is why this method exists). + *

    + * The given {@link RecursiveComparisonConfiguration} is used to tweak the comparison behavior, for example by {@link RecursiveComparisonConfiguration#ignoreCollectionOrder(boolean) ignoring collection order}. + *

    + * Warning: the comparison won't use any comparators set with: + *

      + *
    • {@link #usingComparatorForType(Comparator, Class)}
    • + *
    • {@link #withTypeComparators(TypeComparators)}
    • + *
    • {@link #usingComparatorForElementFieldsWithType(Comparator, Class)}
    • + *
    • {@link #withComparatorsForElementPropertyOrFieldTypes(TypeComparators)}
    • + *
    • {@link #usingComparatorForElementFieldsWithNames(Comparator, String...)}
    • + *
    • {@link #withComparatorsForElementPropertyOrFieldNames(Map)}
    • + *
    + *

    + * These features (and many more) are provided through {@link RecursiveComparisonConfiguration} with: + *

      + *
    • {@link RecursiveComparisonConfiguration#registerComparatorForType(Comparator, Class) registerComparatorForType(Comparator, Class)} / {@link RecursiveComparisonConfiguration.Builder#withComparatorForType(Comparator, Class) withComparatorForType(Comparator, Class)} (using {@link RecursiveComparisonConfiguration.Builder})
    • + *
    • {@link RecursiveComparisonConfiguration#registerEqualsForType(java.util.function.BiPredicate, Class) registerEqualsForType(BiPredicate, Class)} / {@link RecursiveComparisonConfiguration.Builder#withComparatorForType(Comparator, Class) withComparatorForType(Comparator, Class)} (using {@link RecursiveComparisonConfiguration.Builder})
    • + *
    • {@link RecursiveComparisonConfiguration#registerComparatorForFields(Comparator, String...) registerComparatorForFields(Comparator comparator, String... fields)} / {@link RecursiveComparisonConfiguration.Builder#withComparatorForFields(Comparator, String...) withComparatorForField(Comparator comparator, String... fields)} (using {@link RecursiveComparisonConfiguration.Builder})
    • + *
    + *

    + * RecursiveComparisonConfiguration exposes a {@link RecursiveComparisonConfiguration.Builder builder} to ease setting the comparison behaviour, + * call {@link RecursiveComparisonConfiguration#builder() RecursiveComparisonConfiguration.builder()} to start building your configuration. + *

    + * There are differences between this approach and {@link #usingRecursiveComparison()}: + *

      + *
    • contrary to {@link RecursiveComparisonAssert}, you can chain any iterable assertions after this method.
    • + *
    • no comparators registered with {@link AbstractIterableAssert#usingComparatorForType(Comparator, Class)} will be used, you need to register them in the configuration object.
    • + *
    • the assertion errors won't be as detailed as {@link RecursiveComparisonAssert#isEqualTo(Object)} which shows the field differences.
    • + *
    + *

    + * This last point makes sense, take the {@link #contains(Object...)} assertion, it would not be relevant to report the differences of all the iterable's elements differing from the values to look for. + *

    + * Example: + *

     public class Person {
    +   *   String name;
    +   *   boolean hasPhd;
    +   * }
    +   *
    +   * public class Doctor {
    +   *  String name;
    +   *  boolean hasPhd;
    +   * }
    +   *
    +   * Doctor drSheldon = new Doctor("Sheldon Cooper", true);
    +   * Doctor drLeonard = new Doctor("Leonard Hofstadter", true);
    +   * Doctor drRaj = new Doctor("Raj Koothrappali", true);
    +   *
    +   * Person sheldon = new Person("Sheldon Cooper", false);
    +   * Person leonard = new Person("Leonard Hofstadter", false);
    +   * Person raj = new Person("Raj Koothrappali", false);
    +   * Person howard = new Person("Howard Wolowitz", false);
    +   *
    +   * Doctor[] doctors = array(drSheldon, drLeonard, drRaj);
    +   * Person[] people = array(sheldon, leonard, raj);
    +   *
    +   * RecursiveComparisonConfiguration configuration = RecursiveComparisonConfiguration.builder()
    +   *                                                                                  .withIgnoredFields​("hasPhd");
    +   *
    +   * // assertion succeeds as both lists contains equivalent items in order.
    +   * assertThat(doctors).usingRecursiveFieldByFieldElementComparator(configuration)
    +   *                    .contains(sheldon);
    +   *
    +   * // assertion fails because leonard names are different.
    +   * leonard.setName("Leonard Ofstater");
    +   * assertThat(doctors).usingRecursiveFieldByFieldElementComparator(configuration)
    +   *                    .contains(leonard);
    +   *
    +   * // assertion fails because howard is missing and leonard is not expected.
    +   * people = list(howard, sheldon, raj)
    +   * assertThat(doctors).usingRecursiveFieldByFieldElementComparator(configuration)
    +   *                    .contains(howard);
    + * + * A detailed documentation for the recursive comparison is available here: https://assertj.github.io/doc/#assertj-core-recursive-comparison. + *

    + * A point worth mentioning: elements order does matter if the expected iterable is ordered, for example comparing a {@code Set} to a {@code List} fails as {@code List} is ordered and {@code Set} is not.
    + * The ordering can be ignored by calling {@link RecursiveComparisonAssert#ignoringCollectionOrder ignoringCollectionOrder} allowing ordered/unordered iterable comparison, note that {@link RecursiveComparisonAssert#ignoringCollectionOrder ignoringCollectionOrder} is applied recursively on any nested iterable fields, if this behavior is too generic, + * use the more fine grained {@link RecursiveComparisonAssert#ignoringCollectionOrderInFields(String...) ignoringCollectionOrderInFields} or + * {@link RecursiveComparisonAssert#ignoringCollectionOrderInFieldsMatchingRegexes(String...) ignoringCollectionOrderInFieldsMatchingRegexes}. + * + * @param configuration the recursive comparison configuration. + * + * @return {@code this} assertion object. + * @since 3.20.0 + * @see RecursiveComparisonConfiguration + */ + public SELF usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration configuration) { + return usingElementComparator(new ConfigurableRecursiveFieldByFieldComparator(configuration)); + } + + /** + * Deprecated javadoc + *

    * Use field/property by field/property comparison on the given fields/properties only (including inherited * fields/properties) instead of relying on actual type A equals method to compare group elements for * incoming assertion checks. Private fields are included but this can be disabled using @@ -1899,7 +2202,13 @@ public SELF usingRecursiveFieldByFieldElementComparator() { * * @param fields the name of the fields to use the element comparator on * @return {@code this} assertion object. + * @see #usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration) + * @see https://assertj.github.io/doc/#assertj-core-recursive-comparison + * @deprecated This method is deprecated because it performs a shallow field by field comparison, i.e. elements are + * compared field by field but the fields are compared with equals, use {@link #usingRecursiveFieldByFieldElementComparatorOnFields(String...)} instead. + *
    See https://assertj.github.io/doc/#assertj-core-recursive-comparison */ + @Deprecated @CheckReturnValue public SELF usingElementComparatorOnFields(String... fields) { return usingExtendedByTypesElementComparator(new OnFieldsComparator(comparatorsForElementPropertyOrFieldNames, @@ -1908,6 +2217,57 @@ public SELF usingElementComparatorOnFields(String... fields) { } /** + * The assertions chained after this method will use a recursive field by field comparison on the given fields (including + * inherited fields) instead of relying on the element equals method. + * This is handy when the element equals method is not overridden or implemented as you expect. + *

    + * Nested fields are supported and are expressed like: {@code name.first} + *

    + * The comparison is recursive: elements are compared field by field, if a field type has fields they are also compared + * field by field (and so on). + *

    + * Example: + *

     Player derrickRose = new Player(new Name("Derrick", "Rose"), "Chicago Bulls");
    +   * derrickRose.nickname = new Name("Crazy", "Dunks");
    +   *
    +   * Player jalenRose = new Player(new Name("Jalen", "Rose"), "Chicago Bulls");
    +   * jalenRose.nickname = new Name("Crazy", "Defense");
    +   *
    +   * // assertion succeeds as all compared fields match
    +   * assertThat(array(derrickRose)).usingRecursiveFieldByFieldElementComparatorOnFields("name.last", "team", "nickname.first")
    +   *                               .contains(jalenRose);
    +   *
    +   * // assertion fails, name.first values differ
    +   * assertThat(array(derrickRose)).usingRecursiveFieldByFieldElementComparatorOnFields("name")
    +   *                               .contains(jalenRose);
    + *

    + * This method is actually a shortcut of {@link #usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration)} + * with a configuration comparing only the given fields, the previous example can be written as: + *

     RecursiveComparisonConfiguration configuration = RecursiveComparisonConfiguration.builder()
    +   *                                                                                  .withComparedFields("name.last", "team", "nickname.first")
    +   *                                                                                  .build();
    +   *
    +   * assertThat(array(derrickRose)).usingRecursiveFieldByFieldElementComparator(configuration)
    +   *                               .contains(jalenRose);
    + * The recursive comparison is documented here: https://assertj.github.io/doc/#assertj-core-recursive-comparison + *

    + * @param fields the field names to exclude in the elements comparison. + * @return {@code this} assertion object. + * @since 3.20.0 + * @see #usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration) + * @see https://assertj.github.io/doc/#assertj-core-recursive-comparison + */ + @CheckReturnValue + public SELF usingRecursiveFieldByFieldElementComparatorOnFields(String... fields) { + RecursiveComparisonConfiguration recursiveComparisonConfiguration = RecursiveComparisonConfiguration.builder() + .withComparedFields(fields) + .build(); + return usingRecursiveFieldByFieldElementComparator(recursiveComparisonConfiguration); + } + + /** + * Deprecated javadoc + *

    * Use field/property by field/property on all fields/properties except the given ones (including inherited * fields/properties) instead of relying on actual type A equals method to compare group elements for * incoming assertion checks. Private fields are included but this can be disabled using @@ -1934,7 +2294,13 @@ public SELF usingElementComparatorOnFields(String... fields) { * * @param fields the name of the fields to ignore * @return {@code this} assertion object. + * @see #usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration) + * @see https://assertj.github.io/doc/#assertj-core-recursive-comparison + * @deprecated This method is deprecated because it performs a shallow field by field comparison, i.e. elements are + * compared field by field but the fields are compared with equals, use {@link #usingRecursiveFieldByFieldElementComparatorIgnoringFields(String...)} instead. + *
    See https://assertj.github.io/doc/#assertj-core-recursive-comparison */ + @Deprecated @CheckReturnValue public SELF usingElementComparatorIgnoringFields(String... fields) { return usingExtendedByTypesElementComparator(new IgnoringFieldsComparator(comparatorsForElementPropertyOrFieldNames, @@ -1942,6 +2308,55 @@ public SELF usingElementComparatorIgnoringFields(String... fields) { fields)); } + /** + * The assertions chained after this method will use a recursive field by field comparison on all fields (including inherited + * fields) except the given ones instead of relying on the element equals method. + * This is handy when the element equals method is not overridden or implemented as you expect. + *

    + * Nested fields are supported and are expressed like: {@code name.first} + *

    + * The comparison is recursive: elements are compared field by field, if a field type has fields they are also compared + * field by field (and so on). + *

    + * Example: + *

     Player derrickRose = new Player(new Name("Derrick", "Rose"), "Chicago Bulls");
    +   * derrickRose.nickname = new Name("Crazy", "Dunks");
    +   *
    +   * Player jalenRose = new Player(new Name("Jalen", "Rose"), "Chicago Bulls");
    +   * jalenRose.nickname = new Name("Crazy", "Defense");
    +   *
    +   * // assertion succeeds
    +   * assertThat(array(derrickRose)).usingRecursiveFieldByFieldElementComparatorIgnoringFields("name.first", "nickname.last")
    +   *                               .contains(jalenRose);
    +   *
    +   * // assertion fails, names are ignored but nicknames are not and nickname.last values differ
    +   * assertThat(array(derrickRose)).usingRecursiveFieldByFieldElementComparatorIgnoringFields("name")
    +   *                               .contains(jalenRose);
    + *

    + * This method is actually a shortcut of {@link #usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration)} + * with a configuration ignoring the given fields, the previous example can be written as: + *

     RecursiveComparisonConfiguration configuration = RecursiveComparisonConfiguration.builder()
    +   *                                                                                  .withIgnoredFields("name.first", "nickname.last")
    +   *                                                                                  .build();
    +   *
    +   * assertThat(array(derrickRose)).usingRecursiveFieldByFieldElementComparator(configuration)
    +   *                               .contains(jalenRose);
    + * The recursive comparison is documented here: https://assertj.github.io/doc/#assertj-core-recursive-comparison + *

    + * @param fields the field names to exclude in the elements comparison. + * @return {@code this} assertion object. + * @since 3.20.0 + * @see #usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration) + * @see https://assertj.github.io/doc/#assertj-core-recursive-comparison + */ + @CheckReturnValue + public SELF usingRecursiveFieldByFieldElementComparatorIgnoringFields(String... fields) { + RecursiveComparisonConfiguration recursiveComparisonConfiguration = RecursiveComparisonConfiguration.builder() + .withIgnoredFields(fields) + .build(); + return usingRecursiveFieldByFieldElementComparator(recursiveComparisonConfiguration); + } + /** * Extract the values of given field or property from the array's elements under test into a new list, this new list * becoming the object under test. @@ -2234,7 +2649,15 @@ public AbstractListAssert, * @return a new assertion object whose object under test is the list of Tuples containing the extracted values. */ @CheckReturnValue - public AbstractListAssert, Tuple, ObjectAssert> extracting(@SuppressWarnings("unchecked") Function... extractors) { + @SafeVarargs + public final AbstractListAssert, Tuple, ObjectAssert> extracting(Function... extractors) { + return extractingForProxy(extractors); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected AbstractListAssert, Tuple, ObjectAssert> extractingForProxy(Function[] extractors) { Function tupleExtractor = objectToExtractValueFrom -> new Tuple(Stream.of(extractors) .map(extractor -> extractor.apply(objectToExtractValueFrom)) @@ -2937,13 +3360,29 @@ public SELF noneSatisfy(Consumer restrictions) { } @Override - public SELF satisfiesExactly(@SuppressWarnings("unchecked") Consumer... requirements) { + @SafeVarargs + public final SELF satisfiesExactly(Consumer... requirements) { + return satisfiesExactlyForProxy(requirements); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF satisfiesExactlyForProxy(Consumer[] requirements) { iterables.assertSatisfiesExactly(info, newArrayList(actual), requirements); return myself; } @Override - public SELF satisfiesExactlyInAnyOrder(@SuppressWarnings("unchecked") Consumer... consumers) { + @SafeVarargs + public final SELF satisfiesExactlyInAnyOrder(Consumer... consumers) { + return satisfiesExactlyInAnyOrderForProxy(consumers); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF satisfiesExactlyInAnyOrderForProxy(Consumer[] consumers) { iterables.assertSatisfiesExactlyInAnyOrder(info, newArrayList(actual), consumers); return myself; } @@ -2974,7 +3413,15 @@ public SELF satisfiesExactlyInAnyOrder(@SuppressWarnings("unchecked") Consumer predicate) { /** * Create a friendly soft or "hard" assertion. *

    - * Implementations need to redefine it so that some methods, such as {@link #extracting(Function)}, are able - * to build the appropriate list assert (eg: {@link ListAssert} versus {@link ProxyableListAssert}). + * Implementations need to redefine either to be proxy friendly (i.e. no final assertion methods) + * or generic vararg friendly (to use {@link SafeVarargs} annotation which requires final method). *

    * The default implementation will assume that this concrete implementation is NOT a soft assertion. * @@ -3127,6 +3574,7 @@ public RecursiveComparisonAssert usingRecursiveComparison() { * @return a new {@link RecursiveComparisonAssert} instance built with the given {@link RecursiveComparisonConfiguration}. */ @Override + @Beta public RecursiveComparisonAssert usingRecursiveComparison(RecursiveComparisonConfiguration recursiveComparisonConfiguration) { return super.usingRecursiveComparison(recursiveComparisonConfiguration).withTypeComparators(comparatorsByType); } diff --git a/src/main/java/org/assertj/core/api/AbstractObjectAssert.java b/src/main/java/org/assertj/core/api/AbstractObjectAssert.java index 9a360b1822b..7f325deec3f 100644 --- a/src/main/java/org/assertj/core/api/AbstractObjectAssert.java +++ b/src/main/java/org/assertj/core/api/AbstractObjectAssert.java @@ -49,6 +49,8 @@ * @author Joel Costigliola * @author Libor Ondrusek */ +// suppression of deprecation works in Eclipse to hide warning for the deprecated classes in the imports +@SuppressWarnings("deprecation") public abstract class AbstractObjectAssert, ACTUAL> extends AbstractAssert { @@ -900,10 +902,17 @@ public AbstractListAssert, Object, ObjectAssert> extracting(S * @param extractors the extractor functions to extract values from the Object under test. * @return a new assertion object whose object under test is the list containing the extracted values */ - @SuppressWarnings("unchecked") @CheckReturnValue - public AbstractListAssert, Object, ObjectAssert> extracting(Function... extractors) { - requireNonNull(extractors, shouldNotBeNull("extractors").create()); + @SafeVarargs + public final AbstractListAssert, Object, ObjectAssert> extracting(Function... extractors) { + return extractingForProxy(extractors); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected AbstractListAssert, Object, ObjectAssert> extractingForProxy(Function[] extractors) { + requireNonNull(extractors, shouldNotBeNull("extractors")::create); List values = Stream.of(extractors) .map(extractor -> extractor.apply(actual)) .collect(toList()); diff --git a/src/main/java/org/assertj/core/api/AbstractOptionalAssert.java b/src/main/java/org/assertj/core/api/AbstractOptionalAssert.java index 9cf77119689..2a78975a396 100644 --- a/src/main/java/org/assertj/core/api/AbstractOptionalAssert.java +++ b/src/main/java/org/assertj/core/api/AbstractOptionalAssert.java @@ -44,6 +44,7 @@ * @author Nicolai Parlog * @author Grzegorz Piwowarek */ +@SuppressWarnings("deprecation") public abstract class AbstractOptionalAssert, VALUE> extends AbstractAssert> { @@ -245,8 +246,7 @@ public SELF containsInstanceOf(Class clazz) { /** * Use field/property by field/property comparison (including inherited fields/properties) instead of relying on * actual type A equals method to compare the {@link Optional} value's object for incoming assertion - * checks. Private fields are included but this can be disabled using - * {@link Assertions#setAllowExtractingPrivateFields(boolean)}. + * checks. Private fields are included but this can be disabled using {@link Assertions#setAllowExtractingPrivateFields(boolean)}. *

    * This can be handy if equals method of the {@link Optional} value's object to compare does not suit * you. @@ -266,7 +266,17 @@ public SELF containsInstanceOf(Class clazz) { * assertThat(Optional.of(frodo)).usingFieldByFieldValueComparator().contains(frodoClone); * * @return {@code this} assertion object. + * @deprecated This method is deprecated because it performs a shallow field by field comparison, i.e. elements are compared + * field by field but the fields are compared with equals, use {@link #get()} chained with {@link AbstractObjectAssert#usingRecursiveComparison()} instead. + *

     TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);
    +   * TolkienCharacter frodoClone = new TolkienCharacter("Frodo", 33, HOBBIT);
    +   *
    +   * // frodo and frodoClone are equals when doing a field by field comparison.
    +   * assertThat(Optional.of(frodo)).get().usingRecursiveComparison()
    +   *                               .isEqualTo(frodoClone);
    + *
    See https://assertj.github.io/doc/#assertj-core-recursive-comparison */ + @Deprecated @CheckReturnValue public SELF usingFieldByFieldValueComparator() { return usingValueComparator(new FieldByFieldComparator()); diff --git a/src/main/java/org/assertj/core/api/AbstractPathAssert.java b/src/main/java/org/assertj/core/api/AbstractPathAssert.java index 1445063358e..68fca97f816 100644 --- a/src/main/java/org/assertj/core/api/AbstractPathAssert.java +++ b/src/main/java/org/assertj/core/api/AbstractPathAssert.java @@ -1761,14 +1761,14 @@ public SELF isNotEmptyDirectory() { * /root/sub-dir-1/file-2.ext (content) * * Here are some assertions examples: - *
     Path noContentPath = Paths.get("/root/sub-dir-1/file-1.ext");
    -   * Path contentPath = Paths.get("/root/sub-dir-1/file-2.ext");
    +   * 
     Path withoutContent = Paths.get("/root/sub-dir-1/file-1.ext");
    +   * Path withContent = Paths.get("/root/sub-dir-1/file-2.ext");
        *
        * // The following assertion succeeds:
    -   * assertThat(noContentPath).isEmptyFile();
    +   * assertThat(withoutContent).isEmptyFile();
        *
        * // The following assertion fails:
    -   * assertThat(contentPath).isEmptyFile();
    + * assertThat(withContent).isEmptyFile();
    * * @return {@code this} assertion object. * @throws AssertionError if actual is {@code null}. @@ -1792,14 +1792,14 @@ public SELF isEmptyFile() { * /root/sub-dir-1/file-2.ext (content) * * Here are some assertions examples: - *
     Path noContentPath = Paths.get("/root/sub-dir-1/file-1.ext");
    -   * Path contentPath = Paths.get("/root/sub-dir-1/file-2.ext");
    +   * 
     Path withoutContent = Paths.get("/root/sub-dir-1/file-1.ext");
    +   * Path withContent = Paths.get("/root/sub-dir-1/file-2.ext");
        *
        * // The following assertion succeeds:
    -   * assertThat(contentPath).isNotEmptyFile();
    +   * assertThat(withContent).isNotEmptyFile();
        *
        * // The following assertion fails:
    -   * assertThat(noContentPath).isNotEmptyFile();
    + * assertThat(withoutContent).isNotEmptyFile();
    * * @return {@code this} assertion object. * @throws AssertionError if actual is {@code null}. diff --git a/src/main/java/org/assertj/core/api/AbstractPredicateAssert.java b/src/main/java/org/assertj/core/api/AbstractPredicateAssert.java index bb447968172..80d8879618a 100644 --- a/src/main/java/org/assertj/core/api/AbstractPredicateAssert.java +++ b/src/main/java/org/assertj/core/api/AbstractPredicateAssert.java @@ -57,7 +57,15 @@ protected AbstractPredicateAssert(Predicate actual, Class selfType) { * @return this assertion object. * @throws AssertionError if the actual {@code Predicate} does not accept all the given {@code Iterable}'s elements. */ - public SELF accepts(@SuppressWarnings("unchecked") T... values) { + @SafeVarargs + public final SELF accepts(T... values) { + return acceptsForProxy(values); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF acceptsForProxy(T[] values) { isNotNull(); if (values.length == 1) { if (!actual.test(values[0])) throwAssertionError(shouldAccept(actual, values[0], PredicateDescription.GIVEN)); @@ -83,7 +91,15 @@ public SELF accepts(@SuppressWarnings("unchecked") T... values) { * @return this assertion object. * @throws AssertionError if the actual {@code Predicate} accepts one of the given {@code Iterable}'s elements. */ - public SELF rejects(@SuppressWarnings("unchecked") T... values) { + @SafeVarargs + public final SELF rejects(T... values) { + return rejectsForProxy(values); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected SELF rejectsForProxy(T[] values) { isNotNull(); if (values.length == 1) { if (actual.test(values[0])) throwAssertionError(shouldNotAccept(actual, values[0], PredicateDescription.GIVEN)); diff --git a/src/main/java/org/assertj/core/api/AbstractSoftAssertions.java b/src/main/java/org/assertj/core/api/AbstractSoftAssertions.java index 9b1e2431a7f..15fbca25803 100644 --- a/src/main/java/org/assertj/core/api/AbstractSoftAssertions.java +++ b/src/main/java/org/assertj/core/api/AbstractSoftAssertions.java @@ -13,13 +13,12 @@ package org.assertj.core.api; import static java.lang.String.format; -import static java.util.stream.Collectors.toList; -import java.lang.reflect.Constructor; import java.util.List; import org.assertj.core.error.AssertionErrorCreator; import org.assertj.core.internal.Failures; +import org.assertj.core.util.CanIgnoreReturnValue; public abstract class AbstractSoftAssertions extends DefaultAssertionErrorCollector implements SoftAssertionsProvider, InstanceOfAssertFactories { @@ -57,6 +56,7 @@ public void assertAll() { * @return nothing, it's just to be used in {@code doSomething(optional.orElse(() -> fail("boom")));}. * @since 2.6.0 / 3.6.0 */ + @CanIgnoreReturnValue public T fail(String failureMessage) { AssertionError error = Failures.instance().failure(failureMessage); collectAssertionError(error); @@ -72,6 +72,7 @@ public T fail(String failureMessage) { * @return nothing, it's just to be used in {@code doSomething(optional.orElse(() -> fail("boom")));}. * @since 2.6.0 / 3.6.0 */ + @CanIgnoreReturnValue public T fail(String failureMessage, Object... args) { return fail(format(failureMessage, args)); } @@ -85,6 +86,7 @@ public T fail(String failureMessage, Object... args) { * @return nothing, it's just to be used in {@code doSomething(optional.orElse(() -> fail("boom")));}. * @since 2.6.0 / 3.6.0 */ + @CanIgnoreReturnValue public T fail(String failureMessage, Throwable realCause) { AssertionError error = Failures.instance().failure(failureMessage); error.initCause(realCause); @@ -121,11 +123,6 @@ public void shouldHaveThrown(Class throwableClass) { collectAssertionError(error); } - @Override - public List assertionErrorsCollected() { - return decorateErrorsCollected(super.assertionErrorsCollected()); - } - /** * Returns a copy of list of soft assertions collected errors. * @return a copy of list of soft assertions collected errors. @@ -134,84 +131,4 @@ public List errorsCollected() { return decorateErrorsCollected(super.assertionErrorsCollected()); } - /** - * Modifies collected errors. Override to customize modification. - * @param the supertype to use in the list return value - * @param errors list of errors to decorate - * @return decorated list - */ - protected List decorateErrorsCollected(List errors) { - return addLineNumberToErrorMessages(errors); - } - - private List addLineNumberToErrorMessages(List errors) { - return errors.stream() - .map(this::addLineNumberToErrorMessage) - .collect(toList()); - } - - private T addLineNumberToErrorMessage(T error) { - StackTraceElement testStackTraceElement = getFirstStackTraceElementFromTest(error.getStackTrace()); - if (testStackTraceElement != null) { - try { - return createNewInstanceWithLineNumberInErrorMessage(error, testStackTraceElement); - } catch (@SuppressWarnings("unused") SecurityException | ReflectiveOperationException ignored) {} - } - return error; - } - - private T createNewInstanceWithLineNumberInErrorMessage(T error, - StackTraceElement testStackTraceElement) throws ReflectiveOperationException { - @SuppressWarnings("unchecked") - Constructor constructor = (Constructor) error.getClass().getConstructor(String.class, - Throwable.class); - T errorWithLineNumber = constructor.newInstance(buildErrorMessageWithLineNumber(error.getMessage(), - testStackTraceElement), - error.getCause()); - errorWithLineNumber.setStackTrace(error.getStackTrace()); - for (Throwable suppressed : error.getSuppressed()) { - errorWithLineNumber.addSuppressed(suppressed); - } - return errorWithLineNumber; - } - - private String buildErrorMessageWithLineNumber(String originalErrorMessage, StackTraceElement testStackTraceElement) { - String testClassName = simpleClassNameOf(testStackTraceElement); - String testName = testStackTraceElement.getMethodName(); - int lineNumber = testStackTraceElement.getLineNumber(); - return format("%s%nat %s.%s(%s.java:%s)", originalErrorMessage, testClassName, testName, testClassName, lineNumber); - } - - private String simpleClassNameOf(StackTraceElement testStackTraceElement) { - String className = testStackTraceElement.getClassName(); - return className.substring(className.lastIndexOf('.') + 1); - } - - private StackTraceElement getFirstStackTraceElementFromTest(StackTraceElement[] stacktrace) { - for (StackTraceElement element : stacktrace) { - String className = element.getClassName(); - if (isProxiedAssertionClass(className) - || className.startsWith("sun.reflect") - || className.startsWith("jdk.internal.reflect") - || className.startsWith("java.") - || className.startsWith("javax.") - || className.startsWith("org.junit.") - || className.startsWith("org.eclipse.jdt.internal.junit.") - || className.startsWith("org.eclipse.jdt.internal.junit4.") - || className.startsWith("org.eclipse.jdt.internal.junit5.") - || className.startsWith("com.intellij.junit5.") - || className.startsWith("com.intellij.rt.execution.junit.") - || className.startsWith("com.intellij.rt.junit.") // since IntelliJ IDEA build 193.2956.37 - || className.startsWith("org.apache.maven.surefire") - || className.startsWith("org.assertj")) { - continue; - } - return element; - } - return null; - } - - private boolean isProxiedAssertionClass(String className) { - return className.contains("$ByteBuddy$"); - } } diff --git a/src/main/java/org/assertj/core/api/Assert.java b/src/main/java/org/assertj/core/api/Assert.java index 41baafa25bb..ddcb7896884 100644 --- a/src/main/java/org/assertj/core/api/Assert.java +++ b/src/main/java/org/assertj/core/api/Assert.java @@ -750,7 +750,7 @@ public interface Assert, ACTUAL> extends Descr * // assertions fail * assertThat(42L).hasSameHashCodeAs(2501L); * assertThat(null).hasSameHashCodeAs("The Force"); - * assertThat("The Force").hasSameHashCodeAs(null); + * assertThat("The Force").hasSameHashCodeAs("Awakens"); * * @param other the object to check hashCode against. * @@ -770,7 +770,7 @@ public interface Assert, ACTUAL> extends Descr * Example: *
     // assertions succeed
        * assertThat(42L).doesNotHaveSameHashCodeAs(2501L);
    -   * assertThat("The Force").doesNotHaveSameHashCodeAs(null);
    +   * assertThat("The Force").doesNotHaveSameHashCodeAs("Awakens");
        *
        * // assertions fail
        * assertThat(42L).doesNotHaveSameHashCodeAs(42L);
    diff --git a/src/main/java/org/assertj/core/api/Assertions.java b/src/main/java/org/assertj/core/api/Assertions.java
    index 6a9417dc212..545b2468d41 100644
    --- a/src/main/java/org/assertj/core/api/Assertions.java
    +++ b/src/main/java/org/assertj/core/api/Assertions.java
    @@ -282,7 +282,7 @@ public static OptionalLongAssert assertThat(OptionalLong actual) {
        * @param actual the actual value.
        * @return the created assertion object.
        */
    -  public static AbstractBigDecimalAssert assertThat(BigDecimal actual) {
    +  public static BigDecimalAssert assertThat(BigDecimal actual) {
         return AssertionsForClassTypes.assertThat(actual);
       }
     
    @@ -293,7 +293,7 @@ public static AbstractBigDecimalAssert assertThat(BigDecimal actual) {
        * @return the created assertion object.
        * @since 2.7.0 / 3.7.0
        */
    -  public static AbstractBigIntegerAssert assertThat(BigInteger actual) {
    +  public static BigIntegerAssert assertThat(BigInteger actual) {
         return new BigIntegerAssert(actual);
       }
     
    @@ -303,7 +303,7 @@ public static AbstractBigIntegerAssert assertThat(BigInteger actual) {
        * @param actual the actual value.
        * @return the created assertion object.
        */
    -  public static AbstractUriAssert assertThat(URI actual) {
    +  public static UriAssert assertThat(URI actual) {
         return AssertionsForClassTypes.assertThat(actual);
       }
     
    @@ -313,7 +313,7 @@ public static AbstractUriAssert assertThat(URI actual) {
        * @param actual the actual value.
        * @return the created assertion object.
        */
    -  public static AbstractUrlAssert assertThat(URL actual) {
    +  public static UrlAssert assertThat(URL actual) {
         return AssertionsForClassTypes.assertThat(actual);
       }
     
    @@ -323,7 +323,7 @@ public static AbstractUrlAssert assertThat(URL actual) {
        * @param actual the actual value.
        * @return the created assertion object.
        */
    -  public static AbstractBooleanAssert assertThat(boolean actual) {
    +  public static BooleanAssert assertThat(boolean actual) {
         return AssertionsForClassTypes.assertThat(actual);
       }
     
    @@ -333,7 +333,7 @@ public static AbstractBooleanAssert assertThat(boolean actual) {
        * @param actual the actual value.
        * @return the created assertion object.
        */
    -  public static AbstractBooleanAssert assertThat(Boolean actual) {
    +  public static BooleanAssert assertThat(Boolean actual) {
         return AssertionsForClassTypes.assertThat(actual);
       }
     
    @@ -343,7 +343,7 @@ public static AbstractBooleanAssert assertThat(Boolean actual) {
        * @param actual the actual value.
        * @return the created assertion object.
        */
    -  public static AbstractBooleanArrayAssert assertThat(boolean[] actual) {
    +  public static BooleanArrayAssert assertThat(boolean[] actual) {
         return AssertionsForClassTypes.assertThat(actual);
       }
     
    @@ -364,7 +364,7 @@ public static Boolean2DArrayAssert assertThat(boolean[][] actual) {
        * @param actual the actual value.
        * @return the created assertion object.
        */
    -  public static AbstractByteAssert assertThat(byte actual) {
    +  public static ByteAssert assertThat(byte actual) {
         return AssertionsForClassTypes.assertThat(actual);
       }
     
    @@ -374,7 +374,7 @@ public static AbstractByteAssert assertThat(byte actual) {
        * @param actual the actual value.
        * @return the created assertion object.
        */
    -  public static AbstractByteAssert assertThat(Byte actual) {
    +  public static ByteAssert assertThat(Byte actual) {
         return AssertionsForClassTypes.assertThat(actual);
       }
     
    @@ -384,7 +384,7 @@ public static AbstractByteAssert assertThat(Byte actual) {
        * @param actual the actual value.
        * @return the created assertion object.
        */
    -  public static AbstractByteArrayAssert assertThat(byte[] actual) {
    +  public static ByteArrayAssert assertThat(byte[] actual) {
         return AssertionsForClassTypes.assertThat(actual);
       }
     
    @@ -405,7 +405,7 @@ public static Byte2DArrayAssert assertThat(byte[][] actual) {
        * @param actual the actual value.
        * @return the created assertion object.
        */
    -  public static AbstractCharacterAssert assertThat(char actual) {
    +  public static CharacterAssert assertThat(char actual) {
         return AssertionsForClassTypes.assertThat(actual);
       }
     
    @@ -415,7 +415,7 @@ public static AbstractCharacterAssert assertThat(char actual) {
        * @param actual the actual value.
        * @return the created assertion object.
        */
    -  public static AbstractCharArrayAssert assertThat(char[] actual) {
    +  public static CharArrayAssert assertThat(char[] actual) {
         return AssertionsForClassTypes.assertThat(actual);
       }
     
    @@ -436,7 +436,7 @@ public static Char2DArrayAssert assertThat(char[][] actual) {
        * @param actual the actual value.
        * @return the created assertion object.
        */
    -  public static AbstractCharacterAssert assertThat(Character actual) {
    +  public static CharacterAssert assertThat(Character actual) {
         return AssertionsForClassTypes.assertThat(actual);
       }
     
    @@ -456,7 +456,7 @@ public static ClassAssert assertThat(Class actual) {
        * @param actual the actual value.
        * @return the created assertion object.
        */
    -  public static AbstractDoubleAssert assertThat(double actual) {
    +  public static DoubleAssert assertThat(double actual) {
         return AssertionsForClassTypes.assertThat(actual);
       }
     
    @@ -466,7 +466,7 @@ public static AbstractDoubleAssert assertThat(double actual) {
        * @param actual the actual value.
        * @return the created assertion object.
        */
    -  public static AbstractDoubleAssert assertThat(Double actual) {
    +  public static DoubleAssert assertThat(Double actual) {
         return AssertionsForClassTypes.assertThat(actual);
       }
     
    @@ -476,7 +476,7 @@ public static AbstractDoubleAssert assertThat(Double actual) {
        * @param actual the actual value.
        * @return the created assertion object.
        */
    -  public static AbstractDoubleArrayAssert assertThat(double[] actual) {
    +  public static DoubleArrayAssert assertThat(double[] actual) {
         return AssertionsForClassTypes.assertThat(actual);
       }
     
    @@ -497,7 +497,7 @@ public static Double2DArrayAssert assertThat(double[][] actual) {
        * @param actual the actual value.
        * @return the created assertion object.
        */
    -  public static AbstractFileAssert assertThat(File actual) {
    +  public static FileAssert assertThat(File actual) {
         return AssertionsForClassTypes.assertThat(actual);
       }
     
    @@ -520,7 +520,7 @@ public static  FutureAssert assertThat(Future actual) {
        * @param actual the actual value.
        * @return the created assertion object.
        */
    -  public static AbstractInputStreamAssert assertThat(InputStream actual) {
    +  public static InputStreamAssert assertThat(InputStream actual) {
         return AssertionsForClassTypes.assertThat(actual);
       }
     
    @@ -530,7 +530,7 @@ public static  FutureAssert assertThat(Future actual) {
        * @param actual the actual value.
        * @return the created assertion object.
        */
    -  public static AbstractFloatAssert assertThat(float actual) {
    +  public static FloatAssert assertThat(float actual) {
         return AssertionsForClassTypes.assertThat(actual);
       }
     
    @@ -540,7 +540,7 @@ public static AbstractFloatAssert assertThat(float actual) {
        * @param actual the actual value.
        * @return the created assertion object.
        */
    -  public static AbstractFloatAssert assertThat(Float actual) {
    +  public static FloatAssert assertThat(Float actual) {
         return AssertionsForClassTypes.assertThat(actual);
       }
     
    @@ -550,7 +550,7 @@ public static AbstractFloatAssert assertThat(Float actual) {
        * @param actual the actual value.
        * @return the created assertion object.
        */
    -  public static AbstractFloatArrayAssert assertThat(float[] actual) {
    +  public static FloatArrayAssert assertThat(float[] actual) {
         return AssertionsForClassTypes.assertThat(actual);
       }
     
    @@ -560,7 +560,7 @@ public static AbstractFloatArrayAssert assertThat(float[] actual) {
        * @param actual the actual value.
        * @return the created assertion object.
        */
    -  public static AbstractIntegerAssert assertThat(int actual) {
    +  public static IntegerAssert assertThat(int actual) {
         return AssertionsForClassTypes.assertThat(actual);
       }
     
    @@ -570,7 +570,7 @@ public static AbstractIntegerAssert assertThat(int actual) {
        * @param actual the actual value.
        * @return the created assertion object.
        */
    -  public static AbstractIntArrayAssert assertThat(int[] actual) {
    +  public static IntArrayAssert assertThat(int[] actual) {
         return AssertionsForClassTypes.assertThat(actual);
       }
     
    @@ -602,7 +602,7 @@ public static Float2DArrayAssert assertThat(float[][] actual) {
        * @param actual the actual value.
        * @return the created assertion object.
        */
    -  public static AbstractIntegerAssert assertThat(Integer actual) {
    +  public static IntegerAssert assertThat(Integer actual) {
         return AssertionsForClassTypes.assertThat(actual);
       }
     
    @@ -611,9 +611,9 @@ public static AbstractIntegerAssert assertThat(Integer actual) {
        * in order to perform assertions on it.
        * 

    * Navigational methods provided:

      - *
    • {@link AbstractIterableAssert#first() first()}
    • - *
    • {@link AbstractIterableAssert#last() last()}
    • - *
    • {@link AbstractIterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#first() first()}
    • + *
    • {@link IterableAssert#last() last()}
    • + *
    • {@link IterableAssert#elements(int...) element(int...)}
    • *
    *

    * The available assertions after navigating to an element depend on the {@code ELEMENT_ASSERT} parameter of the given @@ -655,9 +655,10 @@ FactoryBasedNavigableIterableAssert assertTh * in order to perform assertions on it. *

    * Navigational methods provided:

      - *
    • {@link AbstractIterableAssert#first() first()}
    • - *
    • {@link AbstractIterableAssert#last() last()}
    • - *
    • {@link AbstractIterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#first() first()}
    • + *
    • {@link IterableAssert#last() last()}
    • + *
    • {@link IterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#elements(int...) element(int...)}
    • *
    *

    * The available assertions after navigating to an element depend on the given {@code assertClass} @@ -690,9 +691,10 @@ ClassBasedNavigableIterableAssert assertThat * in order to perform assertions on it. *

    * Navigational methods provided:

      - *
    • {@link AbstractIterableAssert#first() first()}
    • - *
    • {@link AbstractIterableAssert#last() last()}
    • - *
    • {@link AbstractIterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#first() first()}
    • + *
    • {@link IterableAssert#last() last()}
    • + *
    • {@link IterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#elements(int...) element(int...)}
    • *
    *

    * The available assertions after navigating to an element depend on the {@code ELEMENT_ASSERT} parameter of the given @@ -733,9 +735,10 @@ FactoryBasedNavigableListAssert assertThat(L * in order to perform assertions on it. *

    * Navigational methods provided:

      - *
    • {@link AbstractIterableAssert#first() first()}
    • - *
    • {@link AbstractIterableAssert#last() last()}
    • - *
    • {@link AbstractIterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#first() first()}
    • + *
    • {@link IterableAssert#last() last()}
    • + *
    • {@link IterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#elements(int...) element(int...)}
    • *
    *

    * The available assertions after navigating to an element depend on the given {@code assertClass} @@ -771,7 +774,7 @@ ClassBasedNavigableListAssert assertThat(Lis * @param actual the actual value. * @return the created assertion object. */ - public static AbstractLongAssert assertThat(long actual) { + public static LongAssert assertThat(long actual) { return AssertionsForClassTypes.assertThat(actual); } @@ -781,7 +784,7 @@ public static AbstractLongAssert assertThat(long actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractLongAssert assertThat(Long actual) { + public static LongAssert assertThat(Long actual) { return AssertionsForClassTypes.assertThat(actual); } @@ -791,7 +794,7 @@ public static AbstractLongAssert assertThat(Long actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractLongArrayAssert assertThat(long[] actual) { + public static LongArrayAssert assertThat(long[] actual) { return AssertionsForClassTypes.assertThat(actual); } @@ -846,7 +849,7 @@ public static Object2DArrayAssert assertThat(T[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractShortAssert assertThat(short actual) { + public static ShortAssert assertThat(short actual) { return AssertionsForClassTypes.assertThat(actual); } @@ -856,7 +859,7 @@ public static AbstractShortAssert assertThat(short actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractShortAssert assertThat(Short actual) { + public static ShortAssert assertThat(Short actual) { return AssertionsForClassTypes.assertThat(actual); } @@ -866,7 +869,7 @@ public static AbstractShortAssert assertThat(Short actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractShortArrayAssert assertThat(short[] actual) { + public static ShortArrayAssert assertThat(short[] actual) { return AssertionsForClassTypes.assertThat(actual); } @@ -887,7 +890,7 @@ public static Short2DArrayAssert assertThat(short[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractDateAssert assertThat(Date actual) { + public static DateAssert assertThat(Date actual) { return AssertionsForClassTypes.assertThat(actual); } @@ -897,7 +900,7 @@ public static AbstractDateAssert assertThat(Date actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractZonedDateTimeAssert assertThat(ZonedDateTime actual) { + public static ZonedDateTimeAssert assertThat(ZonedDateTime actual) { return AssertionsForClassTypes.assertThat(actual); } @@ -907,7 +910,7 @@ public static AbstractZonedDateTimeAssert assertThat(ZonedDateTime actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractLocalDateTimeAssert assertThat(LocalDateTime actual) { + public static LocalDateTimeAssert assertThat(LocalDateTime actual) { return AssertionsForClassTypes.assertThat(actual); } @@ -917,7 +920,7 @@ public static AbstractLocalDateTimeAssert assertThat(LocalDateTime actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractOffsetDateTimeAssert assertThat(OffsetDateTime actual) { + public static OffsetDateTimeAssert assertThat(OffsetDateTime actual) { return AssertionsForClassTypes.assertThat(actual); } @@ -927,7 +930,7 @@ public static AbstractOffsetDateTimeAssert assertThat(OffsetDateTime actual) * @param actual the actual value. * @return the created assertion object. */ - public static AbstractOffsetTimeAssert assertThat(OffsetTime actual) { + public static OffsetTimeAssert assertThat(OffsetTime actual) { return AssertionsForClassTypes.assertThat(actual); } @@ -937,7 +940,7 @@ public static AbstractOffsetTimeAssert assertThat(OffsetTime actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractLocalTimeAssert assertThat(LocalTime actual) { + public static LocalTimeAssert assertThat(LocalTime actual) { return AssertionsForClassTypes.assertThat(actual); } @@ -947,7 +950,7 @@ public static AbstractLocalTimeAssert assertThat(LocalTime actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractLocalDateAssert assertThat(LocalDate actual) { + public static LocalDateAssert assertThat(LocalDate actual) { return AssertionsForClassTypes.assertThat(actual); } @@ -958,7 +961,7 @@ public static AbstractLocalDateAssert assertThat(LocalDate actual) { * @return the created assertion object. * @since 3.7.0 */ - public static AbstractInstantAssert assertThat(Instant actual) { + public static InstantAssert assertThat(Instant actual) { return AssertionsForClassTypes.assertThat(actual); } @@ -969,7 +972,7 @@ public static AbstractInstantAssert assertThat(Instant actual) { * @return the created assertion object. * @since 3.15.0 */ - public static AbstractDurationAssert assertThat(Duration actual) { + public static DurationAssert assertThat(Duration actual) { return AssertionsForClassTypes.assertThat(actual); } @@ -980,7 +983,7 @@ public static AbstractDurationAssert assertThat(Duration actual) { * @return the created assertion object. * @since 3.17.0 */ - public static AbstractPeriodAssert assertThat(Period actual) { + public static PeriodAssert assertThat(Period actual) { return AssertionsForClassTypes.assertThat(actual); } @@ -1141,7 +1144,7 @@ public static AtomicStampedReferenceAssert assertThat(AtomicStamp * @param actual the actual value. * @return the created {@link ThrowableAssert}. */ - public static AbstractThrowableAssert assertThat(Throwable actual) { + public static ThrowableAssert assertThat(Throwable actual) { return AssertionsForClassTypes.assertThat(actual); } @@ -1174,7 +1177,7 @@ public static AtomicStampedReferenceAssert assertThat(AtomicStamp * @return the created {@link ThrowableAssert}. */ @CanIgnoreReturnValue - public static AbstractThrowableAssert assertThatThrownBy(ThrowingCallable shouldRaiseThrowable) { + public static ThrowableAssert assertThatThrownBy(ThrowingCallable shouldRaiseThrowable) { return assertThat(catchThrowable(shouldRaiseThrowable)).hasBeenThrown(); } @@ -1211,7 +1214,7 @@ public static AtomicStampedReferenceAssert assertThat(AtomicStamp * @since 3.9.0 */ @CanIgnoreReturnValue - public static AbstractThrowableAssert assertThatThrownBy(ThrowingCallable shouldRaiseThrowable, + public static ThrowableAssert assertThatThrownBy(ThrowingCallable shouldRaiseThrowable, String description, Object... args) { return assertThat(catchThrowable(shouldRaiseThrowable)).as(description, args).hasBeenThrown(); } @@ -1251,7 +1254,7 @@ public static AtomicStampedReferenceAssert assertThat(AtomicStamp * @return the created {@link ThrowableAssert}. * @since 3.7.0 */ - public static AbstractThrowableAssert assertThatCode(ThrowingCallable shouldRaiseOrNotThrowable) { + public static ThrowableAssert assertThatCode(ThrowingCallable shouldRaiseOrNotThrowable) { return AssertionsForClassTypes.assertThatCode(shouldRaiseOrNotThrowable); } @@ -1280,6 +1283,33 @@ public static ObjectAssert assertThatObject(T actual) { return assertThat(actual); } + /** + * Uses the given instance as the instance under test for all the assertions expressed as the passed {@link Consumer}. + *

    + * This is useful to avoid repeating getting the instance to test, a bit like a with block which turns the target into + * the equivalent of {@code this} (as in Groovy for example). + *

    + * Example: + *

     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);
    +   *            });
    + *

    + * {@code assertWith} is variation of {@link AbstractAssert#satisfies(Consumer)} hopefully easier to find for some users. + * + * @param the type of the actual value. + * @param actual the actual value. + * @param requirements to assert on the actual object - must not be null. + * @return the created assertion object. + * @since 3.20.0 + */ + @CanIgnoreReturnValue + public static ObjectAssert assertWith(T actual, Consumer requirements) { + return assertThat(actual).satisfies(requirements); + } + /** * Allows catching a {@link Throwable} more easily when used with Java 8 lambdas. *

    @@ -1493,7 +1523,6 @@ public static T fail(String failureMessage, Throwable realCause) { * @return nothing, it's just to be used in doSomething(optional.orElse(() -> failBecauseExceptionWasNotThrown(IOException.class)));. * @throws AssertionError with a message explaining that a {@link Throwable} of given class was expected to be thrown but had * not been. - * */ @CanIgnoreReturnValue public static T failBecauseExceptionWasNotThrown(Class throwableClass) { @@ -2797,7 +2826,7 @@ public static T assertThat(final AssertProvider component) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractCharSequenceAssert assertThat(CharSequence actual) { + public static CharSequenceAssert assertThat(CharSequence actual) { return AssertionsForInterfaceTypes.assertThat(actual); } @@ -2808,7 +2837,7 @@ public static T assertThat(final AssertProvider component) { * @return the created assertion object. * @since 3.11.0 */ - public static AbstractCharSequenceAssert assertThat(StringBuilder actual) { + public static CharSequenceAssert assertThat(StringBuilder actual) { return AssertionsForClassTypes.assertThat(actual); } @@ -2819,7 +2848,7 @@ public static T assertThat(final AssertProvider component) { * @return the created assertion object. * @since 3.11.0 */ - public static AbstractCharSequenceAssert assertThat(StringBuffer actual) { + public static CharSequenceAssert assertThat(StringBuffer actual) { return AssertionsForClassTypes.assertThat(actual); } @@ -2829,7 +2858,7 @@ public static T assertThat(final AssertProvider component) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractStringAssert assertThat(String actual) { + public static StringAssert assertThat(String actual) { return AssertionsForClassTypes.assertThat(actual); } @@ -3029,7 +3058,7 @@ public static SpliteratorAssert assertThat(Spliterator assertThat(Path actual) { + public static PathAssert assertThat(Path actual) { return AssertionsForInterfaceTypes.assertThat(actual); } @@ -3056,7 +3085,7 @@ public static MapAssert assertThat(Map actual) { * @param actual the actual value. * @return the created assertion object. */ - public static > AbstractComparableAssert assertThat(T actual) { + public static > GenericComparableAssert assertThat(T actual) { return AssertionsForInterfaceTypes.assertThat(actual); } diff --git a/src/main/java/org/assertj/core/api/AssertionsForClassTypes.java b/src/main/java/org/assertj/core/api/AssertionsForClassTypes.java index f900e90f2b3..05a5f8ce9ec 100644 --- a/src/main/java/org/assertj/core/api/AssertionsForClassTypes.java +++ b/src/main/java/org/assertj/core/api/AssertionsForClassTypes.java @@ -137,7 +137,7 @@ public static OptionalLongAssert assertThat(OptionalLong actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractBigDecimalAssert assertThat(BigDecimal actual) { + public static BigDecimalAssert assertThat(BigDecimal actual) { return new BigDecimalAssert(actual); } @@ -147,7 +147,7 @@ public static AbstractBigDecimalAssert assertThat(BigDecimal actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractUriAssert assertThat(URI actual) { + public static UriAssert assertThat(URI actual) { return new UriAssert(actual); } @@ -157,7 +157,7 @@ public static AbstractUriAssert assertThat(URI actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractUrlAssert assertThat(URL actual) { + public static UrlAssert assertThat(URL actual) { return new UrlAssert(actual); } @@ -167,7 +167,7 @@ public static AbstractUrlAssert assertThat(URL actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractBooleanAssert assertThat(boolean actual) { + public static BooleanAssert assertThat(boolean actual) { return new BooleanAssert(actual); } @@ -177,7 +177,7 @@ public static AbstractBooleanAssert assertThat(boolean actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractBooleanAssert assertThat(Boolean actual) { + public static BooleanAssert assertThat(Boolean actual) { return new BooleanAssert(actual); } @@ -187,7 +187,7 @@ public static AbstractBooleanAssert assertThat(Boolean actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractBooleanArrayAssert assertThat(boolean[] actual) { + public static BooleanArrayAssert assertThat(boolean[] actual) { return new BooleanArrayAssert(actual); } @@ -208,7 +208,7 @@ public static Boolean2DArrayAssert assertThat(boolean[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractByteAssert assertThat(byte actual) { + public static ByteAssert assertThat(byte actual) { return new ByteAssert(actual); } @@ -218,7 +218,7 @@ public static AbstractByteAssert assertThat(byte actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractByteAssert assertThat(Byte actual) { + public static ByteAssert assertThat(Byte actual) { return new ByteAssert(actual); } @@ -228,7 +228,7 @@ public static AbstractByteAssert assertThat(Byte actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractByteArrayAssert assertThat(byte[] actual) { + public static ByteArrayAssert assertThat(byte[] actual) { return new ByteArrayAssert(actual); } @@ -249,7 +249,7 @@ public static Byte2DArrayAssert assertThat(byte[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractCharacterAssert assertThat(char actual) { + public static CharacterAssert assertThat(char actual) { return new CharacterAssert(actual); } @@ -259,7 +259,7 @@ public static AbstractCharacterAssert assertThat(char actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractCharArrayAssert assertThat(char[] actual) { + public static CharArrayAssert assertThat(char[] actual) { return new CharArrayAssert(actual); } @@ -280,7 +280,7 @@ public static Char2DArrayAssert assertThat(char[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractCharacterAssert assertThat(Character actual) { + public static CharacterAssert assertThat(Character actual) { return new CharacterAssert(actual); } @@ -300,7 +300,7 @@ public static ClassAssert assertThat(Class actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractDoubleAssert assertThat(double actual) { + public static DoubleAssert assertThat(double actual) { return new DoubleAssert(actual); } @@ -310,7 +310,7 @@ public static AbstractDoubleAssert assertThat(double actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractDoubleAssert assertThat(Double actual) { + public static DoubleAssert assertThat(Double actual) { return new DoubleAssert(actual); } @@ -320,7 +320,7 @@ public static AbstractDoubleAssert assertThat(Double actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractDoubleArrayAssert assertThat(double[] actual) { + public static DoubleArrayAssert assertThat(double[] actual) { return new DoubleArrayAssert(actual); } @@ -341,7 +341,7 @@ public static Double2DArrayAssert assertThat(double[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractFileAssert assertThat(File actual) { + public static FileAssert assertThat(File actual) { return new FileAssert(actual); } @@ -351,7 +351,7 @@ public static AbstractFileAssert assertThat(File actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractInputStreamAssert assertThat(InputStream actual) { + public static InputStreamAssert assertThat(InputStream actual) { return new InputStreamAssert(actual); } @@ -361,7 +361,7 @@ public static AbstractFileAssert assertThat(File actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractFloatAssert assertThat(float actual) { + public static FloatAssert assertThat(float actual) { return new FloatAssert(actual); } @@ -371,7 +371,7 @@ public static AbstractFloatAssert assertThat(float actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractFloatAssert assertThat(Float actual) { + public static FloatAssert assertThat(Float actual) { return new FloatAssert(actual); } @@ -381,7 +381,7 @@ public static AbstractFloatAssert assertThat(Float actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractFloatArrayAssert assertThat(float[] actual) { + public static FloatArrayAssert assertThat(float[] actual) { return new FloatArrayAssert(actual); } @@ -402,7 +402,7 @@ public static Float2DArrayAssert assertThat(float[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractIntegerAssert assertThat(int actual) { + public static IntegerAssert assertThat(int actual) { return new IntegerAssert(actual); } @@ -412,7 +412,7 @@ public static AbstractIntegerAssert assertThat(int actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractIntArrayAssert assertThat(int[] actual) { + public static IntArrayAssert assertThat(int[] actual) { return new IntArrayAssert(actual); } @@ -433,7 +433,7 @@ public static Int2DArrayAssert assertThat(int[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractIntegerAssert assertThat(Integer actual) { + public static IntegerAssert assertThat(Integer actual) { return new IntegerAssert(actual); } @@ -443,7 +443,7 @@ public static AbstractIntegerAssert assertThat(Integer actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractLongAssert assertThat(long actual) { + public static LongAssert assertThat(long actual) { return new LongAssert(actual); } @@ -453,7 +453,7 @@ public static AbstractLongAssert assertThat(long actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractLongAssert assertThat(Long actual) { + public static LongAssert assertThat(Long actual) { return new LongAssert(actual); } @@ -463,7 +463,7 @@ public static AbstractLongAssert assertThat(Long actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractLongArrayAssert assertThat(long[] actual) { + public static LongArrayAssert assertThat(long[] actual) { return new LongArrayAssert(actual); } @@ -518,7 +518,7 @@ public static Object2DArrayAssert assertThat(T[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractShortAssert assertThat(short actual) { + public static ShortAssert assertThat(short actual) { return new ShortAssert(actual); } @@ -528,7 +528,7 @@ public static AbstractShortAssert assertThat(short actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractShortAssert assertThat(Short actual) { + public static ShortAssert assertThat(Short actual) { return new ShortAssert(actual); } @@ -538,7 +538,7 @@ public static AbstractShortAssert assertThat(Short actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractShortArrayAssert assertThat(short[] actual) { + public static ShortArrayAssert assertThat(short[] actual) { return new ShortArrayAssert(actual); } @@ -560,7 +560,7 @@ public static Short2DArrayAssert assertThat(short[][] actual) { * @return the created assertion object. * @since 3.11.0 */ - public static AbstractCharSequenceAssert assertThat(StringBuilder actual) { + public static CharSequenceAssert assertThat(StringBuilder actual) { return new CharSequenceAssert(actual); } @@ -571,7 +571,7 @@ public static Short2DArrayAssert assertThat(short[][] actual) { * @return the created assertion object. * @since 3.11.0 */ - public static AbstractCharSequenceAssert assertThat(StringBuffer actual) { + public static CharSequenceAssert assertThat(StringBuffer actual) { return new CharSequenceAssert(actual); } @@ -581,7 +581,7 @@ public static Short2DArrayAssert assertThat(short[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractStringAssert assertThat(String actual) { + public static StringAssert assertThat(String actual) { return new StringAssert(actual); } @@ -591,7 +591,7 @@ public static AbstractStringAssert assertThat(String actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractDateAssert assertThat(Date actual) { + public static DateAssert assertThat(Date actual) { return new DateAssert(actual); } @@ -601,7 +601,7 @@ public static AbstractDateAssert assertThat(Date actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractZonedDateTimeAssert assertThat(ZonedDateTime actual) { + public static ZonedDateTimeAssert assertThat(ZonedDateTime actual) { return new ZonedDateTimeAssert(actual); } @@ -611,7 +611,7 @@ public static AbstractZonedDateTimeAssert assertThat(ZonedDateTime actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractLocalDateTimeAssert assertThat(LocalDateTime actual) { + public static LocalDateTimeAssert assertThat(LocalDateTime actual) { return new LocalDateTimeAssert(actual); } @@ -621,7 +621,7 @@ public static AbstractLocalDateTimeAssert assertThat(LocalDateTime actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractOffsetDateTimeAssert assertThat(OffsetDateTime actual) { + public static OffsetDateTimeAssert assertThat(OffsetDateTime actual) { return new OffsetDateTimeAssert(actual); } @@ -631,7 +631,7 @@ public static AbstractOffsetDateTimeAssert assertThat(OffsetDateTime actual) * @param actual the actual value. * @return the created assertion object. */ - public static AbstractOffsetTimeAssert assertThat(OffsetTime actual) { + public static OffsetTimeAssert assertThat(OffsetTime actual) { return new OffsetTimeAssert(actual); } @@ -641,7 +641,7 @@ public static AbstractOffsetTimeAssert assertThat(OffsetTime actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractLocalTimeAssert assertThat(LocalTime actual) { + public static LocalTimeAssert assertThat(LocalTime actual) { return new LocalTimeAssert(actual); } @@ -651,7 +651,7 @@ public static AbstractLocalTimeAssert assertThat(LocalTime actual) { * @param localDate the actual value. * @return the created assertion object. */ - public static AbstractLocalDateAssert assertThat(LocalDate localDate) { + public static LocalDateAssert assertThat(LocalDate localDate) { return new LocalDateAssert(localDate); } @@ -662,7 +662,7 @@ public static AbstractLocalDateAssert assertThat(LocalDate localDate) { * @return the created assertion object. * @since 3.7.0 */ - public static AbstractInstantAssert assertThat(Instant instant) { + public static InstantAssert assertThat(Instant instant) { return new InstantAssert(instant); } @@ -673,7 +673,7 @@ public static AbstractInstantAssert assertThat(Instant instant) { * @return the created assertion object. * @since 3.15.0 */ - public static AbstractDurationAssert assertThat(Duration duration) { + public static DurationAssert assertThat(Duration duration) { return new DurationAssert(duration); } @@ -684,7 +684,7 @@ public static AbstractDurationAssert assertThat(Duration duration) { * @return the created assertion object. * @since 3.17.0 */ - public static AbstractPeriodAssert assertThat(Period period) { + public static PeriodAssert assertThat(Period period) { return new PeriodAssert(period); } @@ -694,7 +694,7 @@ public static AbstractPeriodAssert assertThat(Period period) { * @param actual the actual value. * @return the created {@link ThrowableAssert}. */ - public static AbstractThrowableAssert assertThat(Throwable actual) { + public static ThrowableAssert assertThat(Throwable actual) { return new ThrowableAssert(actual); } @@ -727,7 +727,7 @@ public static AbstractPeriodAssert assertThat(Period period) { * @return the created {@link ThrowableAssert}. */ @CanIgnoreReturnValue - public static AbstractThrowableAssert assertThatThrownBy(ThrowingCallable shouldRaiseThrowable) { + public static ThrowableAssert assertThatThrownBy(ThrowingCallable shouldRaiseThrowable) { return assertThat(catchThrowable(shouldRaiseThrowable)).hasBeenThrown(); } @@ -764,7 +764,7 @@ public static AbstractPeriodAssert assertThat(Period period) { * @since 3.9.0 */ @CanIgnoreReturnValue - public static AbstractThrowableAssert assertThatThrownBy(ThrowingCallable shouldRaiseThrowable, + public static ThrowableAssert assertThatThrownBy(ThrowingCallable shouldRaiseThrowable, String description, Object... args) { return assertThat(catchThrowable(shouldRaiseThrowable)).as(description, args).hasBeenThrown(); } @@ -844,7 +844,7 @@ public static NotThrownAssert assertThatNoException() { * @return The captured exception or null if none was raised by the callable. * @since 3.7.0 */ - public static AbstractThrowableAssert assertThatCode(ThrowingCallable shouldRaiseOrNotThrowable) { + public static ThrowableAssert assertThatCode(ThrowingCallable shouldRaiseOrNotThrowable) { return assertThat(catchThrowable(shouldRaiseOrNotThrowable)); } @@ -1088,9 +1088,9 @@ public static Tuple tuple(Object... values) { /** * Globally sets whether - * {@link org.assertj.core.api.AbstractIterableAssert#extracting(String) IterableAssert#extracting(String)} + * {@link org.assertj.core.api.IterableAssert#extracting(String) IterableAssert#extracting(String)} * and - * {@link org.assertj.core.api.AbstractObjectArrayAssert#extracting(String) ObjectArrayAssert#extracting(String)} + * {@link org.assertj.core.api.ObjectArrayAssert#extracting(String) ObjectArrayAssert#extracting(String)} * should be allowed to extract private fields, if not and they try it fails with exception. * * @param allowExtractingPrivateFields allow private fields extraction. Default {@code true}. @@ -1103,8 +1103,8 @@ public static void setAllowExtractingPrivateFields(boolean allowExtractingPrivat * Globally sets whether the use of private fields is allowed for comparison. * The following (incomplete) list of methods will be impacted by this change : *

      - *
    • {@link org.assertj.core.api.AbstractIterableAssert#usingElementComparatorOnFields(java.lang.String...)}
    • - *
    • {@link org.assertj.core.api.AbstractObjectAssert#isEqualToComparingFieldByField(Object)}
    • + *
    • {@link org.assertj.core.api.IterableAssert#usingElementComparatorOnFields(java.lang.String...)}
    • + *
    • {@link org.assertj.core.api.ObjectAssert#isEqualToComparingFieldByField(Object)}
    • *
    * * If the value is false and these methods try to compare private fields, it will fail with an exception. @@ -1472,7 +1472,7 @@ public static Filters filter(Iterable iterableToFilter) { } /** - * Create a {@link FilterOperator} to use in {@link AbstractIterableAssert#filteredOn(String, FilterOperator) + * Create a {@link FilterOperator} to use in {@link IterableAssert#filteredOn(String, FilterOperator) * filteredOn(String, FilterOperation)} to express a filter keeping all Iterable elements whose property/field * value matches one of the given values. *

    @@ -1496,7 +1496,7 @@ public static InFilter in(Object... values) { } /** - * Create a {@link FilterOperator} to use in {@link AbstractIterableAssert#filteredOn(String, FilterOperator) + * Create a {@link FilterOperator} to use in {@link IterableAssert#filteredOn(String, FilterOperator) * filteredOn(String, FilterOperation)} to express a filter keeping all Iterable elements whose property/field * value matches does not match any of the given values. *

    @@ -1520,7 +1520,7 @@ public static NotInFilter notIn(Object... valuesNotToMatch) { } /** - * Create a {@link FilterOperator} to use in {@link AbstractIterableAssert#filteredOn(String, FilterOperator) + * Create a {@link FilterOperator} to use in {@link IterableAssert#filteredOn(String, FilterOperator) * filteredOn(String, FilterOperation)} to express a filter keeping all Iterable elements whose property/field * value matches does not match the given value. *

    @@ -1774,7 +1774,7 @@ public static void setLenientDateParsing(boolean value) { /** * Add the given date format to the ones used to parse date String in String based Date assertions like - * {@link org.assertj.core.api.AbstractDateAssert#isEqualTo(String)}. + * {@link org.assertj.core.api.DateAssert#isEqualTo(String)}. *

    * User date formats are used before default ones in the order they have been registered (first registered, first * used). @@ -1790,7 +1790,7 @@ public static void setLenientDateParsing(boolean value) { * Beware that AssertJ will use the newly registered format for all remaining Date assertions in the test suite *

    * To revert to default formats only, call {@link #useDefaultDateFormatsOnly()} or - * {@link org.assertj.core.api.AbstractDateAssert#withDefaultDateFormatsOnly()}. + * {@link org.assertj.core.api.DateAssert#withDefaultDateFormatsOnly()}. *

    * Code examples: * @@ -1820,7 +1820,7 @@ public static void registerCustomDateFormat(DateFormat userCustomDateFormat) { /** * Add the given date format to the ones used to parse date String in String based Date assertions like - * {@link org.assertj.core.api.AbstractDateAssert#isEqualTo(String)}. + * {@link org.assertj.core.api.DateAssert#isEqualTo(String)}. *

    * User date formats are used before default ones in the order they have been registered (first registered, first * used). diff --git a/src/main/java/org/assertj/core/api/AssertionsForInterfaceTypes.java b/src/main/java/org/assertj/core/api/AssertionsForInterfaceTypes.java index 2bde801dae0..7be900c9d86 100644 --- a/src/main/java/org/assertj/core/api/AssertionsForInterfaceTypes.java +++ b/src/main/java/org/assertj/core/api/AssertionsForInterfaceTypes.java @@ -92,7 +92,7 @@ protected AssertionsForInterfaceTypes() {} * @param actual the actual value. * @return the created assertion object. */ - public static AbstractCharSequenceAssert assertThat(CharSequence actual) { + public static CharSequenceAssert assertThat(CharSequence actual) { return new CharSequenceAssert(actual); } @@ -296,7 +296,7 @@ ClassBasedNavigableListAssert assertThat(Lis * @param actual the path to test * @return the created assertion object */ - public static AbstractPathAssert assertThat(Path actual) { + public static PathAssert assertThat(Path actual) { return new PathAssert(actual); } @@ -323,7 +323,7 @@ public static MapAssert assertThat(Map actual) { * @param actual the actual value. * @return the created assertion object. */ - public static > AbstractComparableAssert assertThat(T actual) { + public static > GenericComparableAssert assertThat(T actual) { return new GenericComparableAssert<>(actual); } diff --git a/src/main/java/org/assertj/core/api/Assumptions.java b/src/main/java/org/assertj/core/api/Assumptions.java index ea3da772806..82b620f1885 100644 --- a/src/main/java/org/assertj/core/api/Assumptions.java +++ b/src/main/java/org/assertj/core/api/Assumptions.java @@ -130,8 +130,8 @@ public static Object intercept(@This AbstractAssert assertion, @SuperCall * @since 2.9.0 / 3.9.0 */ @SuppressWarnings("unchecked") - public static ProxyableObjectAssert assumeThat(T actual) { - return asAssumption(ProxyableObjectAssert.class, Object.class, actual); + public static ObjectAssert assumeThat(T actual) { + return asAssumption(ObjectAssert.class, Object.class, actual); } /** @@ -141,7 +141,7 @@ public static ProxyableObjectAssert assumeThat(T actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractStringAssert assumeThat(String actual) { + public static StringAssert assumeThat(String actual) { return asAssumption(StringAssert.class, String.class, actual); } @@ -152,7 +152,7 @@ public static AbstractStringAssert assumeThat(String actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractBigDecimalAssert assumeThat(BigDecimal actual) { + public static BigDecimalAssert assumeThat(BigDecimal actual) { return asAssumption(BigDecimalAssert.class, BigDecimal.class, actual); } @@ -163,7 +163,7 @@ public static AbstractBigDecimalAssert assumeThat(BigDecimal actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractBigIntegerAssert assumeThat(BigInteger actual) { + public static BigIntegerAssert assumeThat(BigInteger actual) { return asAssumption(BigIntegerAssert.class, BigInteger.class, actual); } @@ -174,7 +174,7 @@ public static AbstractBigIntegerAssert assumeThat(BigInteger actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractUriAssert assumeThat(URI actual) { + public static UriAssert assumeThat(URI actual) { return asAssumption(UriAssert.class, URI.class, actual); } @@ -185,7 +185,7 @@ public static AbstractUriAssert assumeThat(URI actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractUrlAssert assumeThat(URL actual) { + public static UrlAssert assumeThat(URL actual) { return asAssumption(UrlAssert.class, URL.class, actual); } @@ -196,7 +196,7 @@ public static AbstractUrlAssert assumeThat(URL actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractBooleanAssert assumeThat(boolean actual) { + public static BooleanAssert assumeThat(boolean actual) { return asAssumption(BooleanAssert.class, Boolean.class, actual); } @@ -207,7 +207,7 @@ public static AbstractBooleanAssert assumeThat(boolean actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractBooleanAssert assumeThat(Boolean actual) { + public static BooleanAssert assumeThat(Boolean actual) { return asAssumption(BooleanAssert.class, Boolean.class, actual); } @@ -218,7 +218,7 @@ public static AbstractBooleanAssert assumeThat(Boolean actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractBooleanArrayAssert assumeThat(boolean[] actual) { + public static BooleanArrayAssert assumeThat(boolean[] actual) { return asAssumption(BooleanArrayAssert.class, boolean[].class, actual); } @@ -240,7 +240,7 @@ public static Boolean2DArrayAssert assumeThat(boolean[][] actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractByteAssert assumeThat(byte actual) { + public static ByteAssert assumeThat(byte actual) { return asAssumption(ByteAssert.class, Byte.class, actual); } @@ -251,7 +251,7 @@ public static AbstractByteAssert assumeThat(byte actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractByteAssert assumeThat(Byte actual) { + public static ByteAssert assumeThat(Byte actual) { return asAssumption(ByteAssert.class, Byte.class, actual); } @@ -262,7 +262,7 @@ public static AbstractByteAssert assumeThat(Byte actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractByteArrayAssert assumeThat(byte[] actual) { + public static ByteArrayAssert assumeThat(byte[] actual) { return asAssumption(ByteArrayAssert.class, byte[].class, actual); } @@ -284,7 +284,7 @@ public static Byte2DArrayAssert assumeThat(byte[][] actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractCharacterAssert assumeThat(char actual) { + public static CharacterAssert assumeThat(char actual) { return asAssumption(CharacterAssert.class, Character.class, actual); } @@ -295,7 +295,7 @@ public static AbstractCharacterAssert assumeThat(char actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractCharacterAssert assumeThat(Character actual) { + public static CharacterAssert assumeThat(Character actual) { return asAssumption(CharacterAssert.class, Character.class, actual); } @@ -306,7 +306,7 @@ public static AbstractCharacterAssert assumeThat(Character actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractCharArrayAssert assumeThat(char[] actual) { + public static CharArrayAssert assumeThat(char[] actual) { return asAssumption(CharArrayAssert.class, char[].class, actual); } @@ -328,7 +328,7 @@ public static Char2DArrayAssert assumeThat(char[][] actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractCharSequenceAssert assumeThat(CharSequence actual) { + public static CharSequenceAssert assumeThat(CharSequence actual) { return asAssumption(CharSequenceAssert.class, CharSequence.class, actual); } @@ -339,7 +339,7 @@ public static Char2DArrayAssert assumeThat(char[][] actual) { * @return the created assumption for assertion object. * @since 3.11.0 */ - public static AbstractCharSequenceAssert assumeThat(StringBuilder actual) { + public static CharSequenceAssert assumeThat(StringBuilder actual) { return asAssumption(CharSequenceAssert.class, CharSequence.class, actual); } @@ -350,7 +350,7 @@ public static Char2DArrayAssert assumeThat(char[][] actual) { * @return the created assumption for assertion object. * @since 3.11.0 */ - public static AbstractCharSequenceAssert assumeThat(StringBuffer actual) { + public static CharSequenceAssert assumeThat(StringBuffer actual) { return asAssumption(CharSequenceAssert.class, CharSequence.class, actual); } @@ -361,7 +361,7 @@ public static Char2DArrayAssert assumeThat(char[][] actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractShortAssert assumeThat(short actual) { + public static ShortAssert assumeThat(short actual) { return asAssumption(ShortAssert.class, Short.class, actual); } @@ -372,7 +372,7 @@ public static AbstractShortAssert assumeThat(short actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractShortAssert assumeThat(Short actual) { + public static ShortAssert assumeThat(Short actual) { return asAssumption(ShortAssert.class, Short.class, actual); } @@ -383,7 +383,7 @@ public static AbstractShortAssert assumeThat(Short actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractShortArrayAssert assumeThat(short[] actual) { + public static ShortArrayAssert assumeThat(short[] actual) { return asAssumption(ShortArrayAssert.class, short[].class, actual); } @@ -405,7 +405,7 @@ public static Short2DArrayAssert assumeThat(short[][] actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractIntegerAssert assumeThat(int actual) { + public static IntegerAssert assumeThat(int actual) { return asAssumption(IntegerAssert.class, Integer.class, actual); } @@ -416,7 +416,7 @@ public static AbstractIntegerAssert assumeThat(int actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractIntegerAssert assumeThat(Integer actual) { + public static IntegerAssert assumeThat(Integer actual) { return asAssumption(IntegerAssert.class, Integer.class, actual); } @@ -427,7 +427,7 @@ public static AbstractIntegerAssert assumeThat(Integer actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractIntArrayAssert assumeThat(int[] actual) { + public static IntArrayAssert assumeThat(int[] actual) { return asAssumption(IntArrayAssert.class, int[].class, actual); } @@ -449,7 +449,7 @@ public static Int2DArrayAssert assumeThat(int[][] actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractLongAssert assumeThat(long actual) { + public static LongAssert assumeThat(long actual) { return asAssumption(LongAssert.class, Long.class, actual); } @@ -460,7 +460,7 @@ public static AbstractLongAssert assumeThat(long actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractLongAssert assumeThat(Long actual) { + public static LongAssert assumeThat(Long actual) { return asAssumption(LongAssert.class, Long.class, actual); } @@ -471,7 +471,7 @@ public static AbstractLongAssert assumeThat(Long actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractLongArrayAssert assumeThat(long[] actual) { + public static LongArrayAssert assumeThat(long[] actual) { return asAssumption(LongArrayAssert.class, long[].class, actual); } @@ -493,7 +493,7 @@ public static Long2DArrayAssert assumeThat(long[][] actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractFloatAssert assumeThat(float actual) { + public static FloatAssert assumeThat(float actual) { return asAssumption(FloatAssert.class, Float.class, actual); } @@ -504,7 +504,7 @@ public static AbstractFloatAssert assumeThat(float actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractFloatAssert assumeThat(Float actual) { + public static FloatAssert assumeThat(Float actual) { return asAssumption(FloatAssert.class, Float.class, actual); } @@ -515,7 +515,7 @@ public static AbstractFloatAssert assumeThat(Float actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractFloatArrayAssert assumeThat(float[] actual) { + public static FloatArrayAssert assumeThat(float[] actual) { return asAssumption(FloatArrayAssert.class, float[].class, actual); } @@ -537,7 +537,7 @@ public static Float2DArrayAssert assumeThat(float[][] actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractDoubleAssert assumeThat(double actual) { + public static DoubleAssert assumeThat(double actual) { return asAssumption(DoubleAssert.class, Double.class, actual); } @@ -548,7 +548,7 @@ public static AbstractDoubleAssert assumeThat(double actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractDoubleAssert assumeThat(Double actual) { + public static DoubleAssert assumeThat(Double actual) { return asAssumption(DoubleAssert.class, Double.class, actual); } @@ -559,7 +559,7 @@ public static AbstractDoubleAssert assumeThat(Double actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractDoubleArrayAssert assumeThat(double[] actual) { + public static DoubleArrayAssert assumeThat(double[] actual) { return asAssumption(DoubleArrayAssert.class, double[].class, actual); } @@ -740,8 +740,8 @@ public static AtomicStampedReferenceAssert assumeThat(AtomicStamp * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractClassAssert assumeThat(Class actual) { - return asAssumption(ProxyableClassAssert.class, Class.class, actual); + public static ClassAssert assumeThat(Class actual) { + return asAssumption(ClassAssert.class, Class.class, actual); } /** @@ -751,7 +751,7 @@ public static AbstractClassAssert assumeThat(Class actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractDateAssert assumeThat(Date actual) { + public static DateAssert assumeThat(Date actual) { return asAssumption(DateAssert.class, Date.class, actual); } @@ -762,7 +762,7 @@ public static AbstractDateAssert assumeThat(Date actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractFileAssert assumeThat(File actual) { + public static FileAssert assumeThat(File actual) { return asAssumption(FileAssert.class, File.class, actual); } @@ -773,7 +773,7 @@ public static AbstractFileAssert assumeThat(File actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractPathAssert assumeThat(Path actual) { + public static PathAssert assumeThat(Path actual) { return asAssumption(PathAssert.class, Path.class, actual); } @@ -784,7 +784,7 @@ public static AbstractPathAssert assumeThat(Path actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractInputStreamAssert assumeThat(InputStream actual) { + public static InputStreamAssert assumeThat(InputStream actual) { return asAssumption(InputStreamAssert.class, InputStream.class, actual); } @@ -798,7 +798,7 @@ public static AbstractPathAssert assumeThat(Path actual) { * @since 2.9.0 / 3.9.0 */ @SuppressWarnings("unchecked") - public static AbstractFutureAssert, RESULT> assumeThat(Future future) { + public static FutureAssert assumeThat(Future future) { return asAssumption(FutureAssert.class, Future.class, future); } @@ -811,14 +811,12 @@ public static AbstractPathAssert assumeThat(Path actual) { * @since 2.9.0 / 3.9.0 */ @SuppressWarnings("unchecked") - public static ProxyableIterableAssert assumeThat(Iterable actual) { - return asAssumption(ProxyableIterableAssert.class, Iterable.class, actual); + public static IterableAssert assumeThat(Iterable actual) { + return asAssumption(IterableAssert.class, Iterable.class, actual); } /** * Creates a new instance of {@link IteratorAssert} assumption. - *

    - * Breaking change in version 3.12.0: this method does not return anymore an {@link ProxyableIterableAssert} but an {@link IteratorAssert}.
    * * @param the type of elements. * @param actual the actual value. @@ -839,8 +837,8 @@ public static IteratorAssert assumeThat(Iterator FactoryBasedNavigableListAssert, List, ELEMENT, ObjectAssert> assumeThat(List actual) { - return asAssumption(ProxyableListAssert.class, List.class, actual); + public static ListAssert assumeThat(List actual) { + return asAssumption(ListAssert.class, List.class, actual); } /** @@ -852,8 +850,8 @@ public static FactoryBasedNavigableListAssert ProxyableObjectArrayAssert assumeThat(T[] actual) { - return asAssumption(ProxyableObjectArrayAssert.class, Object[].class, actual); + public static ObjectArrayAssert assumeThat(T[] actual) { + return asAssumption(ObjectArrayAssert.class, Object[].class, actual); } /** @@ -879,8 +877,8 @@ public static Object2DArrayAssert assumeThat(T[][] actual) { * @since 2.9.0 / 3.9.0 */ @SuppressWarnings("unchecked") - public static AbstractMapAssert assumeThat(Map actual) { - return asAssumption(ProxyableMapAssert.class, Map.class, actual); + public static MapAssert assumeThat(Map actual) { + return asAssumption(MapAssert.class, Map.class, actual); } /** @@ -892,7 +890,7 @@ public static Object2DArrayAssert assumeThat(T[][] actual) { * @since 2.9.0 / 3.9.0 */ @SuppressWarnings("unchecked") - public static > AbstractComparableAssert assumeThat(T actual) { + public static > GenericComparableAssert assumeThat(T actual) { return asAssumption(GenericComparableAssert.class, Comparable.class, actual); } @@ -903,7 +901,7 @@ public static > AbstractComparableAssert a * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractThrowableAssert assumeThat(Throwable actual) { + public static ThrowableAssert assumeThat(Throwable actual) { return asAssumption(ThrowableAssert.class, Throwable.class, actual); } @@ -921,7 +919,7 @@ public static > AbstractComparableAssert a * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - public static AbstractThrowableAssert assumeThatThrownBy(ThrowingCallable shouldRaiseThrowable) { + public static ThrowableAssert assumeThatThrownBy(ThrowingCallable shouldRaiseThrowable) { return asAssumption(ThrowableAssert.class, Throwable.class, catchThrowable(shouldRaiseThrowable)); } @@ -948,7 +946,7 @@ public static > AbstractComparableAssert a * @return the created {@link ThrowableAssert}. * @since 3.9.0 */ - public static AbstractThrowableAssert assumeThatCode(ThrowingCallable shouldRaiseOrNotThrowable) { + public static ThrowableAssert assumeThatCode(ThrowingCallable shouldRaiseOrNotThrowable) { return assumeThat(catchThrowable(shouldRaiseOrNotThrowable)); } @@ -970,7 +968,7 @@ public static > AbstractComparableAssert a * @return the created assertion object. * @since 3.12.0 */ - public static ProxyableObjectAssert assumeThatObject(T actual) { + public static ObjectAssert assumeThatObject(T actual) { return assumeThat(actual); } @@ -983,8 +981,8 @@ public static ProxyableObjectAssert assumeThatObject(T actual) { * @since 3.9.0 */ @SuppressWarnings("unchecked") - public static ProxyablePredicateAssert assumeThat(Predicate actual) { - return asAssumption(ProxyablePredicateAssert.class, Predicate.class, actual); + public static PredicateAssert assumeThat(Predicate actual) { + return asAssumption(PredicateAssert.class, Predicate.class, actual); } /** @@ -1102,7 +1100,7 @@ public static OptionalLongAssert assumeThat(OptionalLong actual) { * @return the created assumption for assertion object. * @since 3.9.0 */ - public static AbstractZonedDateTimeAssert assumeThat(ZonedDateTime actual) { + public static ZonedDateTimeAssert assumeThat(ZonedDateTime actual) { return asAssumption(ZonedDateTimeAssert.class, ZonedDateTime.class, actual); } @@ -1113,7 +1111,7 @@ public static AbstractZonedDateTimeAssert assumeThat(ZonedDateTime actual) { * @return the created assumption for assertion object. * @since 3.9.0 */ - public static AbstractLocalDateTimeAssert assumeThat(LocalDateTime actual) { + public static LocalDateTimeAssert assumeThat(LocalDateTime actual) { return asAssumption(LocalDateTimeAssert.class, LocalDateTime.class, actual); } @@ -1124,7 +1122,7 @@ public static AbstractLocalDateTimeAssert assumeThat(LocalDateTime actual) { * @return the created assumption for assertion object. * @since 3.9.0 */ - public static AbstractOffsetDateTimeAssert assumeThat(OffsetDateTime actual) { + public static OffsetDateTimeAssert assumeThat(OffsetDateTime actual) { return asAssumption(OffsetDateTimeAssert.class, OffsetDateTime.class, actual); } @@ -1135,7 +1133,7 @@ public static AbstractOffsetDateTimeAssert assumeThat(OffsetDateTime actual) * @return the created assumption for assertion object. * @since 3.9.0 */ - public static AbstractOffsetTimeAssert assumeThat(OffsetTime actual) { + public static OffsetTimeAssert assumeThat(OffsetTime actual) { return asAssumption(OffsetTimeAssert.class, OffsetTime.class, actual); } @@ -1146,7 +1144,7 @@ public static AbstractOffsetTimeAssert assumeThat(OffsetTime actual) { * @return the created assumption for assertion object. * @since 3.9.0 */ - public static AbstractLocalTimeAssert assumeThat(LocalTime actual) { + public static LocalTimeAssert assumeThat(LocalTime actual) { return asAssumption(LocalTimeAssert.class, LocalTime.class, actual); } @@ -1157,7 +1155,7 @@ public static AbstractLocalTimeAssert assumeThat(LocalTime actual) { * @return the created assumption for assertion object. * @since 3.9.0 */ - public static AbstractLocalDateAssert assumeThat(LocalDate actual) { + public static LocalDateAssert assumeThat(LocalDate actual) { return asAssumption(LocalDateAssert.class, LocalDate.class, actual); } @@ -1168,7 +1166,7 @@ public static AbstractLocalDateAssert assumeThat(LocalDate actual) { * @return the created assumption for assertion object. * @since 3.9.0 */ - public static AbstractInstantAssert assumeThat(Instant actual) { + public static InstantAssert assumeThat(Instant actual) { return asAssumption(InstantAssert.class, Instant.class, actual); } @@ -1179,7 +1177,7 @@ public static AbstractInstantAssert assumeThat(Instant actual) { * @return the created assumption for assertion object. * @since 3.15.0 */ - public static AbstractDurationAssert assumeThat(Duration actual) { + public static DurationAssert assumeThat(Duration actual) { return asAssumption(DurationAssert.class, Duration.class, actual); } @@ -1190,7 +1188,7 @@ public static AbstractDurationAssert assumeThat(Duration actual) { * @return the created assumption for assertion object. * @since 3.17.0 */ - public static AbstractPeriodAssert assumeThat(Period actual) { + public static PeriodAssert assumeThat(Period actual) { return asAssumption(PeriodAssert.class, Period.class, actual); } @@ -1203,8 +1201,8 @@ public static AbstractPeriodAssert assumeThat(Period actual) { * @since 3.9.0 */ @SuppressWarnings("unchecked") - public static AbstractListAssert, ELEMENT, ObjectAssert> assumeThat(Stream actual) { - return asAssumption(ProxyableListAssert.class, Stream.class, actual); + public static ListAssert assumeThat(Stream actual) { + return asAssumption(ListAssert.class, Stream.class, actual); } /** @@ -1215,8 +1213,8 @@ public static AbstractListAssert, ELEMENT, * @since 3.9.0 */ @SuppressWarnings("unchecked") - public static AbstractListAssert, Double, ObjectAssert> assumeThat(DoubleStream actual) { - return asAssumption(ProxyableListAssert.class, DoubleStream.class, actual); + public static ListAssert assumeThat(DoubleStream actual) { + return asAssumption(ListAssert.class, DoubleStream.class, actual); } /** @@ -1227,8 +1225,8 @@ public static AbstractListAssert, Double, ObjectAssert * @since 3.9.0 */ @SuppressWarnings("unchecked") - public static AbstractListAssert, Long, ObjectAssert> assumeThat(LongStream actual) { - return asAssumption(ProxyableListAssert.class, LongStream.class, actual); + public static ListAssert assumeThat(LongStream actual) { + return asAssumption(ListAssert.class, LongStream.class, actual); } /** @@ -1239,8 +1237,8 @@ public static AbstractListAssert, Long, ObjectAssert, Integer, ObjectAssert> assumeThat(IntStream actual) { - return asAssumption(ProxyableListAssert.class, IntStream.class, actual); + public static ListAssert assumeThat(IntStream actual) { + return asAssumption(ListAssert.class, IntStream.class, actual); } /** @@ -1251,7 +1249,7 @@ public static AbstractListAssert, Integer, ObjectAsse * @return the created assumption for assertion object. */ @SuppressWarnings("unchecked") - public static AbstractSpliteratorAssert assumeThat(Spliterator actual) { + public static SpliteratorAssert assumeThat(Spliterator actual) { return asAssumption(SpliteratorAssert.class, Spliterator.class, actual); } @@ -1326,13 +1324,12 @@ private static RuntimeException assumptionNotMet(Class exceptionClass, // @format:off Object actual = assertion.actual; if (assertion instanceof StringAssert) return asAssumption(StringAssert.class, String.class, actual); - if (assertion instanceof FactoryBasedNavigableListAssert) return asAssumption(ProxyableListAssert.class, List.class, actual); - if (assertion instanceof ProxyableIterableAssert) return asAssumption(ProxyableIterableAssert.class, Iterable.class, actual); - if (assertion instanceof ProxyableMapAssert) return asAssumption(ProxyableMapAssert.class, Map.class, actual); - if (assertion instanceof AbstractObjectArrayAssert) return asAssumption(ProxyableObjectArrayAssert.class, Object[].class, actual); + if (assertion instanceof FactoryBasedNavigableListAssert) return asAssumption(ListAssert.class, List.class, actual); + if (assertion instanceof IterableAssert) return asAssumption(IterableAssert.class, Iterable.class, actual); + if (assertion instanceof MapAssert) return asAssumption(MapAssert.class, Map.class, actual); + if (assertion instanceof AbstractObjectArrayAssert) return asAssumption(ObjectArrayAssert.class, Object[].class, actual); if (assertion instanceof IterableSizeAssert) return asIterableSizeAssumption(assertion); if (assertion instanceof MapSizeAssert) return asMapSizeAssumption(assertion); - if (assertion instanceof ProxyableObjectAssert) return asAssumption(ObjectAssert.class, Object.class, actual); if (assertion instanceof ObjectAssert) return asAssumption(ObjectAssert.class, Object.class, actual); if (assertion instanceof RecursiveComparisonAssert) return asRecursiveComparisonAssumption(assertion); // @format:on diff --git a/src/main/java/org/assertj/core/api/AtomicLongArrayAssert.java b/src/main/java/org/assertj/core/api/AtomicLongArrayAssert.java index 89cd7a17936..ce7dd8a3b3e 100644 --- a/src/main/java/org/assertj/core/api/AtomicLongArrayAssert.java +++ b/src/main/java/org/assertj/core/api/AtomicLongArrayAssert.java @@ -90,7 +90,6 @@ public void isEmpty() { * @since 2.7.0 / 3.7.0 */ @Override - @CheckReturnValue public AtomicLongArrayAssert isNotEmpty() { arrays.assertNotEmpty(info, array); return myself; diff --git a/src/main/java/org/assertj/core/api/AtomicReferenceArrayAssert.java b/src/main/java/org/assertj/core/api/AtomicReferenceArrayAssert.java index 1c424b56990..7c56960d582 100644 --- a/src/main/java/org/assertj/core/api/AtomicReferenceArrayAssert.java +++ b/src/main/java/org/assertj/core/api/AtomicReferenceArrayAssert.java @@ -46,6 +46,7 @@ import org.assertj.core.api.filter.FilterOperator; import org.assertj.core.api.filter.Filters; import org.assertj.core.api.iterable.ThrowingExtractor; +import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration; import org.assertj.core.condition.Not; import org.assertj.core.data.Index; import org.assertj.core.description.Description; @@ -54,6 +55,7 @@ import org.assertj.core.internal.AtomicReferenceArrayElementComparisonStrategy; import org.assertj.core.internal.CommonErrors; import org.assertj.core.internal.ComparatorBasedComparisonStrategy; +import org.assertj.core.internal.ConfigurableRecursiveFieldByFieldComparator; import org.assertj.core.internal.ExtendedByTypesComparator; import org.assertj.core.internal.FieldByFieldComparator; import org.assertj.core.internal.IgnoringFieldsComparator; @@ -61,13 +63,14 @@ import org.assertj.core.internal.ObjectArrays; import org.assertj.core.internal.Objects; import org.assertj.core.internal.OnFieldsComparator; -import org.assertj.core.internal.RecursiveFieldByFieldComparator; import org.assertj.core.internal.TypeComparators; import org.assertj.core.presentation.PredicateDescription; import org.assertj.core.util.CheckReturnValue; import org.assertj.core.util.VisibleForTesting; import org.assertj.core.util.introspection.IntrospectionError; +// suppression of deprecation works in Eclipse to hide warning for the deprecated classes in the imports +@SuppressWarnings("deprecation") public class AtomicReferenceArrayAssert extends AbstractAssert, AtomicReferenceArray> implements IndexedObjectEnumerableAssert, T>, @@ -457,7 +460,15 @@ public AtomicReferenceArrayAssert hasSameSizeAs(Iterable other) { * @since 2.7.0 / 3.7.0 */ @Override - public AtomicReferenceArrayAssert contains(@SuppressWarnings("unchecked") T... values) { + @SafeVarargs + public final AtomicReferenceArrayAssert contains(T... values) { + return containsForProxy(values); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected AtomicReferenceArrayAssert containsForProxy(T[] values) { arrays.assertContains(info, array, values); return myself; } @@ -487,7 +498,15 @@ public AtomicReferenceArrayAssert contains(@SuppressWarnings("unchecked") T.. * @since 2.7.0 / 3.7.0 */ @Override - public AtomicReferenceArrayAssert containsOnly(@SuppressWarnings("unchecked") T... values) { + @SafeVarargs + public final AtomicReferenceArrayAssert containsOnly(T... values) { + return containsOnlyForProxy(values); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected AtomicReferenceArrayAssert containsOnlyForProxy(T[] values) { arrays.assertContainsOnly(info, array, values); return myself; } @@ -597,7 +616,15 @@ public AtomicReferenceArrayAssert hasSameElementsAs(Iterable ite * @since 2.7.0 / 3.7.0 */ @Override - public AtomicReferenceArrayAssert containsOnlyOnce(@SuppressWarnings("unchecked") T... values) { + @SafeVarargs + public final AtomicReferenceArrayAssert containsOnlyOnce(T... values) { + return containsOnlyOnceForProxy(values); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected AtomicReferenceArrayAssert containsOnlyOnceForProxy(T[] values) { arrays.assertContainsOnlyOnce(info, array, values); return myself; } @@ -632,7 +659,15 @@ public AtomicReferenceArrayAssert containsOnlyOnceElementsOf(Iterable containsExactly(@SuppressWarnings("unchecked") T... values) { + @SafeVarargs + public final AtomicReferenceArrayAssert containsExactly(T... values) { + return containsExactlyForProxy(values); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected AtomicReferenceArrayAssert containsExactlyForProxy(T[] values) { arrays.assertContainsExactly(info, array, values); return myself; } @@ -658,7 +693,15 @@ public AtomicReferenceArrayAssert containsExactly(@SuppressWarnings("unchecke * contains some or none of the given values, or more values than the given ones. */ @Override - public AtomicReferenceArrayAssert containsExactlyInAnyOrder(@SuppressWarnings("unchecked") T... values) { + @SafeVarargs + public final AtomicReferenceArrayAssert containsExactlyInAnyOrder(T... values) { + return containsExactlyInAnyOrderForProxy(values); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected AtomicReferenceArrayAssert containsExactlyInAnyOrderForProxy(T[] values) { arrays.assertContainsExactlyInAnyOrder(info, array, values); return myself; } @@ -735,7 +778,15 @@ public AtomicReferenceArrayAssert containsExactlyElementsOf(Iterable containsSequence(@SuppressWarnings("unchecked") T... sequence) { + @SafeVarargs + public final AtomicReferenceArrayAssert containsSequence(T... sequence) { + return containsSequenceForProxy(sequence); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected AtomicReferenceArrayAssert containsSequenceForProxy(T[] sequence) { arrays.assertContainsSequence(info, array, sequence); return myself; } @@ -792,7 +843,15 @@ public AtomicReferenceArrayAssert containsSequence(Iterable sequ * @throws AssertionError if the actual AtomicReferenceArray does not contain the given sequence. */ @Override - public AtomicReferenceArrayAssert doesNotContainSequence(@SuppressWarnings("unchecked") T... sequence) { + @SafeVarargs + public final AtomicReferenceArrayAssert doesNotContainSequence(T... sequence) { + return doesNotContainSequenceForProxy(sequence); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected AtomicReferenceArrayAssert doesNotContainSequenceForProxy(T[] sequence) { arrays.assertDoesNotContainSequence(info, array, sequence); return myself; } @@ -846,7 +905,15 @@ public AtomicReferenceArrayAssert doesNotContainSequence(Iterable containsSubsequence(@SuppressWarnings("unchecked") T... subsequence) { + @SafeVarargs + public final AtomicReferenceArrayAssert containsSubsequence(T... subsequence) { + return containsSubsequenceForProxy(subsequence); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected AtomicReferenceArrayAssert containsSubsequenceForProxy(T[] subsequence) { arrays.assertContainsSubsequence(info, array, subsequence); return myself; } @@ -898,7 +965,15 @@ public AtomicReferenceArrayAssert containsSubsequence(Iterable s * @throws AssertionError if the actual AtomicReferenceArray contains the given subsequence. */ @Override - public AtomicReferenceArrayAssert doesNotContainSubsequence(@SuppressWarnings("unchecked") T... subsequence) { + @SafeVarargs + public final AtomicReferenceArrayAssert doesNotContainSubsequence(T... subsequence) { + return doesNotContainSubsequenceForProxy(subsequence); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected AtomicReferenceArrayAssert doesNotContainSubsequenceForProxy(T[] subsequence) { arrays.assertDoesNotContainSubsequence(info, array, subsequence); return myself; } @@ -989,6 +1064,38 @@ public AtomicReferenceArrayAssert hasOnlyElementsOfTypes(Class... types) { return myself; } + /** + * Verifies that the actual elements are of the given types in the given order, there should be as many expected types as there are actual elements. + *

    + * Example: + *

     AtomicReferenceArray<Object> objects = new AtomicReferenceArray<>(new Object[] { 1, "a", 1.00 });
    +   *
    +   * // assertion succeeds
    +   * assertThat(objects).hasExactlyElementsOfTypes(Integer.class, String.class, String.class, Double.class);
    +   *
    +   * // assertions fail
    +   * // missing second String type
    +   * assertThat(objects).hasExactlyElementsOfTypes(Integer.class, String.class, Double.class);
    +   * // no Float type in actual
    +   * assertThat(objects).hasExactlyElementsOfTypes(Float.class, String.class, String.class, Double.class);
    +   * // correct types but wrong order
    +   * assertThat(objects).hasExactlyElementsOfTypes(String.class, Integer.class, String.class, Double.class);
    +   * // actual has more elements than the specified expected types
    +   * assertThat(objects).hasExactlyElementsOfTypes(String.class);
    + * + * @param expectedTypes the expected types + * @return {@code this} assertion object. + * @throws NullPointerException if the given type array is {@code null}. + * @throws AssertionError if actual is {@code null}. + * @throws AssertionError if the actual elements types don't exactly match the given ones (in the given order). + */ + @Override + public AtomicReferenceArrayAssert hasExactlyElementsOfTypes(Class... expectedTypes) { + arrays.assertHasExactlyElementsOfTypes(info, array, expectedTypes); + return myself; + } + + /** * Verifies that the actual AtomicReferenceArray does not contain the given object at the given index. *

    @@ -1040,7 +1147,15 @@ public AtomicReferenceArrayAssert doesNotContain(T value, Index index) { * @throws AssertionError if the actual AtomicReferenceArray contains any of the given values. */ @Override - public AtomicReferenceArrayAssert doesNotContain(@SuppressWarnings("unchecked") T... values) { + @SafeVarargs + public final AtomicReferenceArrayAssert doesNotContain(T... values) { + return doesNotContainForProxy(values); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected AtomicReferenceArrayAssert doesNotContainForProxy(T[] values) { arrays.assertDoesNotContain(info, array, values); return myself; } @@ -1116,7 +1231,15 @@ public AtomicReferenceArrayAssert doesNotHaveDuplicates() { * @throws AssertionError if the actual AtomicReferenceArray does not start with the given sequence of objects. */ @Override - public AtomicReferenceArrayAssert startsWith(@SuppressWarnings("unchecked") T... sequence) { + @SafeVarargs + public final AtomicReferenceArrayAssert startsWith(T... sequence) { + return startsWithForProxy(sequence); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected AtomicReferenceArrayAssert startsWithForProxy(T[] sequence) { arrays.assertStartsWith(info, array, sequence); return myself; } @@ -1143,7 +1266,15 @@ public AtomicReferenceArrayAssert startsWith(@SuppressWarnings("unchecked") T * @throws AssertionError if the actual AtomicReferenceArray does not end with the given sequence of objects. */ @Override - public AtomicReferenceArrayAssert endsWith(T first, @SuppressWarnings("unchecked") T... sequence) { + @SafeVarargs + public final AtomicReferenceArrayAssert endsWith(T first, T... sequence) { + return endsWithForProxy(first, sequence); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected AtomicReferenceArrayAssert endsWithForProxy(T first, T[] sequence) { arrays.assertEndsWith(info, array, first, sequence); return myself; } @@ -1220,7 +1351,15 @@ public AtomicReferenceArrayAssert isSubsetOf(Iterable values) { * @throws AssertionError if the actual {@code Iterable} is not subset of the given values. */ @Override - public AtomicReferenceArrayAssert isSubsetOf(@SuppressWarnings("unchecked") T... values) { + @SafeVarargs + public final AtomicReferenceArrayAssert isSubsetOf(T... values) { + return isSubsetOfForProxy(values); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected AtomicReferenceArrayAssert isSubsetOfForProxy(T[] values) { arrays.assertIsSubsetOf(info, array, Arrays.asList(values)); return myself; } @@ -1733,15 +1872,16 @@ public AtomicReferenceArrayAssert usingDefaultElementComparator() { } /** + * Deprecated javadoc + *

    * Allows to set a comparator to compare properties or fields of elements with the given names. * A typical usage is for comparing fields of numeric type at a given precision. *

    * To be used, comparators need to be specified by this method before calling any of: *

      - *
    • {@link #usingFieldByFieldElementComparator}
    • - *
    • {@link #usingElementComparatorOnFields}
    • - *
    • {@link #usingElementComparatorIgnoringFields}
    • - *
    • {@link #usingRecursiveFieldByFieldElementComparator}
    • + *
    • {@link #usingFieldByFieldElementComparator()}
    • + *
    • {@link #usingElementComparatorOnFields(String...)}
    • + *
    • {@link #usingElementComparatorIgnoringFields(String...)}
    • *
    *

    * Comparators specified by this method have precedence over comparators specified by @@ -1794,7 +1934,22 @@ public AtomicReferenceArrayAssert usingDefaultElementComparator() { * @param elementPropertyOrFieldNames the names of the properties and/or fields of the elements the comparator should be used for * @return {@code this} assertions object * @since 2.7.0 / 3.7.0 + * @deprecated This method is used with {@link #usingFieldByFieldElementComparator()} which is deprecated in favor of + * {@link #usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration)} or {@link #usingRecursiveComparison()}. + *

    + * When using {@link #usingRecursiveComparison()} the equivalent is: + *

      + *
    • {@link RecursiveComparisonAssert#withEqualsForFields(java.util.function.BiPredicate, String...)}
    • + *
    • {@link RecursiveComparisonAssert#withComparatorForFields(Comparator, String...)}
    • + *
    + *

    + * and when using {@link RecursiveComparisonConfiguration}: + *

      + *
    • {@link RecursiveComparisonConfiguration.Builder#withEqualsForFields(java.util.function.BiPredicate, String...)}
    • + *
    • {@link RecursiveComparisonConfiguration.Builder#withComparatorForFields(Comparator, String...)}
    • + *
    */ + @Deprecated @CheckReturnValue public AtomicReferenceArrayAssert usingComparatorForElementFieldsWithNames(Comparator comparator, String... elementPropertyOrFieldNames) { @@ -1805,15 +1960,16 @@ public AtomicReferenceArrayAssert usingComparatorForElementFieldsWithName } /** + * Deprecated javadoc + *

    * Allows to set a specific comparator to compare properties or fields of elements with the given type. * A typical usage is for comparing fields of numeric type at a given precision. *

    * To be used, comparators need to be specified by this method before calling any of: *

      - *
    • {@link #usingFieldByFieldElementComparator}
    • - *
    • {@link #usingElementComparatorOnFields}
    • - *
    • {@link #usingElementComparatorIgnoringFields}
    • - *
    • {@link #usingRecursiveFieldByFieldElementComparator}
    • + *
    • {@link #usingFieldByFieldElementComparator()}
    • + *
    • {@link #usingElementComparatorOnFields(String...)}
    • + *
    • {@link #usingElementComparatorIgnoringFields(String...)}
    • *
    *

    * Comparators specified by {@link #usingComparatorForElementFieldsWithNames(Comparator, String...) usingComparatorForElementFieldsWithNames} @@ -1873,7 +2029,22 @@ public AtomicReferenceArrayAssert usingComparatorForElementFieldsWithName * @param type the {@link java.lang.Class} of the type of the element fields the comparator should be used for * @return {@code this} assertions object * @since 2.7.0 / 3.7.0 + * @deprecated This method is used with {@link #usingFieldByFieldElementComparator()} which is deprecated in favor of + * {@link #usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration)} or {@link #usingRecursiveComparison()}. + *

    + * When using {@link #usingRecursiveComparison()} the equivalent is: + *

      + *
    • {@link RecursiveComparisonAssert#withEqualsForType(java.util.function.BiPredicate, Class)}
    • + *
    • {@link RecursiveComparisonAssert#withComparatorForType(Comparator, Class)}
    • + *
    + *

    + * and when using {@link RecursiveComparisonConfiguration}: + *

      + *
    • {@link RecursiveComparisonConfiguration.Builder#withEqualsForType(java.util.function.BiPredicate, Class)}
    • + *
    • {@link RecursiveComparisonConfiguration.Builder#withComparatorForType(Comparator, Class)}
    • + *
    */ + @Deprecated @CheckReturnValue public AtomicReferenceArrayAssert usingComparatorForElementFieldsWithType(Comparator comparator, Class type) { @@ -1888,10 +2059,9 @@ public AtomicReferenceArrayAssert usingComparatorForElementFieldsWithType *

    * Usage of this method affects comparators set by next methods: *

      - *
    • {@link #usingFieldByFieldElementComparator}
    • - *
    • {@link #usingElementComparatorOnFields}
    • - *
    • {@link #usingElementComparatorIgnoringFields}
    • - *
    • {@link #usingRecursiveFieldByFieldElementComparator}
    • + *
    • {@link #usingFieldByFieldElementComparator()}
    • + *
    • {@link #usingElementComparatorOnFields(String...)}
    • + *
    • {@link #usingElementComparatorIgnoringFields(String...)}
    • *
    *

    * Example: @@ -1920,6 +2090,8 @@ public AtomicReferenceArrayAssert usingComparatorForType(Comparator co } /** + * Deprecated javadoc + *

    * Use field/property by field/property comparison (including inherited fields/properties) instead of relying on * actual type A equals method to compare AtomicReferenceArray elements for incoming assertion checks. Private fields * are included but this can be disabled using {@link Assertions#setAllowExtractingPrivateFields(boolean)}. @@ -1945,7 +2117,12 @@ public AtomicReferenceArrayAssert usingComparatorForType(Comparator co * * @return {@code this} assertion object. * @since 2.7.0 / 3.7.0 + * @deprecated This method is deprecated because it performs a shallow field by field comparison, i.e. elements are compared + * field by field but the fields are compared with equals, use {@link #usingRecursiveFieldByFieldElementComparator()} + * or {@link #usingRecursiveComparison()} instead to perform a true recursive comparison. + *
    See https://assertj.github.io/doc/#assertj-core-recursive-comparison */ + @Deprecated @CheckReturnValue public AtomicReferenceArrayAssert usingFieldByFieldElementComparator() { return usingExtendedByTypesElementComparator(new FieldByFieldComparator(comparatorsForElementPropertyOrFieldNames, @@ -1953,55 +2130,176 @@ public AtomicReferenceArrayAssert usingFieldByFieldElementComparator() { } /** - * Use a recursive field/property by field/property comparison (including inherited fields/properties) - * instead of relying on actual type A equals method to compare AtomicReferenceArray elements for incoming - * assertion checks. This can be useful if actual's {@code equals} implementation does not suit you. + * Enable using a recursive field by field comparison strategy similar to {@link #usingRecursiveComparison()} but contrary to the latter you can chain any iterable assertions after this method (this is why this method exists). *

    - * The recursive property/field comparison is not applied on fields having a custom {@code equals} - * implementation, i.e. the overridden {@code equals} method will be used instead of a field/property by field/property comparison. + * This method uses the default {@link RecursiveComparisonConfiguration}, if you need to customize it use {@link #usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration)} instead. *

    - * You can specify a custom comparator per (nested) name or type of element field with - * {@link #usingComparatorForElementFieldsWithNames(Comparator, String...) usingComparatorForElementFieldsWithNames} - * and {@link #usingComparatorForElementFieldsWithType(Comparator, Class) usingComparatorForElementFieldsWithType}. + * Breaking change: since 3.20.0 the comparison won't use any comparators set with: + *

      + *
    • {@link #usingComparatorForType(Comparator, Class)}
    • + *
    • {@link #usingComparatorForElementFieldsWithType(Comparator, Class)}
    • + *
    • {@link #usingComparatorForElementFieldsWithNames(Comparator, String...)}
    • + *
    *

    - * The recursive comparison handles cycles. + * These features (and many more) are provided through {@link #usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration)} with a customized {@link RecursiveComparisonConfiguration} where there methods are called: + *

      + *
    • {@link RecursiveComparisonConfiguration#registerComparatorForType(Comparator, Class) registerComparatorForType(Comparator, Class)} / {@link RecursiveComparisonConfiguration.Builder#withComparatorForType(Comparator, Class) withComparatorForType(Comparator, Class)} (using {@link RecursiveComparisonConfiguration.Builder})
    • + *
    • {@link RecursiveComparisonConfiguration#registerEqualsForType(java.util.function.BiPredicate, Class) registerEqualsForType(BiPredicate, Class)} / {@link RecursiveComparisonConfiguration.Builder#withComparatorForType(Comparator, Class) withComparatorForType(Comparator, Class)} (using {@link RecursiveComparisonConfiguration.Builder})
    • + *
    • {@link RecursiveComparisonConfiguration#registerComparatorForFields(Comparator, String...) registerComparatorForFields(Comparator comparator, String... fields)} / {@link RecursiveComparisonConfiguration.Builder#withComparatorForFields(Comparator, String...) withComparatorForField(Comparator comparator, String... fields)} (using {@link RecursiveComparisonConfiguration.Builder})
    • + *
    *

    - * The objects to compare can be of different types but must have the same properties/fields. For example if actual object has a - * {@code name} String field, the other object must also have one. + * There are differences between this approach and {@link #usingRecursiveComparison()}: + *

      + *
    • contrary to {@link RecursiveComparisonAssert}, you can chain any iterable assertions after this method.
    • + *
    • no comparators registered with {@link AbstractIterableAssert#usingComparatorForType(Comparator, Class)} will be used, you need to register them in the configuration object.
    • + *
    • the assertion errors won't be as detailed as {@link RecursiveComparisonAssert#isEqualTo(Object)} which shows the field differences.
    • + *
    *

    - * If an object has a field and a property with the same name, the property value will be used over the field. + * This last point makes sense, take the {@link #contains(Object...)} assertion, it would not be relevant to report the differences of all the iterable's elements differing from the values to look for. *

    * Example: + *

     public class Person {
    +   *   String name;
    +   *   boolean hasPhd;
    +   * }
        *
    -   * 
     TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);
    -   * TolkienCharacter pippin = new TolkienCharacter("Pippin", 28, HOBBIT);
    -   * frodo.setFriend(pippin);
    -   * pippin.setFriend(frodo);
    +   * public class Doctor {
    +   *  String name;
    +   *  boolean hasPhd;
    +   * }
        *
    -   * TolkienCharacter frodoClone = new TolkienCharacter("Frodo", 33, HOBBIT);
    -   * TolkienCharacter pippinClone = new TolkienCharacter("Pippin", 28, HOBBIT);
    -   * frodoClone.setFriend(pippinClone);
    -   * pippinClone.setFriend(frodoClone);
    +   * Doctor drSheldon = new Doctor("Sheldon Cooper", true);
    +   * Doctor drLeonard = new Doctor("Leonard Hofstadter", true);
    +   * Doctor drRaj = new Doctor("Raj Koothrappali", true);
        *
    -   * AtomicReferenceArray<TolkienCharacter> hobbits = new AtomicReferenceArray<>(new TolkienCharacter[] {frodo, pippin});
    +   * Person sheldon = new Person("Sheldon Cooper", true);
    +   * Person leonard = new Person("Leonard Hofstadter", true);
    +   * Person raj = new Person("Raj Koothrappali", true);
    +   * Person howard = new Person("Howard Wolowitz", true);
        *
    -   * // fails if equals has not been overridden in TolkienCharacter as it would compares object references
    -   * assertThat(hobbits).contains(frodoClone, pippinClone);
    +   * AtomicReferenceArray<Doctor> doctors = new AtomicReferenceArray<>(array(drSheldon, drLeonard, drRaj));
    +   * AtomicReferenceArray<Person> persons = new AtomicReferenceArray<>(array(sheldon, leonard, raj));
        *
    -   * // frodo/frodoClone and pippin/pippinClone are equals when doing a recursive property/field by property/field comparison
    -   * assertThat(hobbits).usingRecursiveFieldByFieldElementComparator()
    -   *                    .contains(frodoClone, pippinClone);
    + * // assertion succeeds as both lists contains equivalent items in order. + * assertThat(doctors).usingRecursiveFieldByFieldElementComparator() + * .contains(sheldon); + * + * // assertion fails because leonard names are different. + * leonard.setName("Leonard Ofstater"); + * assertThat(doctors).usingRecursiveFieldByFieldElementComparator() + * .contains(leonard); + * + * // assertion fails because howard is missing and leonard is not expected. + * people = list(howard, sheldon, raj) + * assertThat(doctors).usingRecursiveFieldByFieldElementComparator() + * .contains(howard);
    + *

    + * Another point worth mentioning: elements order does matter if the expected iterable is ordered, for example comparing a {@code Set} to a {@code List} fails as {@code List} is ordered and {@code Set} is not.
    + * The ordering can be ignored by calling {@link RecursiveComparisonAssert#ignoringCollectionOrder ignoringCollectionOrder} allowing ordered/unordered iterable comparison, note that {@link RecursiveComparisonAssert#ignoringCollectionOrder ignoringCollectionOrder} is applied recursively on any nested iterable fields, if this behavior is too generic, + * use the more fine grained {@link RecursiveComparisonAssert#ignoringCollectionOrderInFields(String...) ignoringCollectionOrderInFields} or + * {@link RecursiveComparisonAssert#ignoringCollectionOrderInFieldsMatchingRegexes(String...) ignoringCollectionOrderInFieldsMatchingRegexes}. * * @return {@code this} assertion object. - * @since 2.7.0 / 3.7.0 + * @since 2.7.0 / 3.7.0 - breaking change in 3.20.0 + * @see RecursiveComparisonConfiguration + * @see usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration) */ @CheckReturnValue public AtomicReferenceArrayAssert usingRecursiveFieldByFieldElementComparator() { - return usingExtendedByTypesElementComparator(new RecursiveFieldByFieldComparator(comparatorsForElementPropertyOrFieldNames, - getComparatorsForElementPropertyOrFieldTypes())); + return usingRecursiveFieldByFieldElementComparator(new RecursiveComparisonConfiguration()); + } + + /** + * Enable using a recursive field by field comparison strategy similar to {@link #usingRecursiveComparison()} but contrary to the latter you can chain any iterable assertions after this method (this is why this method exists). + *

    + * The given {@link RecursiveComparisonConfiguration} is used to tweak the comparison behavior, for example by {@link RecursiveComparisonConfiguration#ignoreCollectionOrder(boolean) ignoring collection order}. + *

    + * Warning: the comparison won't use any comparators set with: + *

      + *
    • {@link #usingComparatorForType(Comparator, Class)}
    • + *
    • {@link #usingComparatorForElementFieldsWithType(Comparator, Class)}
    • + *
    • {@link #usingComparatorForElementFieldsWithNames(Comparator, String...)}
    • + *
    + *

    + * These features (and many more) are provided through {@link RecursiveComparisonConfiguration} with: + *

      + *
    • {@link RecursiveComparisonConfiguration#registerComparatorForType(Comparator, Class) registerComparatorForType(Comparator, Class)} / {@link RecursiveComparisonConfiguration.Builder#withComparatorForType(Comparator, Class) withComparatorForType(Comparator, Class)} (using {@link RecursiveComparisonConfiguration.Builder})
    • + *
    • {@link RecursiveComparisonConfiguration#registerEqualsForType(java.util.function.BiPredicate, Class) registerEqualsForType(BiPredicate, Class)} / {@link RecursiveComparisonConfiguration.Builder#withComparatorForType(Comparator, Class) withComparatorForType(Comparator, Class)} (using {@link RecursiveComparisonConfiguration.Builder})
    • + *
    • {@link RecursiveComparisonConfiguration#registerComparatorForFields(Comparator, String...) registerComparatorForFields(Comparator comparator, String... fields)} / {@link RecursiveComparisonConfiguration.Builder#withComparatorForFields(Comparator, String...) withComparatorForField(Comparator comparator, String... fields)} (using {@link RecursiveComparisonConfiguration.Builder})
    • + *
    + *

    + * RecursiveComparisonConfiguration exposes a {@link RecursiveComparisonConfiguration.Builder builder} to ease setting the comparison behaviour, + * call {@link RecursiveComparisonConfiguration#builder() RecursiveComparisonConfiguration.builder()} to start building your configuration. + *

    + * There are differences between this approach and {@link #usingRecursiveComparison()}: + *

      + *
    • contrary to {@link RecursiveComparisonAssert}, you can chain any iterable assertions after this method.
    • + *
    • no comparators registered with {@link AbstractIterableAssert#usingComparatorForType(Comparator, Class)} will be used, you need to register them in the configuration object.
    • + *
    • the assertion errors won't be as detailed as {@link RecursiveComparisonAssert#isEqualTo(Object)} which shows the field differences.
    • + *
    + *

    + * This last point makes sense, take the {@link #contains(Object...)} assertion, it would not be relevant to report the differences of all the iterable's elements differing from the values to look for. + *

    + * Example: + *

     public class Person {
    +   *   String name;
    +   *   boolean hasPhd;
    +   * }
    +   *
    +   * public class Doctor {
    +   *  String name;
    +   *  boolean hasPhd;
    +   * }
    +   *
    +   * Doctor drSheldon = new Doctor("Sheldon Cooper", true);
    +   * Doctor drLeonard = new Doctor("Leonard Hofstadter", true);
    +   * Doctor drRaj = new Doctor("Raj Koothrappali", true);
    +   *
    +   * Person sheldon = new Person("Sheldon Cooper", false);
    +   * Person leonard = new Person("Leonard Hofstadter", false);
    +   * Person raj = new Person("Raj Koothrappali", false);
    +   * Person howard = new Person("Howard Wolowitz", false);
    +   *
    +   * AtomicReferenceArray<Doctor> doctors = new AtomicReferenceArray<>(array(drSheldon, drLeonard, drRaj));
    +   * AtomicReferenceArray<Person> persons = new AtomicReferenceArray<>(array(sheldon, leonard, raj));
    +   *
    +   * RecursiveComparisonConfiguration configuration = RecursiveComparisonConfiguration.builder()
    +   *                                                                                  .withIgnoredFields​("hasPhd");
    +   *
    +   * // assertion succeeds as both lists contains equivalent items in order.
    +   * assertThat(doctors).usingRecursiveFieldByFieldElementComparator(configuration)
    +   *                    .contains(sheldon);
    +   *
    +   * // assertion fails because leonard names are different.
    +   * leonard.setName("Leonard Ofstater");
    +   * assertThat(doctors).usingRecursiveFieldByFieldElementComparator(configuration)
    +   *                    .contains(leonard);
    +   *
    +   * // assertion fails because howard is missing and leonard is not expected.
    +   * people = list(howard, sheldon, raj)
    +   * assertThat(doctors).usingRecursiveFieldByFieldElementComparator(configuration)
    +   *                    .contains(howard);
    + * + * A detailed documentation for the recursive comparison is available here: https://assertj.github.io/doc/#assertj-core-recursive-comparison. + *

    + * A point worth mentioning: elements order does matter if the expected iterable is ordered, for example comparing a {@code Set} to a {@code List} fails as {@code List} is ordered and {@code Set} is not.
    + * The ordering can be ignored by calling {@link RecursiveComparisonAssert#ignoringCollectionOrder ignoringCollectionOrder} allowing ordered/unordered iterable comparison, note that {@link RecursiveComparisonAssert#ignoringCollectionOrder ignoringCollectionOrder} is applied recursively on any nested iterable fields, if this behavior is too generic, + * use the more fine grained {@link RecursiveComparisonAssert#ignoringCollectionOrderInFields(String...) ignoringCollectionOrderInFields} or + * {@link RecursiveComparisonAssert#ignoringCollectionOrderInFieldsMatchingRegexes(String...) ignoringCollectionOrderInFieldsMatchingRegexes}. + * + * @param configuration the recursive comparison configuration. + * + * @return {@code this} assertion object. + * @since 3.20.0 + * @see RecursiveComparisonConfiguration + */ + public AtomicReferenceArrayAssert usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration configuration) { + return usingElementComparator(new ConfigurableRecursiveFieldByFieldComparator(configuration)); } /** + * Deprecated javadoc + *

    * Use field/property by field/property comparison on the given fields/properties only (including inherited * fields/properties) instead of relying on actual type A equals method to compare AtomicReferenceArray elements for * incoming assertion checks. Private fields are included but this can be disabled using @@ -2029,7 +2327,13 @@ public AtomicReferenceArrayAssert usingRecursiveFieldByFieldElementComparator * @param fields the fields to compare field/property by field/property. * @return {@code this} assertion object. * @since 2.7.0 / 3.7.0 + * @see #usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration) + * @see https://assertj.github.io/doc/#assertj-core-recursive-comparison + * @deprecated This method is deprecated because it performs a shallow field by field comparison, i.e. elements are + * compared field by field but the fields are compared with equals, use {@link #usingRecursiveFieldByFieldElementComparatorOnFields(String...)} instead. + *
    See https://assertj.github.io/doc/#assertj-core-recursive-comparison */ + @Deprecated @CheckReturnValue public AtomicReferenceArrayAssert usingElementComparatorOnFields(String... fields) { return usingExtendedByTypesElementComparator(new OnFieldsComparator(comparatorsForElementPropertyOrFieldNames, @@ -2037,6 +2341,57 @@ public AtomicReferenceArrayAssert usingElementComparatorOnFields(String... fi } /** + * The assertions chained after this method will use a recursive field by field comparison on the given fields (including + * inherited fields) instead of relying on the element equals method. + * This is handy when the element equals method is not overridden or implemented as you expect. + *

    + * Nested fields are supported and are expressed like: {@code name.first} + *

    + * The comparison is recursive: elements are compared field by field, if a field type has fields they are also compared + * field by field (and so on). + *

    + * Example: + *

     Player derrickRose = new Player(new Name("Derrick", "Rose"), "Chicago Bulls");
    +   * derrickRose.nickname = new Name("Crazy", "Dunks");
    +   *
    +   * Player jalenRose = new Player(new Name("Jalen", "Rose"), "Chicago Bulls");
    +   * jalenRose.nickname = new Name("Crazy", "Defense");
    +   *
    +   * // assertion succeeds as all compared fields match
    +   * assertThat(atomicArray(derrickRose)).usingRecursiveFieldByFieldElementComparatorOnFields("name.last", "team", "nickname.first")
    +   *                                     .contains(jalenRose);
    +   *
    +   * // assertion fails, name.first values differ
    +   * assertThat(atomicArray(derrickRose)).usingRecursiveFieldByFieldElementComparatorOnFields("name")
    +   *                                     .contains(jalenRose);
    + *

    + * This method is actually a shortcut of {@link #usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration)} + * with a configuration comparing only the given fields, the previous example can be written as: + *

     RecursiveComparisonConfiguration configuration = RecursiveComparisonConfiguration.builder()
    +   *                                                                                  .withComparedFields("name.last", "team", "nickname.first")
    +   *                                                                                  .build();
    +   *
    +   * assertThat(atomicArray(derrickRose)).usingRecursiveFieldByFieldElementComparator(configuration)
    +   *                                     .contains(jalenRose);
    + * The recursive comparison is documented here: https://assertj.github.io/doc/#assertj-core-recursive-comparison + *

    + * @param fields the field names to exclude in the elements comparison. + * @return {@code this} assertion object. + * @since 3.20.0 + * @see #usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration) + * @see https://assertj.github.io/doc/#assertj-core-recursive-comparison + */ + @CheckReturnValue + public AtomicReferenceArrayAssert usingRecursiveFieldByFieldElementComparatorOnFields(String... fields) { + RecursiveComparisonConfiguration recursiveComparisonConfiguration = RecursiveComparisonConfiguration.builder() + .withComparedFields(fields) + .build(); + return usingRecursiveFieldByFieldElementComparator(recursiveComparisonConfiguration); + } + + /** + * Deprecated javadoc + *

    * Use field/property by field/property on all fields/properties except the given ones (including inherited * fields/properties) instead of relying on actual type A equals method to compare AtomicReferenceArray elements for * incoming assertion checks. Private fields are included but this can be disabled using @@ -2064,7 +2419,13 @@ public AtomicReferenceArrayAssert usingElementComparatorOnFields(String... fi * @param fields the names of the fields/properties to ignore * @return {@code this} assertion object. * @since 2.7.0 / 3.7.0 + * @see #usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration) + * @see https://assertj.github.io/doc/#assertj-core-recursive-comparison + * @deprecated This method is deprecated because it performs a shallow field by field comparison, i.e. elements are + * compared field by field but the fields are compared with equals, use {@link #usingRecursiveFieldByFieldElementComparatorIgnoringFields(String...)} instead. + *
    See https://assertj.github.io/doc/#assertj-core-recursive-comparison */ + @Deprecated @CheckReturnValue public AtomicReferenceArrayAssert usingElementComparatorIgnoringFields(String... fields) { return usingExtendedByTypesElementComparator(new IgnoringFieldsComparator(comparatorsForElementPropertyOrFieldNames, @@ -2072,6 +2433,55 @@ public AtomicReferenceArrayAssert usingElementComparatorIgnoringFields(String fields)); } + /** + * The assertions chained after this method will use a recursive field by field comparison on all fields (including inherited + * fields) except the given ones instead of relying on the element equals method. + * This is handy when the element equals method is not overridden or implemented as you expect. + *

    + * Nested fields are supported and are expressed like: {@code name.first} + *

    + * The comparison is recursive: elements are compared field by field, if a field type has fields they are also compared + * field by field (and so on). + *

    + * Example: + *

     Player derrickRose = new Player(new Name("Derrick", "Rose"), "Chicago Bulls");
    +   * derrickRose.nickname = new Name("Crazy", "Dunks");
    +   *
    +   * Player jalenRose = new Player(new Name("Jalen", "Rose"), "Chicago Bulls");
    +   * jalenRose.nickname = new Name("Crazy", "Defense");
    +   *
    +   * // assertion succeeds
    +   * assertThat(atomicArray(derrickRose)).usingRecursiveFieldByFieldElementComparatorIgnoringFields("name.first", "nickname.last")
    +   *                                     .contains(jalenRose);
    +   *
    +   * // assertion fails, names are ignored but nicknames are not and nickname.last values differ
    +   * assertThat(atomicArray(derrickRose)).usingRecursiveFieldByFieldElementComparatorIgnoringFields("name")
    +   *                                     .contains(jalenRose);
    + *

    + * This method is actually a shortcut of {@link #usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration)} + * with a configuration ignoring the given fields, the previous example can be written as: + *

     RecursiveComparisonConfiguration configuration = RecursiveComparisonConfiguration.builder()
    +   *                                                                                  .withIgnoredFields("name.first", "nickname.last")
    +   *                                                                                  .build();
    +   *
    +   * assertThat(atomicArray(derrickRose)).usingRecursiveFieldByFieldElementComparator(configuration)
    +   *                                     .contains(jalenRose);
    + * The recursive comparison is documented here: https://assertj.github.io/doc/#assertj-core-recursive-comparison + *

    + * @param fields the field names to exclude in the elements comparison. + * @return {@code this} assertion object. + * @since 3.20.0 + * @see #usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration) + * @see https://assertj.github.io/doc/#assertj-core-recursive-comparison + */ + @CheckReturnValue + public AtomicReferenceArrayAssert usingRecursiveFieldByFieldElementComparatorIgnoringFields(String... fields) { + RecursiveComparisonConfiguration recursiveComparisonConfiguration = RecursiveComparisonConfiguration.builder() + .withIgnoredFields(fields) + .build(); + return usingRecursiveFieldByFieldElementComparator(recursiveComparisonConfiguration); + } + /** * Extract the values of given field or property from the array's elements under test into a new array, this new array * becoming the array under test. @@ -3057,13 +3467,29 @@ public AtomicReferenceArrayAssert noneSatisfy(Consumer restriction } @Override - public AtomicReferenceArrayAssert satisfiesExactly(@SuppressWarnings("unchecked") Consumer... requirements) { + @SafeVarargs + public final AtomicReferenceArrayAssert satisfiesExactly(Consumer... requirements) { + return satisfiesExactlyForProxy(requirements); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected AtomicReferenceArrayAssert satisfiesExactlyForProxy(Consumer[] requirements) { iterables.assertSatisfiesExactly(info, newArrayList(array), requirements); return myself; } @Override - public AtomicReferenceArrayAssert satisfiesExactlyInAnyOrder(@SuppressWarnings("unchecked") Consumer... consumers) { + @SafeVarargs + public final AtomicReferenceArrayAssert satisfiesExactlyInAnyOrder(Consumer... consumers) { + return satisfiesExactlyInAnyOrderForProxy(consumers); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected AtomicReferenceArrayAssert satisfiesExactlyInAnyOrderForProxy(Consumer[] consumers) { iterables.assertSatisfiesExactlyInAnyOrder(info, newArrayList(array), consumers); return myself; } @@ -3094,7 +3520,15 @@ public AtomicReferenceArrayAssert satisfiesExactlyInAnyOrder(@SuppressWarning * @since 2.9.0 / 3.9.0 */ @Override - public AtomicReferenceArrayAssert containsAnyOf(@SuppressWarnings("unchecked") T... values) { + @SafeVarargs + public final AtomicReferenceArrayAssert containsAnyOf(T... values) { + return containsAnyOfForProxy(values); + } + + // This method is protected in order to be proxied for SoftAssertions / Assumptions. + // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs + // in order to avoid compiler warning in user code + protected AtomicReferenceArrayAssert containsAnyOfForProxy(T[] values) { arrays.assertContainsAnyOf(info, array, values); return myself; } diff --git a/src/main/java/org/assertj/core/api/BDDAssertions.java b/src/main/java/org/assertj/core/api/BDDAssertions.java index 95949159912..c0deede8666 100644 --- a/src/main/java/org/assertj/core/api/BDDAssertions.java +++ b/src/main/java/org/assertj/core/api/BDDAssertions.java @@ -15,11 +15,14 @@ import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.io.UncheckedIOException; import java.math.BigDecimal; import java.math.BigInteger; import java.net.URI; import java.net.URL; +import java.nio.charset.Charset; import java.nio.file.Path; +import java.text.DateFormat; import java.time.Duration; import java.time.Instant; import java.time.LocalDate; @@ -29,6 +32,7 @@ import java.time.OffsetTime; import java.time.Period; import java.time.ZonedDateTime; +import java.time.temporal.TemporalUnit; import java.util.Date; import java.util.Iterator; import java.util.List; @@ -54,7 +58,9 @@ import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; import java.util.concurrent.atomic.AtomicStampedReference; import java.util.concurrent.atomic.LongAdder; +import java.util.function.Consumer; import java.util.function.DoublePredicate; +import java.util.function.Function; import java.util.function.IntPredicate; import java.util.function.LongPredicate; import java.util.function.Predicate; @@ -64,6 +70,28 @@ import java.util.stream.Stream; import org.assertj.core.api.ThrowableAssert.ThrowingCallable; +import org.assertj.core.api.filter.FilterOperator; +import org.assertj.core.api.filter.InFilter; +import org.assertj.core.api.filter.NotFilter; +import org.assertj.core.api.filter.NotInFilter; +import org.assertj.core.condition.AllOf; +import org.assertj.core.condition.AnyOf; +import org.assertj.core.condition.DoesNotHave; +import org.assertj.core.condition.Not; +import org.assertj.core.configuration.Configuration; +import org.assertj.core.data.Index; +import org.assertj.core.data.MapEntry; +import org.assertj.core.data.Offset; +import org.assertj.core.data.Percentage; +import org.assertj.core.data.TemporalUnitOffset; +import org.assertj.core.description.Description; +import org.assertj.core.groups.Properties; +import org.assertj.core.groups.Tuple; +import org.assertj.core.presentation.BinaryRepresentation; +import org.assertj.core.presentation.HexadecimalRepresentation; +import org.assertj.core.presentation.Representation; +import org.assertj.core.presentation.StandardRepresentation; +import org.assertj.core.presentation.UnicodeRepresentation; import org.assertj.core.util.CanIgnoreReturnValue; import org.assertj.core.util.CheckReturnValue; @@ -253,7 +281,7 @@ public static OptionalDoubleAssert then(OptionalDouble optional) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractBigDecimalAssert then(BigDecimal actual) { + public static BigDecimalAssert then(BigDecimal actual) { return assertThat(actual); } @@ -264,7 +292,7 @@ public static AbstractBigDecimalAssert then(BigDecimal actual) { * @return the created assertion object. * @since 2.7.0 / 3.7.0 */ - public static AbstractBigIntegerAssert then(BigInteger actual) { + public static BigIntegerAssert then(BigInteger actual) { return assertThat(actual); } @@ -274,7 +302,7 @@ public static AbstractBigIntegerAssert then(BigInteger actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractBooleanAssert then(boolean actual) { + public static BooleanAssert then(boolean actual) { return assertThat(actual); } @@ -284,7 +312,7 @@ public static AbstractBooleanAssert then(boolean actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractBooleanAssert then(Boolean actual) { + public static BooleanAssert then(Boolean actual) { return assertThat(actual); } @@ -294,7 +322,7 @@ public static AbstractBooleanAssert then(Boolean actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractBooleanArrayAssert then(boolean[] actual) { + public static BooleanArrayAssert then(boolean[] actual) { return assertThat(actual); } @@ -315,7 +343,7 @@ public static Boolean2DArrayAssert then(boolean[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractByteAssert then(byte actual) { + public static ByteAssert then(byte actual) { return assertThat(actual); } @@ -325,7 +353,7 @@ public static AbstractByteAssert then(byte actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractByteAssert then(Byte actual) { + public static ByteAssert then(Byte actual) { return assertThat(actual); } @@ -335,7 +363,7 @@ public static AbstractByteAssert then(Byte actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractByteArrayAssert then(byte[] actual) { + public static ByteArrayAssert then(byte[] actual) { return assertThat(actual); } @@ -356,7 +384,7 @@ public static Byte2DArrayAssert then(byte[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractCharacterAssert then(char actual) { + public static CharacterAssert then(char actual) { return assertThat(actual); } @@ -366,7 +394,7 @@ public static AbstractCharacterAssert then(char actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractCharArrayAssert then(char[] actual) { + public static CharArrayAssert then(char[] actual) { return assertThat(actual); } @@ -387,7 +415,7 @@ public static Char2DArrayAssert then(char[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractCharacterAssert then(Character actual) { + public static CharacterAssert then(Character actual) { return assertThat(actual); } @@ -409,7 +437,7 @@ public static ClassAssert then(Class actual) { * @param actual the actual value. * @return the created assertion object. */ - public static > AbstractComparableAssert then(T actual) { + public static > GenericComparableAssert then(T actual) { return assertThat(actual); } @@ -453,9 +481,10 @@ public static IteratorAssert then(Iterator actual) { * in order to perform assertions on it. *

    * Navigational methods provided:

      - *
    • {@link AbstractIterableAssert#first() first()}
    • - *
    • {@link AbstractIterableAssert#last() last()}
    • - *
    • {@link AbstractIterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#first() first()}
    • + *
    • {@link IterableAssert#last() last()}
    • + *
    • {@link IterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#elements(int...) element(int...)}
    • *
    *

    * The available assertions after navigating to an element depend on the {@code ELEMENT_ASSERT} parameter of the given @@ -496,9 +525,10 @@ FactoryBasedNavigableIterableAssert then(Ite * in order to perform assertions on it. *

    * Navigational methods provided:

      - *
    • {@link AbstractIterableAssert#first() first()}
    • - *
    • {@link AbstractIterableAssert#last() last()}
    • - *
    • {@link AbstractIterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#first() first()}
    • + *
    • {@link IterableAssert#last() last()}
    • + *
    • {@link IterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#elements(int...) element(int...)}
    • *
    *

    * The available assertions after navigating to an element depend on the given {@code assertClass} @@ -530,9 +560,10 @@ ClassBasedNavigableIterableAssert then(ACTUA * in order to perform assertions on it. *

    * Navigational methods provided:

      - *
    • {@link AbstractIterableAssert#first() first()}
    • - *
    • {@link AbstractIterableAssert#last() last()}
    • - *
    • {@link AbstractIterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#first() first()}
    • + *
    • {@link IterableAssert#last() last()}
    • + *
    • {@link IterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#elements(int...) element(int...)}
    • *
    *

    * The available assertions after navigating to an element depend on the {@code ELEMENT_ASSERT} parameter of the given @@ -572,9 +603,10 @@ FactoryBasedNavigableListAssert then(List * Navigational methods provided:

      - *
    • {@link AbstractIterableAssert#first() first()}
    • - *
    • {@link AbstractIterableAssert#last() last()}
    • - *
    • {@link AbstractIterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#first() first()}
    • + *
    • {@link IterableAssert#last() last()}
    • + *
    • {@link IterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#elements(int...) element(int...)}
    • *
    *

    * The available assertions after navigating to an element depend on the given {@code assertClass} @@ -609,7 +641,7 @@ ClassBasedNavigableListAssert then(List then(double actual) { + public static DoubleAssert then(double actual) { return assertThat(actual); } @@ -619,7 +651,7 @@ public static AbstractDoubleAssert then(double actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractDoubleAssert then(Double actual) { + public static DoubleAssert then(Double actual) { return assertThat(actual); } @@ -629,7 +661,7 @@ public static AbstractDoubleAssert then(Double actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractDoubleArrayAssert then(double[] actual) { + public static DoubleArrayAssert then(double[] actual) { return assertThat(actual); } @@ -650,7 +682,7 @@ public static Double2DArrayAssert then(double[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractFileAssert then(File actual) { + public static FileAssert then(File actual) { return assertThat(actual); } @@ -660,7 +692,7 @@ public static AbstractFileAssert then(File actual) { * @param actual the path to test * @return the created assertion object */ - public static AbstractPathAssert then(Path actual) { + public static PathAssert then(Path actual) { return assertThat(actual); } @@ -682,7 +714,7 @@ public static FutureAssert then(Future actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractInputStreamAssert then(InputStream actual) { + public static InputStreamAssert then(InputStream actual) { return assertThat(actual); } @@ -692,7 +724,7 @@ public static FutureAssert then(Future actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractFloatAssert then(float actual) { + public static FloatAssert then(float actual) { return assertThat(actual); } @@ -702,7 +734,7 @@ public static AbstractFloatAssert then(float actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractFloatAssert then(Float actual) { + public static FloatAssert then(Float actual) { return assertThat(actual); } @@ -712,7 +744,7 @@ public static AbstractFloatAssert then(Float actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractFloatArrayAssert then(float[] actual) { + public static FloatArrayAssert then(float[] actual) { return assertThat(actual); } @@ -733,7 +765,7 @@ public static Float2DArrayAssert then(float[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractIntegerAssert then(int actual) { + public static IntegerAssert then(int actual) { return assertThat(actual); } @@ -743,7 +775,7 @@ public static AbstractIntegerAssert then(int actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractIntArrayAssert then(int[] actual) { + public static IntArrayAssert then(int[] actual) { return assertThat(actual); } @@ -764,7 +796,7 @@ public static Int2DArrayAssert then(int[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractIntegerAssert then(Integer actual) { + public static IntegerAssert then(Integer actual) { return assertThat(actual); } @@ -785,7 +817,7 @@ public static ListAssert then(List actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractLongAssert then(long actual) { + public static LongAssert then(long actual) { return assertThat(actual); } @@ -795,7 +827,7 @@ public static AbstractLongAssert then(long actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractLongAssert then(Long actual) { + public static LongAssert then(Long actual) { return assertThat(actual); } @@ -805,7 +837,7 @@ public static AbstractLongAssert then(Long actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractLongArrayAssert then(long[] actual) { + public static LongArrayAssert then(long[] actual) { return assertThat(actual); } @@ -872,7 +904,7 @@ public static MapAssert then(Map actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractShortAssert then(short actual) { + public static ShortAssert then(short actual) { return assertThat(actual); } @@ -882,7 +914,7 @@ public static AbstractShortAssert then(short actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractShortAssert then(Short actual) { + public static ShortAssert then(Short actual) { return assertThat(actual); } @@ -892,7 +924,7 @@ public static AbstractShortAssert then(Short actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractShortArrayAssert then(short[] actual) { + public static ShortArrayAssert then(short[] actual) { return assertThat(actual); } @@ -913,7 +945,7 @@ public static Short2DArrayAssert then(short[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractCharSequenceAssert then(CharSequence actual) { + public static CharSequenceAssert then(CharSequence actual) { return assertThat(actual); } @@ -924,7 +956,7 @@ public static Short2DArrayAssert then(short[][] actual) { * @return the created assertion object. * @since 3.11.0 */ - public static AbstractCharSequenceAssert then(StringBuilder actual) { + public static CharSequenceAssert then(StringBuilder actual) { return assertThat(actual); } @@ -935,7 +967,7 @@ public static Short2DArrayAssert then(short[][] actual) { * @return the created assertion object. * @since 3.11.0 */ - public static AbstractCharSequenceAssert then(StringBuffer actual) { + public static CharSequenceAssert then(StringBuffer actual) { return assertThat(actual); } @@ -945,7 +977,7 @@ public static Short2DArrayAssert then(short[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractStringAssert then(String actual) { + public static StringAssert then(String actual) { return assertThat(actual); } @@ -955,7 +987,7 @@ public static AbstractStringAssert then(String actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractDateAssert then(Date actual) { + public static DateAssert then(Date actual) { return assertThat(actual); } @@ -1116,7 +1148,7 @@ public static AtomicStampedReferenceAssert then(AtomicStampedRefe * @param actual the actual value. * @return the created assertion Throwable. */ - public static AbstractThrowableAssert then(Throwable actual) { + public static ThrowableAssert then(Throwable actual) { return assertThat(actual); } @@ -1149,7 +1181,7 @@ public static AtomicStampedReferenceAssert then(AtomicStampedRefe * @return the created {@link ThrowableAssert}. */ @CanIgnoreReturnValue - public static AbstractThrowableAssert thenThrownBy(ThrowingCallable shouldRaiseThrowable) { + public static ThrowableAssert thenThrownBy(ThrowingCallable shouldRaiseThrowable) { return assertThat(catchThrowable(shouldRaiseThrowable)).hasBeenThrown(); } @@ -1185,7 +1217,7 @@ public static AtomicStampedReferenceAssert then(AtomicStampedRefe * @since 3.9.0 */ @CanIgnoreReturnValue - public static AbstractThrowableAssert thenThrownBy(ThrowingCallable shouldRaiseThrowable, + public static ThrowableAssert thenThrownBy(ThrowingCallable shouldRaiseThrowable, String description, Object... args) { return assertThat(catchThrowable(shouldRaiseThrowable)).as(description, args).hasBeenThrown(); } @@ -1231,7 +1263,7 @@ public static AtomicStampedReferenceAssert then(AtomicStampedRefe * @return The captured exception or null if none was raised by the callable. * @since 3.7.0 */ - public static AbstractThrowableAssert thenCode(ThrowingCallable shouldRaiseOrNotThrowable) { + public static ThrowableAssert thenCode(ThrowingCallable shouldRaiseOrNotThrowable) { return assertThat(catchThrowable(shouldRaiseOrNotThrowable)); } @@ -1256,13 +1288,40 @@ public static ObjectAssert thenObject(T actual) { return then(actual); } + /** + * Uses the given instance as the instance under test for all the assertions expressed as the passed {@link Consumer}. + *

    + * This is useful to avoid repeating getting the instance to test, a bit like a with block which turns the target into + * the equivalent of {@code this} (as in Groovy for example). + *

    + * Example: + *

     thenWith(team.getPlayers().get(0).getStats(),
    +   *            stats -> {
    +   *               assertThat(stats.pointPerGame).isGreaterThan(25.7);
    +   *               assertThat(stats.assistsPerGame).isGreaterThan(7.2);
    +   *               assertThat(stats.reboundsPerGame).isBetween(9, 12);
    +   *            });
    + *

    + * {@code assertWith} is variation of {@link AbstractAssert#satisfies(Consumer)} hopefully easier to find for some users. + * + * @param the type of the actual value. + * @param actual the actual value. + * @param requirements to assert on the actual object - must not be null. + * @return the created assertion object. + * @since 3.20.0 + */ + @CanIgnoreReturnValue + public static ObjectAssert thenWith(T actual, Consumer requirements) { + return then(actual).satisfies(requirements); + } + /** * Creates a new instance of {@link org.assertj.core.api.LocalDateAssert}. * * @param actual the actual value. * @return the created assertion object. */ - public static AbstractLocalDateAssert then(LocalDate actual) { + public static LocalDateAssert then(LocalDate actual) { return assertThat(actual); } @@ -1272,7 +1331,7 @@ public static AbstractLocalDateAssert then(LocalDate actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractLocalDateTimeAssert then(LocalDateTime actual) { + public static LocalDateTimeAssert then(LocalDateTime actual) { return assertThat(actual); } @@ -1282,7 +1341,7 @@ public static AbstractLocalDateTimeAssert then(LocalDateTime actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractZonedDateTimeAssert then(ZonedDateTime actual) { + public static ZonedDateTimeAssert then(ZonedDateTime actual) { return assertThat(actual); } @@ -1292,7 +1351,7 @@ public static AbstractZonedDateTimeAssert then(ZonedDateTime actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractLocalTimeAssert then(LocalTime actual) { + public static LocalTimeAssert then(LocalTime actual) { return assertThat(actual); } @@ -1302,7 +1361,7 @@ public static AbstractLocalTimeAssert then(LocalTime actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractOffsetTimeAssert then(OffsetTime actual) { + public static OffsetTimeAssert then(OffsetTime actual) { return assertThat(actual); } @@ -1313,7 +1372,7 @@ public static AbstractOffsetTimeAssert then(OffsetTime actual) { * @return the created assertion object. * @since 3.7.0 */ - public static AbstractInstantAssert then(Instant actual) { + public static InstantAssert then(Instant actual) { return assertThat(actual); } @@ -1324,7 +1383,7 @@ public static AbstractInstantAssert then(Instant actual) { * @return the created assertion object. * @since 3.15.0 */ - public static AbstractDurationAssert then(Duration actual) { + public static DurationAssert then(Duration actual) { return assertThat(actual); } @@ -1335,7 +1394,7 @@ public static AbstractDurationAssert then(Duration actual) { * @return the created assertion object. * @since 3.17.0 */ - public static AbstractPeriodAssert then(Period actual) { + public static PeriodAssert then(Period actual) { return assertThat(actual); } @@ -1345,7 +1404,7 @@ public static AbstractPeriodAssert then(Period actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractUriAssert then(URI actual) { + public static UriAssert then(URI actual) { return assertThat(actual); } @@ -1355,7 +1414,7 @@ public static AbstractUriAssert then(URI actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractUrlAssert then(URL actual) { + public static UrlAssert then(URL actual) { return assertThat(actual); } @@ -1365,7 +1424,7 @@ public static AbstractUrlAssert then(URL actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractOffsetDateTimeAssert then(OffsetDateTime actual) { + public static OffsetDateTimeAssert then(OffsetDateTime actual) { return assertThat(actual); } @@ -1602,6 +1661,78 @@ public static SpliteratorAssert then(Spliterator act return assertThat(actual); } + /** + * Allows catching a {@link Throwable} more easily when used with Java 8 lambdas. + *

    + * This caught {@link Throwable} can then be asserted. + *

    + * If you need to assert on the real type of Throwable caught (e.g. IOException), use {@link #catchThrowableOfType(ThrowableAssert.ThrowingCallable, Class)}. + *

    + * Example: + *

    {@literal @}Test
    +   * public void testException() {
    +   *   // when
    +   *   Throwable thrown = catchThrowable(() -> { throw new Exception("boom!"); });
    +   *
    +   *   // then
    +   *   assertThat(thrown).isInstanceOf(Exception.class)
    +   *                     .hasMessageContaining("boom");
    +   * } 
    + * + * @param shouldRaiseThrowable The lambda with the code that should raise the exception. + * @return The captured exception or null if none was raised by the callable. + * @see #catchThrowableOfType(ThrowableAssert.ThrowingCallable, Class) + * + * @since 3.20.0 + */ + public static Throwable catchThrowable(ThrowingCallable shouldRaiseThrowable) { + return AssertionsForClassTypes.catchThrowable(shouldRaiseThrowable); + } + + /** + * Allows catching a {@link Throwable} of a specific type. + *

    + * A call is made to {@code catchThrowable(ThrowingCallable)}, if no exception is thrown it returns null + * otherwise it checks that the caught {@link Throwable} has the specified type and casts it making it convenient to perform subtype-specific assertions on it. + *

    + * Example: + *

     class TextException extends Exception {
    +   *   int line;
    +   *   int column;
    +   *
    +   *   public TextException(String msg, int line, int column) {
    +   *     super(msg);
    +   *     this.line = line;
    +   *     this.column = column;
    +   *   }
    +   * }
    +   *
    +   * TextException textException = catchThrowableOfType(() -> { throw new TextException("boom!", 1, 5); },
    +   *                                                    TextException.class);
    +   * // assertions succeed
    +   * assertThat(textException).hasMessage("boom!");
    +   * assertThat(textException.line).isEqualTo(1);
    +   * assertThat(textException.column).isEqualTo(5);
    +   *
    +   * // succeeds as catchThrowableOfType returns null when the code does not thrown any exceptions
    +   * assertThat(catchThrowableOfType(() -> {}, Exception.class)).isNull();
    +   *
    +   * // fails as TextException is not a RuntimeException
    +   * catchThrowableOfType(() -> { throw new TextException("boom!", 1, 5); }, RuntimeException.class);
    + * + * @param the {@link Throwable} type. + * @param shouldRaiseThrowable The lambda with the code that should raise the exception. + * @param type The type of exception that the code is expected to raise. + * @return The captured exception or null if none was raised by the callable. + * @see #catchThrowable(ThrowableAssert.ThrowingCallable) + * + * @since 3.20.0 + */ + public static THROWABLE catchThrowableOfType(ThrowingCallable shouldRaiseThrowable, + Class type) { + return AssertionsForClassTypes.catchThrowableOfType(shouldRaiseThrowable, type); + } + /** * Entry point to check that an exception of type T is thrown by a given {@code throwingCallable} * which allows to chain assertions on the thrown exception. @@ -1672,4 +1803,1485 @@ public static ThrowableTypeAssert thenIllegalStateExcepti return assertThatIllegalStateException(); } + // ------------------------------------------------------------------------------------------------- + // fail methods : not assertions but here to have a single entry point to all AssertJ features. + // ------------------------------------------------------------------------------------------------- + + /** + * Sets whether we remove elements related to AssertJ from assertion error stack trace. + *

    + * Default is {@value org.assertj.core.configuration.Configuration#REMOVE_ASSERTJ_RELATED_ELEMENTS_FROM_STACK_TRACE}. + * + * @param removeAssertJRelatedElementsFromStackTrace flag. + * + * @since 3.20.0 + */ + public static void setRemoveAssertJRelatedElementsFromStackTrace(boolean removeAssertJRelatedElementsFromStackTrace) { + Assertions.setRemoveAssertJRelatedElementsFromStackTrace(removeAssertJRelatedElementsFromStackTrace); + } + + /** + * Throws an {@link AssertionError} with the given message. + * + * @param dummy return value type + * @param failureMessage error message. + * @return nothing, it's just to be used in {@code doSomething(optional.orElse(() -> fail("boom")));}. + * @throws AssertionError with the given message. + * + * @since 3.20.0 + */ + @CanIgnoreReturnValue + public static T fail(String failureMessage) { + return Assertions.fail(failureMessage); + } + + /** + * Throws an {@link AssertionError} with the given message built as {@link String#format(String, Object...)}. + * + * @param dummy return value type + * @param failureMessage error message. + * @param args Arguments referenced by the format specifiers in the format string. + * @return nothing, it's just to be used in doSomething(optional.orElse(() -> fail("b%s", ""oom)));. + * @throws AssertionError with the given built message. + * + * @since 3.20.0 + */ + @CanIgnoreReturnValue + public static T fail(String failureMessage, Object... args) { + return Assertions.fail(failureMessage, args); + } + + /** + * Throws an {@link AssertionError} with the given message and with the {@link Throwable} that caused the failure. + * @param dummy return value type + * @param failureMessage the description of the failed assertion. It can be {@code null}. + * @param realCause cause of the error. + * @return nothing, it's just to be used in doSomething(optional.orElse(() -> fail("boom", cause)));. + * @throws AssertionError with the given message and with the {@link Throwable} that caused the failure. + * + * @since 3.20.0 + */ + @CanIgnoreReturnValue + public static T fail(String failureMessage, Throwable realCause) { + return Assertions.fail(failureMessage, realCause); + } + + /** + * Throws an {@link AssertionError} with a message explaining that a {@link Throwable} of given class was expected to be thrown + * but had not been. + * @param dummy return value type + * @param throwableClass the Throwable class that was expected to be thrown. + * @return nothing, it's just to be used in doSomething(optional.orElse(() -> shouldHaveThrown(IOException.class)));. + * @throws AssertionError with a message explaining that a {@link Throwable} of given class was expected to be thrown but had + * not been. + * + * @since 3.20.0 + */ + @CanIgnoreReturnValue + public static T shouldHaveThrown(Class throwableClass) { + return Assertions.shouldHaveThrown(throwableClass); + } + + /** + * In error messages, sets the threshold when iterable/array formatting will be on one line (if their String description + * length <= this parameter) or it will be formatted with one element per line. + *

    + * The default value for maxLengthForSingleLineDescription is {@value Configuration#MAX_LENGTH_FOR_SINGLE_LINE_DESCRIPTION}. + *

    + * The following array will be formatted on one line as its length <= 80: + *

     String[] greatBooks = array("A Game of Thrones", "The Lord of the Rings", "Assassin's Apprentice");
    +   * // formatted as:
    +   * ["A Game of Thrones", "The Lord of the Rings", "Assassin's Apprentice"]
    + * whereas this array is formatted on multiple lines (one element per line) + * + *
     String[] greatBooks = array("A Game of Thrones", "The Lord of the Rings", "Assassin's Apprentice", "Guards! Guards! (Discworld)");
    +   * // formatted as:
    +   * ["A Game of Thrones",
    +   *  "The Lord of the Rings",
    +   *  "Assassin's Apprentice",
    +   *  "Guards! Guards! (Discworld)"]
    + * + * @param maxLengthForSingleLineDescription the maximum length for an iterable/array to be displayed on one line + * + * @since 3.20.0 + */ + public static void setMaxLengthForSingleLineDescription(int maxLengthForSingleLineDescription) { + Assertions.setMaxLengthForSingleLineDescription(maxLengthForSingleLineDescription); + } + + /** + * Sets the maximum number of elements to display in error messages for iterables, arrays and map . + *

    + * Example with a value of {@code 4}. + *

    + * The following array will be formatted entirely as it's length is <= 4: + *

     String[] greatBooks = array("A Game of Thrones", "The Lord of the Rings", "Assassin's Apprentice");
    +   * // formatted as:
    +   * ["A Game of Thrones", "The Lord of the Rings", "Assassin's Apprentice"]
    + * + * whereas for this 6 elements array, only the first and last two elements are displayed (4 in total): + *
     String[] greatBooks = array("A Game of Thrones", "The Lord of the Rings", "Assassin's Apprentice", "Guards! Guards!", "The Lies of Locke Lamora", "Aux Ombres d’Abyme");
    +   * // formatted as:
    +   * ["A Game of Thrones", "The Lord of the Rings", ... "The Lies of Locke Lamora", "Aux Ombres d’Abyme"]
    + * + * @param maxElementsForPrinting the maximum elements that would be printed for iterables, arrays and maps. + * + * @since 3.20.0 + */ + public static void setMaxElementsForPrinting(int maxElementsForPrinting) { + Assertions.setMaxElementsForPrinting(maxElementsForPrinting); + } + + /** + * Enable/disable printing assertions description to the console (disabled by default). + *

    + * The printed assertions description include all the successful assertions description and respectively the first failed one for standard assertions and all failed ones for soft assertions. + *

    + * If you want to process the description differently, create a {@link Consumer Consumer<Description>} and register it with {@link #setDescriptionConsumer(Consumer)}. + * + * @param printAssertionsDescription whether to print assertions description. + * + * @since 3.20.0 + */ + public static void setPrintAssertionsDescription(boolean printAssertionsDescription) { + Assertions.setPrintAssertionsDescription(printAssertionsDescription); + } + + /** + * All assertions description will be consumed by the given {@link Consumer Consumer<Description>} allowing for example to record them in a file. + *

    + * The consumed descriptions include all the successful assertions description and respectively the first failed one for standard assertions and all failed ones for soft assertions. + *

    + * To unset the descriptionConsumer, call {@code setDescriptionConsumer(null);} + * + * @param descriptionConsumer the {@link Description} consumer + * + * @since 3.20.0 + */ + public static void setDescriptionConsumer(Consumer descriptionConsumer) { + Assertions.setDescriptionConsumer(descriptionConsumer); + } + + /** + * Sets how many stacktrace elements are included in {@link Throwable} representation (by default this set to 3). + *

    + * Examples: + *

      static class Test1 {
    +   *
    +   *   static void boom() {
    +   *     Test2.boom2();
    +   *   }
    +   *
    +   *   static class Test2 {
    +   *     static void boom2() {
    +   *       throw new RuntimeException();
    +   *     }
    +   *   }
    +   * }
    + * + * {@code Test1.boom()} exception should be represented like this in error messages: + *
     java.lang.RuntimeException
    +   *  at org.assertj.core.presentation.Test1$Test2.boom2(StandardRepresentation_throwable_format_Test.java:35)
    +   *  at org.assertj.core.presentation.Test1.boom(StandardRepresentation_throwable_format_Test.java:40);java.lang.RuntimeException
    +   *  at org.assertj.core.presentation.Test1.lambda$1(StandardRepresentation_throwable_format_Test.java:63)org.assertj.core.util.Throwables_Description_Test$test1$test2.exception_layer_2(Throwables_Description_Test.java:24)
    +   *  ...(69 remaining lines not displayed - this can be changed with Assertions.setMaxStackTraceElementsDisplayed)org.assertj.core.util.Throwables_Description_Test$test1.exception_layer_1(Throwables_Description_Test.java:30)
    + * + * @param maxStackTraceElementsDisplayed the maximum number of lines for a stacktrace to be displayed on one throw. + * @see Configuration + * + * @since 3.20.0 + */ + public static void setMaxStackTraceElementsDisplayed(int maxStackTraceElementsDisplayed) { + Assertions.setMaxStackTraceElementsDisplayed(maxStackTraceElementsDisplayed); + } + + // ------------------------------------------------------------------------------------------------------ + // properties methods : not assertions but here to have a single entry point to all AssertJ features. + // ------------------------------------------------------------------------------------------------------ + + /** + * Only delegate to {@link Properties#extractProperty(String)} so that Assertions offers a full feature entry point + * to + * all AssertJ features (but you can use {@link Properties} if you prefer). + *

    + * Typical usage is to chain extractProperty with from method, see examples below : + * + *

     // extract simple property values having a java standard type (here String)
    +   * assertThat(extractProperty("name", String.class).from(fellowshipOfTheRing))
    +   *           .contains("Boromir", "Gandalf", "Frodo", "Legolas")
    +   *           .doesNotContain("Sauron", "Elrond");
    +   *
    +   * // extracting property works also with user's types (here Race)
    +   * assertThat(extractProperty("race", String.class).from(fellowshipOfTheRing))
    +   *           .contains(HOBBIT, ELF).doesNotContain(ORC);
    +   *
    +   * // extract nested property on Race
    +   * assertThat(extractProperty("race.name", String.class).from(fellowshipOfTheRing))
    +   *           .contains("Hobbit", "Elf")
    +   *           .doesNotContain("Orc");
    + * @param the type of value to extract. + * @param propertyName the name of the property to be read from the elements of a {@code Iterable}. It may be a nested + * property (e.g. "address.street.number"). + * @param propertyType the type of property to extract + * @return the created {@code Properties}. + * @throws NullPointerException if the given property name is {@code null}. + * @throws IllegalArgumentException if the given property name is empty. + * + * @since 3.20.0 + */ + public static Properties extractProperty(String propertyName, Class propertyType) { + return Assertions.extractProperty(propertyName, propertyType); + } + + /** + * Only delegate to {@link Properties#extractProperty(String)} so that Assertions offers a full feature entry point + * to + * all AssertJ features (but you can use {@link Properties} if you prefer). + *

    + * Typical usage is to chain extractProperty with from method, see examples below : + * + *

     // extract simple property values, as no type has been defined the extracted property will be considered as Object
    +   * // to define the real property type (here String) use extractProperty("name", String.class) instead.
    +   * assertThat(extractProperty("name").from(fellowshipOfTheRing))
    +   *           .contains("Boromir", "Gandalf", "Frodo", "Legolas")
    +   *           .doesNotContain("Sauron", "Elrond");
    +   *
    +   * // extracting property works also with user's types (here Race), even though it will be considered as Object
    +   * // to define the real property type (here String) use extractProperty("name", Race.class) instead.
    +   * assertThat(extractProperty("race").from(fellowshipOfTheRing)).contains(HOBBIT, ELF).doesNotContain(ORC);
    +   *
    +   * // extract nested property on Race
    +   * assertThat(extractProperty("race.name").from(fellowshipOfTheRing)).contains("Hobbit", "Elf").doesNotContain("Orc"); 
    + * + * @param propertyName the name of the property to be read from the elements of a {@code Iterable}. It may be a nested + * property (e.g. "address.street.number"). + * @throws NullPointerException if the given property name is {@code null}. + * @throws IllegalArgumentException if the given property name is empty. + * @return the created {@code Properties}. + * + * @since 3.20.0 + */ + public static Properties extractProperty(String propertyName) { + return Assertions.extractProperty(propertyName); + } + + /** + * Utility method to build nicely a {@link Tuple} when working with {@link IterableAssert#extracting(String...)} or + * {@link ObjectArrayAssert#extracting(String...)} + * + * @param values the values stored in the {@link Tuple} + * @return the built {@link Tuple} + * + * @since 3.20.0 + */ + public static Tuple tuple(Object... values) { + return Assertions.tuple(values); + } + + /** + * Globally sets whether + * {@link org.assertj.core.api.AbstractIterableAssert#extracting(String) IterableAssert#extracting(String)} + * and + * {@link org.assertj.core.api.AbstractObjectArrayAssert#extracting(String) ObjectArrayAssert#extracting(String)} + * should be allowed to extract private fields, if not and they try it fails with exception. + * + * @param allowExtractingPrivateFields allow private fields extraction. Default is {@value org.assertj.core.configuration.Configuration#ALLOW_EXTRACTING_PRIVATE_FIELDS}. + * + * @since 3.20.0 + */ + public static void setAllowExtractingPrivateFields(boolean allowExtractingPrivateFields) { + Assertions.setAllowExtractingPrivateFields(allowExtractingPrivateFields); + } + + /** + * Globally sets whether the use of private fields is allowed for comparison. + * The following (incomplete) list of methods will be impacted by this change : + *
      + *
    • + * {@link org.assertj.core.api.AbstractIterableAssert#usingElementComparatorOnFields(java.lang.String...)} + *
    • + *
    • {@link org.assertj.core.api.AbstractObjectAssert#isEqualToComparingFieldByField(Object)}
    • + *
    + * + * If the value is false and these methods try to compare private fields, it will fail with an exception. + * + * @param allowComparingPrivateFields allow private fields comparison. Default is {@value org.assertj.core.configuration.Configuration#ALLOW_COMPARING_PRIVATE_FIELDS}. + * + * @since 3.20.0 + */ + public static void setAllowComparingPrivateFields(boolean allowComparingPrivateFields) { + Assertions.setAllowComparingPrivateFields(allowComparingPrivateFields); + } + + /** + * Globally sets whether the extractor considers bare-named property methods like {@code String name()}. + * Defaults to enabled. + * @param barenamePropertyMethods whether bare-named property methods are found + * + * @since 3.20.0 + */ + public static void setExtractBareNamePropertyMethods(boolean barenamePropertyMethods) { + Assertions.setExtractBareNamePropertyMethods(barenamePropertyMethods); + } + + // ------------------------------------------------------------------------------------------------------ + // Data utility methods : not assertions but here to have a single entry point to all AssertJ features. + // ------------------------------------------------------------------------------------------------------ + + /** + * Only delegate to {@link MapEntry#entry(Object, Object)} so that Assertions offers a full feature entry point to + * all + * AssertJ features (but you can use {@link MapEntry} if you prefer). + *

    + * Typical usage is to call entry in MapAssert contains assertion, see examples below : + * + *

     Map<Ring, TolkienCharacter> ringBearers = ... // init omitted
    +   *
    +   * assertThat(ringBearers).contains(entry(oneRing, frodo), entry(nenya, galadriel));
    + * @param the type of keys in the map. + * @param the type of values in the map. + * @param key the key of the entry to create. + * @param value the value of the entry to create. + * @return the created {@code MapEntry}. + * + * @since 3.20.0 + */ + public static MapEntry entry(K key, V value) { + return Assertions.entry(key, value); + } + + /** + * Only delegate to {@link Index#atIndex(int)} so that Assertions offers a full feature entry point to all AssertJ + * features (but you can use {@link Index} if you prefer). + *

    + * Typical usage : + *

     List<Ring> elvesRings = newArrayList(vilya, nenya, narya);
    +   * assertThat(elvesRings).contains(vilya, atIndex(0)).contains(nenya, atIndex(1)).contains(narya, atIndex(2));
    + * + * @param index the value of the index. + * @return the created {@code Index}. + * @throws IllegalArgumentException if the given value is negative. + * + * @since 3.20.0 + */ + public static Index atIndex(int index) { + return Assertions.atIndex(index); + } + + /** + * Builds an {@link Offset} to use with {@code isCloseTo} assertions. + *

    + * Typical usage : + *

     assertThat(0.1).isCloseTo(0.0, within(0.1));
    + * @param value the allowed offset + * @return the created {@code Offset}. + * @throws NullPointerException if the given value is {@code null}. + * @throws IllegalArgumentException if the given value is negative. + * + * @since 3.20.0 + */ + public static Offset within(Double value) { + return Assertions.offset(value); + } + + /** + * Builds an {@link Offset} to use with real number assertions. + *

    + * Typical usage : + *

     assertThat(0.1).isEqualTo(0.0, withPrecision(0.1));
    + * @param value the required precision + * @return the created {@code Offset}. + * @throws NullPointerException if the given value is {@code null}. + * @throws IllegalArgumentException if the given value is negative. + * + * @since 3.20.0 + */ + public static Offset withPrecision(Double value) { + return Assertions.offset(value); + } + + /** + * Builds an {@link Offset} to use with isCloseTo assertions. + *

    + * Typical usage : + *

     assertThat(8.2f).isCloseTo(8.0f, within(0.2f));
    + * + * @param value the allowed offset + * @return the created {@code Offset}. + * @throws NullPointerException if the given value is {@code null}. + * @throws IllegalArgumentException if the given value is negative. + * + * @since 3.20.0 + */ + public static Offset within(Float value) { + return Assertions.offset(value); + } + + /** + * Builds an {@link Offset} to use with real number assertions. + *

    + * Typical usage : + *

     assertThat(0.2f).isEqualTo(0.0f, withPrecision(0.2f));
    + * @param value the required precision + * @return the created {@code Offset}. + * @throws NullPointerException if the given value is {@code null}. + * @throws IllegalArgumentException if the given value is negative. + * + * @since 3.20.0 + */ + public static Offset withPrecision(Float value) { + return Assertions.offset(value); + } + + /** + * Assertions entry point for BigDecimal {@link Offset} to use with isCloseTo assertions. + *

    + * Typical usage : + *

     assertThat(BigDecimal.TEN).isCloseTo(new BigDecimal("10.5"), within(BigDecimal.ONE));
    + * + * @param value the allowed offset + * @return the created {@code Offset}. + * @throws NullPointerException if the given value is {@code null}. + * @throws IllegalArgumentException if the given value is negative. + * + * @since 3.20.0 + */ + public static Offset within(BigDecimal value) { + return Assertions.within(value); + } + + /** + * Assertions entry point for BigInteger {@link Offset} to use with isCloseTo assertions. + *

    + * Typical usage : + *

     assertThat(BigInteger.TEN).isCloseTo(new BigInteger("11"), within(new BigInteger("2")));
    + * + * @since 2.7.0 / 3.7.0 + * @param value the allowed offset + * @return the created {@code Offset}. + * @throws NullPointerException if the given value is {@code null}. + * @throws IllegalArgumentException if the given value is negative. + * + * @since 3.20.0 + */ + public static Offset within(BigInteger value) { + return Assertions.within(value); + } + + /** + * Assertions entry point for Byte {@link Offset} to use with isCloseTo assertions. + *

    + * Typical usage : + *

     assertThat((byte) 10).isCloseTo((byte) 11, within((byte) 1));
    + * + * @param value the value of the offset. + * @return the created {@code Offset}. + * @throws NullPointerException if the given value is {@code null}. + * @throws IllegalArgumentException if the given value is negative. + * + * @since 3.20.0 + */ + public static Offset within(Byte value) { + return Assertions.within(value); + } + + /** + * Assertions entry point for Integer {@link Offset} to use with isCloseTo assertions. + *

    + * Typical usage : + *

     assertThat(10).isCloseTo(11, within(1));
    + * + * @param value the value of the offset. + * @return the created {@code Offset}. + * @throws NullPointerException if the given value is {@code null}. + * @throws IllegalArgumentException if the given value is negative. + * + * @since 3.20.0 + */ + public static Offset within(Integer value) { + return Assertions.within(value); + } + + /** + * Assertions entry point for Short {@link Offset} to use with isCloseTo assertions. + *

    + * Typical usage : + *

     assertThat(10).isCloseTo(11, within(1));
    + * + * @param value the allowed offset + * @return the created {@code Offset}. + * @throws NullPointerException if the given value is {@code null}. + * @throws IllegalArgumentException if the given value is negative. + * + * @since 3.20.0 + */ + public static Offset within(Short value) { + return Assertions.within(value); + } + + /** + * Assertions entry point for Long {@link Offset} to use with {@link AbstractLongAssert#isCloseTo(long, Offset) isCloseTo} assertions. + *

    + * Typical usage : + *

     assertThat(5l).isCloseTo(7l, within(2l));
    + * + * @param value the allowed offset + * @return the created {@code Offset}. + * @throws NullPointerException if the given value is {@code null}. + * @throws IllegalArgumentException if the given value is negative. + * + * @since 3.20.0 + */ + public static Offset within(Long value) { + return Assertions.within(value); + } + + /** + * Assertions entry point for {@link TemporalUnitOffset} with with less than or equal condition + * to use with isCloseTo temporal assertions. + *

    + * Typical usage : + *

     LocalTime _07_10 = LocalTime.of(7, 10);
    +   * LocalTime _07_12 = LocalTime.of(7, 12);
    +   * assertThat(_07_10).isCloseTo(_07_12, within(5, ChronoUnit.MINUTES));
    + * + * @param value the allowed offset + * @param unit the {@link TemporalUnit} of the offset + * @return the created {@code Offset}. + * + * @since 3.20.0 + */ + public static TemporalUnitOffset within(long value, TemporalUnit unit) { + return Assertions.within(value, unit); + } + + /** + * Syntactic sugar method to use with {@link AbstractDurationAssert#isCloseTo(Duration, Duration)} assertion. + *

    + * Example: + *

     assertThat(Duration.ofMinutes(2)).isCloseTo(Duration.ofMinutes(3), withMarginOf(Duration.ofMinutes(1)));
    + * + * @param allowedDifference the allowed difference {@link Duration}. + * @return the given value. + * + * @since 3.20.0 + */ + public static Duration withMarginOf(Duration allowedDifference) { + return Assertions.withMarginOf(allowedDifference); + } + + /** + * Assertions entry point for Double {@link org.assertj.core.data.Percentage} to use with isCloseTo assertions for + * percentages. + *

    + * Typical usage : + *

     assertThat(11.0).isCloseTo(10.0, withinPercentage(10.0));
    + * + * @param value the required precision percentage + * @return the created {@code Percentage}. + * @throws NullPointerException if the given value is {@code null}. + * @throws IllegalArgumentException if the given value is negative. + * + * @since 3.20.0 + */ + public static Percentage withinPercentage(Double value) { + return Assertions.withinPercentage(value); + } + + /** + * Assertions entry point for Integer {@link org.assertj.core.data.Percentage} to use with isCloseTo assertions for + * percentages. + *

    + * Typical usage : + *

     assertThat(11).isCloseTo(10, withinPercentage(10));
    + * + * @param value the required precision percentage + * @return the created {@code Percentage}. + * @throws NullPointerException if the given value is {@code null}. + * @throws IllegalArgumentException if the given value is negative. + * + * @since 3.20.0 + */ + public static Percentage withinPercentage(Integer value) { + return Assertions.withinPercentage(value); + } + + /** + * Assertions entry point for Long {@link org.assertj.core.data.Percentage} to use with isCloseTo assertions for + * percentages. + *

    + * Typical usage : + *

     assertThat(11L).isCloseTo(10L, withinPercentage(10L));
    + * + * @param value the required precision percentage + * @return the created {@code Percentage}. + * @throws NullPointerException if the given value is {@code null}. + * @throws IllegalArgumentException if the given value is negative. + * + * @since 3.20.0 + */ + public static Percentage withinPercentage(Long value) { + return Assertions.withinPercentage(value); + } + + /** + * Build a {@link Offset#strictOffset(Number) strict Offset} to use with {@link AbstractDoubleAssert#isCloseTo(double, Offset)} and {@link AbstractDoubleAssert#isNotCloseTo(double, Offset)} assertions. + *

    + * A strict offset implies a strict comparison which means that {@code isCloseTo} will fail when abs(actual - expected) == offset. + *

    + * Examples: + *

     // assertion succeeds
    +   * assertThat(8.1).isCloseTo(8.0, byLessThan(0.2));
    +   *
    +   * // assertions fail
    +   * assertThat(8.1).isCloseTo(8.0, byLessThan(0.1)); // strict comparison!
    +   * assertThat(8.1).isCloseTo(8.0, byLessThan(0.01));
    + * + * @param value the value of the offset. + * @return the created {@code Offset}. + * @throws NullPointerException if the given value is {@code null}. + * @throws IllegalArgumentException if the given value is negative. + * + * @since 3.20.0 + */ + public static Offset byLessThan(Double value) { + return Assertions.byLessThan(value); + } + + /** + * Alias for {@link #offset(Float)} to use with isCloseTo assertions. + *

    + * Typical usage : + *

     assertThat(8.2f).isCloseTo(8.0f, byLessThan(0.5f));
    + * + * @param value the value of the offset. + * @return the created {@code Offset}. + * @throws NullPointerException if the given value is {@code null}. + * @throws IllegalArgumentException if the given value is negative. + * + * @since 3.20.0 + */ + public static Offset byLessThan(Float value) { + return Assertions.byLessThan(value); + } + + /** + * Assertions entry point for BigDecimal {@link Offset} to use with isCloseTo assertions. + *

    + * Typical usage : + *

     assertThat(BigDecimal.TEN).isCloseTo(new BigDecimal("10.5"), byLessThan(BigDecimal.ONE));
    + * + * @param value the value of the offset. + * @return the created {@code Offset}. + * @throws NullPointerException if the given value is {@code null}. + * @throws IllegalArgumentException if the given value is negative. + * + * @since 3.20.0 + */ + public static Offset byLessThan(BigDecimal value) { + return Assertions.byLessThan(value); + } + + /** + * Assertions entry point for BigInteger {@link Offset} to use with isCloseTo assertions. + *

    + * Typical usage : + *

     assertThat(BigInteger.TEN).isCloseTo(new BigInteger("11"), byLessThan(new BigInteger("2")));
    + * + * @param value the value of the offset. + * @return the created {@code Offset}. + * @throws NullPointerException if the given value is {@code null}. + * @throws IllegalArgumentException if the given value is negative. + * + * @since 3.20.0 + */ + public static Offset byLessThan(BigInteger value) { + return Assertions.byLessThan(value); + } + + /** + * Assertions entry point for Byte {@link Offset} to use with isCloseTo assertions. + *

    + * Typical usage : + *

     assertThat((byte) 10).isCloseTo((byte) 11, byLessThan((byte) 2));
    + * + * @param value the value of the offset. + * @return the created {@code Offset}. + * @throws NullPointerException if the given value is {@code null}. + * @throws IllegalArgumentException if the given value is negative. + * + * @since 3.20.0 + */ + public static Offset byLessThan(Byte value) { + return Assertions.byLessThan(value); + } + + /** + * Assertions entry point for Long {@link Offset} to use with strict {@link AbstractIntegerAssert#isCloseTo(int, Offset) isCloseTo} assertions. + *

    + * Typical usage : + *

     assertThat(10).isCloseTo(12, byLessThan(1));
    + * + * @param value the value of the offset. + * @return the created {@code Offset}. + * @throws NullPointerException if the given value is {@code null}. + * @throws IllegalArgumentException if the given value is negative. + * + * @since 3.20.0 + */ + public static Offset byLessThan(Integer value) { + return Assertions.byLessThan(value); + } + + /** + * Assertions entry point for Short {@link Offset} to use with isCloseTo assertions. + *

    + * Typical usage : + *

     assertThat((short) 10).isCloseTo((short) 11, byLessThan((short) 2));
    + * + * @param value the value of the offset. + * @return the created {@code Offset}. + * @throws NullPointerException if the given value is {@code null}. + * @throws IllegalArgumentException if the given value is negative. + * + * @since 3.20.0 + */ + public static Offset byLessThan(Short value) { + return Assertions.byLessThan(value); + } + + /** + * Assertions entry point for Long {@link Offset} to use with strict {@link AbstractLongAssert#isCloseTo(long, Offset) isCloseTo} assertions. + *

    + * Typical usage : + *

     assertThat(5l).isCloseTo(7l, byLessThan(3l));
    + * + * @param value the value of the offset. + * @return the created {@code Offset}. + * @throws NullPointerException if the given value is {@code null}. + * @throws IllegalArgumentException if the given value is negative. + * + * @since 3.20.0 + */ + public static Offset byLessThan(Long value) { + return Assertions.byLessThan(value); + } + + /** + * Assertions entry point for {@link TemporalUnitOffset} with strict less than condition + * to use with {@code isCloseTo} temporal assertions. + *

    + * Typical usage : + *

     LocalTime _07_10 = LocalTime.of(7, 10);
    +   * LocalTime _07_12 = LocalTime.of(7, 12);
    +   * assertThat(_07_10).isCloseTo(_07_12, byLessThan(5, ChronoUnit.MINUTES));
    + * + * @param value the value of the offset. + * @param unit the {@link TemporalUnit} of the offset. + * @return the created {@code Offset}. + * + * @since 3.20.0 + */ + public static TemporalUnitOffset byLessThan(long value, TemporalUnit unit) { + return Assertions.byLessThan(value, unit); + } + + /** + * A syntax sugar to write fluent assertion using {@link ObjectAssert#returns(Object, Function)}. + *

    + * Example: + *

     Jedi yoda = new Jedi("Yoda", "Green");
    +   * assertThat(yoda).returns("Yoda", from(Jedi::getName))
    +   *                 .returns(2.4, from(Jedi::getHeight))
    +   *                 .returns(150, from(Jedi::getWeight)); 
    + * + * @param extractor A function to extract test subject's property + * @param Type of test subject + * @param Type of the property under the assertion + * @return same instance of {@code extractor} + * + * @since 3.20.0 + */ + public static Function from(Function extractor) { + return Assertions.from(extractor); + } + + /** + * A syntax sugar to write fluent assertion with methods having an {@link InstanceOfAssertFactory} parameter. + *

    + * Example: + *

     Jedi yoda = new Jedi("Yoda", "Green");
    +   * assertThat(yoda).extracting(Jedi::getName, as(InstanceOfAssertFactories.STRING))
    +   *                 .startsWith("Yo");
    + * + * @param assertFactory the factory which verifies the type and creates the new {@code Assert} + * @param the type to use for the cast. + * @param the type of the resulting {@code Assert} + * @return same instance of {@code assertFactory} + * + * @since 3.20.0 + * @see AbstractObjectAssert#extracting(String, InstanceOfAssertFactory) + * @see AbstractObjectAssert#extracting(Function, InstanceOfAssertFactory) + * @see AbstractMapAssert#extractingByKey(Object, InstanceOfAssertFactory) + * @see AbstractOptionalAssert#get(InstanceOfAssertFactory) + * @see AbstractIterableAssert#first(InstanceOfAssertFactory) + * @see AbstractIterableAssert#last(InstanceOfAssertFactory) + * @see AbstractIterableAssert#element(int, InstanceOfAssertFactory) + * + * @since 3.20.0 + */ + public static > InstanceOfAssertFactory as(InstanceOfAssertFactory assertFactory) { + return Assertions.as(assertFactory); + } + // ------------------------------------------------------------------------------------------------------ + // Condition methods : not assertions but here to have a single entry point to all AssertJ features. + // ------------------------------------------------------------------------------------------------------ + + /** + * Creates a new {@link AllOf} + * + * @param the type of object the given condition accept. + * @param conditions the conditions to evaluate. + * @return the created {@code AllOf}. + * @throws NullPointerException if the given array is {@code null}. + * @throws NullPointerException if any of the elements in the given array is {@code null}. + * + * @since 3.20.0 + */ + @SafeVarargs + public static Condition allOf(Condition... conditions) { + return Assertions.allOf(conditions); + } + + /** + * Creates a new {@link AllOf} + * + * @param the type of object the given condition accept. + * @param conditions the conditions to evaluate. + * @return the created {@code AllOf}. + * @throws NullPointerException if the given iterable is {@code null}. + * @throws NullPointerException if any of the elements in the given iterable is {@code null}. + * + * @since 3.20.0 + */ + public static Condition allOf(Iterable> conditions) { + return Assertions.allOf(conditions); + } + + /** + * Only delegate to {@link AnyOf#anyOf(Condition...)} so that Assertions offers a full feature entry point to all + * AssertJ features (but you can use {@link AnyOf} if you prefer). + *

    + * Typical usage (jedi and sith are {@link Condition}) : + * + *

     assertThat("Vader").is(anyOf(jedi, sith));
    + * + * @param the type of object the given condition accept. + * @param conditions the conditions to evaluate. + * @return the created {@code AnyOf}. + * + * @since 3.20.0 + */ + @SafeVarargs + public static Condition anyOf(Condition... conditions) { + return Assertions.anyOf(conditions); + } + + /** + * Creates a new {@link AnyOf} + * + * @param the type of object the given condition accept. + * @param conditions the conditions to evaluate. + * @return the created {@code AnyOf}. + * @throws NullPointerException if the given iterable is {@code null}. + * @throws NullPointerException if any of the elements in the given iterable is {@code null}. + * + * @since 3.20.0 + */ + public static Condition anyOf(Iterable> conditions) { + return Assertions.anyOf(conditions); + } + + /** + * Creates a new {@link DoesNotHave}. + * + * @param the type of object the given condition accept. + * @param condition the condition to inverse. + * @return The DoesNotHave condition created. + * + * @since 3.20.0 + */ + public static DoesNotHave doesNotHave(Condition condition) { + return Assertions.doesNotHave(condition); + } + + /** + * Creates a new {@link Not}. + * + * @param the type of object the given condition accept. + * @param condition the condition to inverse. + * @return The Not condition created. + * + * @since 3.20.0 + */ + public static Not not(Condition condition) { + return Assertions.not(condition); + } + + // -------------------------------------------------------------------------------------------------- + // Filter methods : not assertions but here to have a single entry point to all AssertJ features. + // -------------------------------------------------------------------------------------------------- + + /** + * Create a {@link FilterOperator} to use in {@link AbstractIterableAssert#filteredOn(String, FilterOperator) + * filteredOn(String, FilterOperation)} to express a filter keeping all Iterable elements whose property/field + * value matches one of the given values. + *

    + * As often, an example helps: + *

     Employee yoda   = new Employee(1L, new Name("Yoda"), 800);
    +   * Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);
    +   * Employee luke   = new Employee(3L, new Name("Luke", "Skywalker"), 26);
    +   * Employee noname = new Employee(4L, null, 50);
    +   *
    +   * List<Employee> employees = newArrayList(yoda, luke, obiwan, noname);
    +   *
    +   * assertThat(employees).filteredOn("age", in(800, 26))
    +   *                      .containsOnly(yoda, obiwan, luke);
    + * + * @param values values to match (one match is sufficient) + * @return the created "in" filter + * + * @since 3.20.0 + */ + public static InFilter in(Object... values) { + return Assertions.in(values); + } + + /** + * Create a {@link FilterOperator} to use in {@link AbstractIterableAssert#filteredOn(String, FilterOperator) + * filteredOn(String, FilterOperation)} to express a filter keeping all Iterable elements whose property/field + * value matches does not match any of the given values. + *

    + * As often, an example helps: + *

     Employee yoda   = new Employee(1L, new Name("Yoda"), 800);
    +   * Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);
    +   * Employee luke   = new Employee(3L, new Name("Luke", "Skywalker"), 26);
    +   * Employee noname = new Employee(4L, null, 50);
    +   *
    +   * List<Employee> employees = newArrayList(yoda, luke, obiwan, noname);
    +   *
    +   * assertThat(employees).filteredOn("age", notIn(800, 50))
    +   *                      .containsOnly(luke);
    + * + * @param valuesNotToMatch values not to match (none of the values must match) + * @return the created "not in" filter + * + * @since 3.20.0 + */ + public static NotInFilter notIn(Object... valuesNotToMatch) { + return Assertions.notIn(valuesNotToMatch); + } + + /** + * Create a {@link FilterOperator} to use in {@link AbstractIterableAssert#filteredOn(String, FilterOperator) + * filteredOn(String, FilterOperation)} to express a filter keeping all Iterable elements whose property/field + * value matches does not match the given value. + *

    + * As often, an example helps: + *

     Employee yoda   = new Employee(1L, new Name("Yoda"), 800);
    +   * Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);
    +   * Employee luke   = new Employee(3L, new Name("Luke", "Skywalker"), 26);
    +   * Employee noname = new Employee(4L, null, 50);
    +   *
    +   * List<Employee> employees = newArrayList(yoda, luke, obiwan, noname);
    +   *
    +   * assertThat(employees).filteredOn("age", not(800))
    +   *                      .containsOnly(luke, noname);
    + * + * @param valueNotToMatch the value not to match + * @return the created "not" filter + * + * @since 3.20.0 + */ + public static NotFilter not(Object valueNotToMatch) { + return Assertions.not(valueNotToMatch); + } + + // -------------------------------------------------------------------------------------------------- + // File methods : not assertions but here to have a single entry point to all AssertJ features. + // -------------------------------------------------------------------------------------------------- + + /** + * Loads the text content of a file, so that it can be passed to {@link #assertThat(String)}. + *

    + * Note that this will load the entire file in memory; for larger files, there might be a more efficient alternative + * with {@link #assertThat(File)}. + *

    + * + * @param file the file. + * @param charset the character set to use. + * @return the content of the file. + * @throws NullPointerException if the given charset is {@code null}. + * @throws UncheckedIOException if an I/O exception occurs. + * + * @since 3.20.0 + */ + public static String contentOf(File file, Charset charset) { + return Assertions.contentOf(file, charset); + } + + /** + * Loads the text content of a file, so that it can be passed to {@link #assertThat(String)}. + *

    + * Note that this will load the entire file in memory; for larger files, there might be a more efficient alternative + * with {@link #assertThat(File)}. + *

    + * + * @param file the file. + * @param charsetName the name of the character set to use. + * @return the content of the file. + * @throws IllegalArgumentException if the given character set is not supported on this platform. + * @throws UncheckedIOException if an I/O exception occurs. + * + * @since 3.20.0 + */ + public static String contentOf(File file, String charsetName) { + return Assertions.contentOf(file, charsetName); + } + + /** + * Loads the text content of a file with the default character set, so that it can be passed to + * {@link #assertThat(String)}. + *

    + * Note that this will load the entire file in memory; for larger files, there might be a more efficient alternative + * with {@link #assertThat(File)}. + *

    + * + * @param file the file. + * @return the content of the file. + * @throws UncheckedIOException if an I/O exception occurs. + * + * @since 3.20.0 + */ + public static String contentOf(File file) { + return Assertions.contentOf(file, Charset.defaultCharset()); + } + + /** + * Loads the text content of a file into a list of strings with the default charset, each string corresponding to a + * line. + * The line endings are either \n, \r or \r\n. + * + * @param file the file. + * @return the content of the file. + * @throws NullPointerException if the given charset is {@code null}. + * @throws UncheckedIOException if an I/O exception occurs. + * + * @since 3.20.0 + */ + public static List linesOf(File file) { + return Assertions.linesOf(file, Charset.defaultCharset()); + } + + /** + * Loads the text content of a file into a list of strings, each string corresponding to a line. + * The line endings are either \n, \r or \r\n. + * + * @param file the file. + * @param charset the character set to use. + * @return the content of the file. + * @throws NullPointerException if the given charset is {@code null}. + * @throws UncheckedIOException if an I/O exception occurs. + * + * @since 3.20.0 + */ + public static List linesOf(File file, Charset charset) { + return Assertions.linesOf(file, charset); + } + + /** + * Loads the text content of a file into a list of strings, each string corresponding to a line. The line endings are + * either \n, \r or \r\n. + * + * @param file the file. + * @param charsetName the name of the character set to use. + * @return the content of the file. + * @throws NullPointerException if the given charset is {@code null}. + * @throws UncheckedIOException if an I/O exception occurs. + * + * @since 3.20.0 + */ + public static List linesOf(File file, String charsetName) { + return Assertions.linesOf(file, charsetName); + } + + // -------------------------------------------------------------------------------------------------- + // URL/Resource methods : not assertions but here to have a single entry point to all AssertJ features. + // -------------------------------------------------------------------------------------------------- + + /** + * Loads the text content of a URL, so that it can be passed to {@link #assertThat(String)}. + *

    + * Note that this will load the entire contents in memory. + *

    + * + * @param url the URL. + * @param charset the character set to use. + * @return the content of the URL. + * @throws NullPointerException if the given charset is {@code null}. + * @throws UncheckedIOException if an I/O exception occurs. + * + * @since 3.20.0 + */ + public static String contentOf(URL url, Charset charset) { + return Assertions.contentOf(url, charset); + } + + /** + * Loads the text content of a URL, so that it can be passed to {@link #assertThat(String)}. + *

    + * Note that this will load the entire contents in memory. + *

    + * + * @param url the URL. + * @param charsetName the name of the character set to use. + * @return the content of the URL. + * @throws IllegalArgumentException if the given character set is not supported on this platform. + * @throws UncheckedIOException if an I/O exception occurs. + * + * @since 3.20.0 + */ + public static String contentOf(URL url, String charsetName) { + return Assertions.contentOf(url, charsetName); + } + + /** + * Loads the text content of a URL with the default character set, so that it can be passed to + * {@link #assertThat(String)}. + *

    + * Note that this will load the entire file in memory; for larger files. + *

    + * + * @param url the URL. + * @return the content of the file. + * @throws UncheckedIOException if an I/O exception occurs. + * + * @since 3.20.0 + */ + public static String contentOf(URL url) { + return Assertions.contentOf(url, Charset.defaultCharset()); + } + + /** + * Loads the text content of a URL into a list of strings with the default charset, each string corresponding to a + * line. + * The line endings are either \n, \r or \r\n. + * + * @param url the URL. + * @return the content of the file. + * @throws NullPointerException if the given charset is {@code null}. + * @throws UncheckedIOException if an I/O exception occurs. + * + * @since 3.20.0 + */ + public static List linesOf(URL url) { + return Assertions.linesOf(url, Charset.defaultCharset()); + } + + /** + * Loads the text content of a URL into a list of strings, each string corresponding to a line. + * The line endings are either \n, \r or \r\n. + * + * @param url the URL. + * @param charset the character set to use. + * @return the content of the file. + * @throws NullPointerException if the given charset is {@code null}. + * @throws UncheckedIOException if an I/O exception occurs. + * + * @since 3.20.0 + */ + public static List linesOf(URL url, Charset charset) { + return Assertions.linesOf(url, charset); + } + + /** + * Loads the text content of a URL into a list of strings, each string corresponding to a line. The line endings are + * either \n, \r or \r\n. + * + * @param url the URL. + * @param charsetName the name of the character set to use. + * @return the content of the file. + * @throws NullPointerException if the given charset is {@code null}. + * @throws UncheckedIOException if an I/O exception occurs. + * + * @since 3.20.0 + */ + public static List linesOf(URL url, String charsetName) { + return Assertions.linesOf(url, charsetName); + } + + // -------------------------------------------------------------------------------------------------- + // Date formatting methods : not assertions but here to have a single entry point to all AssertJ features. + // -------------------------------------------------------------------------------------------------- + + /** + * Instead of using default strict date/time parsing, it is possible to use lenient parsing mode for default date + * formats parser to interpret inputs that do not precisely match supported date formats (lenient parsing). + *

    + * With strict parsing, inputs must match exactly date/time format. + * + *

    + * Example: + *

     final Date date = Dates.parse("2001-02-03");
    +   * final Date dateTime = parseDatetime("2001-02-03T04:05:06");
    +   * final Date dateTimeWithMs = parseDatetimeWithMs("2001-02-03T04:05:06.700");
    +   *
    +   * Assertions.setLenientDateParsing(true);
    +   *
    +   * // assertions will pass
    +   * assertThat(date).isEqualTo("2001-01-34");
    +   * assertThat(date).isEqualTo("2001-02-02T24:00:00");
    +   * assertThat(date).isEqualTo("2001-02-04T-24:00:00.000");
    +   * assertThat(dateTime).isEqualTo("2001-02-03T04:05:05.1000");
    +   * assertThat(dateTime).isEqualTo("2001-02-03T04:04:66");
    +   * assertThat(dateTimeWithMs).isEqualTo("2001-02-03T04:05:07.-300");
    +   *
    +   * // assertions will fail
    +   * assertThat(date).hasSameTimeAs("2001-02-04"); // different date
    +   * assertThat(dateTime).hasSameTimeAs("2001-02-03 04:05:06"); // leniency does not help here
    + * + * To revert to default strict date parsing, call {@code setLenientDateParsing(false)}. + * + * @param value whether lenient parsing mode should be enabled or not + * + * @since 3.20.0 + */ + public static void setLenientDateParsing(boolean value) { + Assertions.setLenientDateParsing(value); + } + + /** + * Add the given date format to the ones used to parse date String in String based Date assertions like + * {@link org.assertj.core.api.AbstractDateAssert#isEqualTo(String)}. + *

    + * User date formats are used before default ones in the order they have been registered (first registered, first + * used). + *

    + * AssertJ is gonna use any date formats registered with one of these methods : + *

      + *
    • {@link org.assertj.core.api.AbstractDateAssert#withDateFormat(String)}
    • + *
    • {@link org.assertj.core.api.AbstractDateAssert#withDateFormat(java.text.DateFormat)}
    • + *
    • {@link #registerCustomDateFormat(java.text.DateFormat)}
    • + *
    • {@link #registerCustomDateFormat(String)}
    • + *
    + *

    + * Beware that AssertJ will use the newly registered format for all remaining Date assertions in the test suite + *

    + * To revert to default formats only, call {@link #useDefaultDateFormatsOnly()} or + * {@link org.assertj.core.api.AbstractDateAssert#withDefaultDateFormatsOnly()}. + *

    + * Code examples: + *

     Date date = ... // set to 2003 April the 26th
    +   * assertThat(date).isEqualTo("2003-04-26");
    +   *
    +   * try {
    +   *   // date with a custom format : failure since the default formats don't match.
    +   *   assertThat(date).isEqualTo("2003/04/26");
    +   * } catch (AssertionError e) {
    +   *   assertThat(e).hasMessage("Failed to parse 2003/04/26 with any of these date formats: " +
    +   *                            "[yyyy-MM-dd'T'HH:mm:ss.SSSX, yyyy-MM-dd'T'HH:mm:ss.SSS, " +
    +   *                            "yyyy-MM-dd'T'HH:mm:ssX, " +
    +   *                            "yyyy-MM-dd'T'HH:mm:ss, yyyy-MM-dd]");
    +   * }
    +   *
    +   * // registering a custom date format to make the assertion pass
    +   * registerCustomDateFormat(new SimpleDateFormat("yyyy/MM/dd")); // registerCustomDateFormat("yyyy/MM/dd") would work to.
    +   * assertThat(date).isEqualTo("2003/04/26");
    +   *
    +   * // the default formats are still available and should work
    +   * assertThat(date).isEqualTo("2003-04-26");
    + * + * @param userCustomDateFormat the new Date format used for String based Date assertions. + * + * @since 3.20.0 + */ + public static void registerCustomDateFormat(DateFormat userCustomDateFormat) { + Assertions.registerCustomDateFormat(userCustomDateFormat); + } + + /** + * Add the given date format to the ones used to parse date String in String based Date assertions like + * {@link org.assertj.core.api.AbstractDateAssert#isEqualTo(String)}. + *

    + * User date formats are used before default ones in the order they have been registered (first registered, first + * used). + *

    + * AssertJ is gonna use any date formats registered with one of these methods : + *

      + *
    • {@link org.assertj.core.api.AbstractDateAssert#withDateFormat(String)}
    • + *
    • {@link org.assertj.core.api.AbstractDateAssert#withDateFormat(java.text.DateFormat)}
    • + *
    • {@link #registerCustomDateFormat(java.text.DateFormat)}
    • + *
    • {@link #registerCustomDateFormat(String)}
    • + *
    + *

    + * Beware that AssertJ will use the newly registered format for all remaining Date assertions in the test suite. + *

    + * To revert to default formats only, call {@link #useDefaultDateFormatsOnly()} or + * {@link org.assertj.core.api.AbstractDateAssert#withDefaultDateFormatsOnly()}. + *

    + * Code examples: + *

     Date date = ... // set to 2003 April the 26th
    +   * assertThat(date).isEqualTo("2003-04-26");
    +   *
    +   * try {
    +   *   // date with a custom format : failure since the default formats don't match.
    +   *   assertThat(date).isEqualTo("2003/04/26");
    +   * } catch (AssertionError e) {
    +   *   assertThat(e).hasMessage("Failed to parse 2003/04/26 with any of these date formats: " +
    +   *                            "[yyyy-MM-dd'T'HH:mm:ss.SSSX, yyyy-MM-dd'T'HH:mm:ss.SSS, " +
    +   *                            "yyyy-MM-dd'T'HH:mm:ssX, " +
    +   *                            "yyyy-MM-dd'T'HH:mm:ss, yyyy-MM-dd]");
    +   * }
    +   *
    +   * // registering a custom date format to make the assertion pass
    +   * registerCustomDateFormat("yyyy/MM/dd");
    +   * assertThat(date).isEqualTo("2003/04/26");
    +   *
    +   * // the default formats are still available and should work
    +   * assertThat(date).isEqualTo("2003-04-26");
    + * + * @param userCustomDateFormatPattern the new Date format pattern used for String based Date assertions. + * + * @since 3.20.0 + */ + public static void registerCustomDateFormat(String userCustomDateFormatPattern) { + Assertions.registerCustomDateFormat(userCustomDateFormatPattern); + } + + /** + * Remove all registered custom date formats => use only the defaults date formats to parse string as date. + *

    + * Beware that the default formats are expressed in the current local timezone. + *

    + * Defaults date format are: + *

      + *
    • yyyy-MM-dd HH:mm:ss.SSSX
    • + *
    • yyyy-MM-dd'T'HH:mm:ss.SSS
    • + *
    • yyyy-MM-dd HH:mm:ss.SSS (for {@link java.sql.Timestamp} String representation support)
    • + *
    • yyyy-MM-dd'T'HH:mm:ssX
    • + *
    • yyyy-MM-dd'T'HH:mm:ss
    • + *
    • yyyy-MM-dd
    • + *
    + *

    + * Example of valid string date representations: + *

      + *
    • 2003-04-26T03:01:02.999
    • + *
    • 2003-04-26 03:01:02.999
    • + *
    • 2003-04-26T13:01:02
    • + *
    • 2003-04-26
    • + *
    + * + * @since 3.20.0 + */ + public static void useDefaultDateFormatsOnly() { + Assertions.useDefaultDateFormatsOnly(); + } + + /** + * Register a {@link Representation} that will be used in all following assertions. + *

    + * {@link Representation} are used to format types in assertions error messages. + *

    + * An alternative way of using a different representation is to register one as a service, + * this approach is described in {@link Representation}, it requires more work than this method + * but has the advantage of not having to do anything in your tests and it would be applied to all the tests globally + *

    + * Example : + *

     private class Example {}
    +   *
    +   * private class CustomRepresentation extends StandardRepresentation {
    +   *
    +   *   // override needed to hook specific formatting
    +   *   {@literal @}Override
    +   *   public String toStringOf(Object o) {
    +   *     if (o instanceof Example) return "Example";
    +   *     // fallback to default formatting.
    +   *     return super.toStringOf(o);
    +   *   }
    +   *
    +   *   // change String representation
    +   *   {@literal @}Override
    +   *   protected String toStringOf(String s) {
    +   *     return "$" + s + "$";
    +   *   }
    +   * }
    +   *
    +   * Assertions.useRepresentation(new CustomRepresentation());
    +   *
    +   * // this assertion fails ...
    +   * assertThat(new Example()).isNull();
    +   * // ... with error :
    +   * // "expected:<[null]> but was:<[Example]>"
    +   *
    +   * // this one fails ...
    +   * assertThat("foo").startsWith("bar");
    +   * // ... with error :
    +   * // Expecting:
    +   * //   <$foo$>
    +   * // to start with:
    +   * //   <$bar$>
    + * + * @param customRepresentation the {@link Representation} to use + * + * @since 3.20.0 + */ + public static void useRepresentation(Representation customRepresentation) { + Assertions.useRepresentation(customRepresentation); + } + + /** + * Assertions error messages uses a {@link Representation} to format the different types involved, using this method + * you can control the formatting of a given type by providing a specific formatter. + * + * + *

    + * Registering a formatter makes it available for all AssertJ {@link Representation}: + *

      + *
    • {@link StandardRepresentation}
    • + *
    • {@link UnicodeRepresentation}
    • + *
    • {@link HexadecimalRepresentation}
    • + *
    • {@link BinaryRepresentation}
    • + *
    + *

    + * Example : + *

     // without specific formatter
    +   * assertThat(STANDARD_REPRESENTATION.toStringOf(123L)).isEqualTo("123L");
    +   *
    +   * // register a formatter for Long
    +   * Assertions.registerFormatterForType(Long.class, value -> "$" + value + "$");
    +   *
    +   * // now Long will be formatted between in $$ in error message.
    +   * assertThat(STANDARD_REPRESENTATION.toStringOf(longNumber)).isEqualTo("$123$");
    +   *
    +   * // fails with error : expected:<$456$> but was:<$123$>
    +   * assertThat(123L).isEqualTo(456L);
    + * + * @param the type of format. + * @param type the class of the type to format + * @param formatter the formatter {@link Function} + * + * @since 3.5.0 + */ + public static void registerFormatterForType(Class type, Function formatter) { + Assertions.registerFormatterForType(type, formatter); + } + + /** + * Fallback to use {@link StandardRepresentation} to revert the effect of calling {@link #useRepresentation(Representation)}. + * + * @since 3.20.0 + */ + public static void useDefaultRepresentation() { + Assertions.useDefaultRepresentation(); + } } diff --git a/src/main/java/org/assertj/core/api/BDDAssumptions.java b/src/main/java/org/assertj/core/api/BDDAssumptions.java index edbc3973b9b..d5046f27a25 100644 --- a/src/main/java/org/assertj/core/api/BDDAssumptions.java +++ b/src/main/java/org/assertj/core/api/BDDAssumptions.java @@ -124,10 +124,10 @@ private BDDAssumptions() {} *} * * @param actual the actual boolean value to be validated. - * @return the {@link AbstractBooleanAssert} assertion object to be used for validation. + * @return the {@link BooleanAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractBooleanAssert given(boolean actual) { + public static BooleanAssert given(boolean actual) { return assumeThat(actual); } @@ -153,10 +153,10 @@ public static AbstractBooleanAssert given(boolean actual) { *} * * @param actual the actual {@link Boolean} value to be validated. - * @return the {@link AbstractBooleanAssert} assertion object to be used for validation. + * @return the {@link BooleanAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractBooleanAssert given(Boolean actual) { + public static BooleanAssert given(Boolean actual) { return assumeThat(actual); } @@ -182,10 +182,10 @@ public static AbstractBooleanAssert given(Boolean actual) { *} * * @param actual the actual booleans' array to be validated. - * @return the {@link AbstractBooleanArrayAssert} assertion object to be used for validation. + * @return the {@link BooleanArrayAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractBooleanArrayAssert given(boolean[] actual) { + public static BooleanArrayAssert given(boolean[] actual) { return assumeThat(actual); } @@ -240,10 +240,10 @@ public static Boolean2DArrayAssert given(boolean[][] actual) { *} * * @param actual the actual byte value to be validated. - * @return the {@link AbstractByteAssert} assertion object to be used for validation. + * @return the {@link ByteAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractByteAssert given(byte actual) { + public static ByteAssert given(byte actual) { return assumeThat(actual); } @@ -269,10 +269,10 @@ public static AbstractByteAssert given(byte actual) { *} * * @param actual the actual {@link Byte} value to be validated. - * @return the {@link AbstractByteAssert} assertion object to be used for validation. + * @return the {@link ByteAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractByteAssert given(Byte actual) { + public static ByteAssert given(Byte actual) { return assumeThat(actual); } @@ -298,10 +298,10 @@ public static AbstractByteAssert given(Byte actual) { *} * * @param actual the actual bytes' array to be validated. - * @return the {@link AbstractByteArrayAssert} assertion object to be used for validation. + * @return the {@link ByteArrayAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractByteArrayAssert given(byte[] actual) { + public static ByteArrayAssert given(byte[] actual) { return assumeThat(actual); } @@ -356,10 +356,10 @@ public static Byte2DArrayAssert given(byte[][] actual) { *} * * @param actual the actual short value to be validated. - * @return the {@link AbstractShortAssert} assertion object to be used for validation. + * @return the {@link ShortAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractShortAssert given(short actual) { + public static ShortAssert given(short actual) { return assumeThat(actual); } @@ -385,10 +385,10 @@ public static AbstractShortAssert given(short actual) { *} * * @param actual the actual {@link Short} value to be validated. - * @return the {@link AbstractShortAssert} assertion object to be used for validation. + * @return the {@link ShortAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractShortAssert given(Short actual) { + public static ShortAssert given(Short actual) { return assumeThat(actual); } @@ -414,10 +414,10 @@ public static AbstractShortAssert given(Short actual) { *} * * @param actual the actual shorts' array to be validated. - * @return the {@link AbstractShortArrayAssert} assertion object to be used for validation. + * @return the {@link ShortArrayAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractShortArrayAssert given(short[] actual) { + public static ShortArrayAssert given(short[] actual) { return assumeThat(actual); } @@ -472,10 +472,10 @@ public static Short2DArrayAssert given(short[][] actual) { *} * * @param actual the actual int value to be validated. - * @return the {@link AbstractIntegerAssert} assertion object to be used for validation. + * @return the {@link IntegerAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractIntegerAssert given(int actual) { + public static IntegerAssert given(int actual) { return assumeThat(actual); } @@ -501,10 +501,10 @@ public static AbstractIntegerAssert given(int actual) { *} * * @param actual the actual {@link Integer} value to be validated. - * @return the {@link AbstractIntegerAssert} assertion object to be used for validation. + * @return the {@link IntegerAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractIntegerAssert given(Integer actual) { + public static IntegerAssert given(Integer actual) { return assumeThat(actual); } @@ -530,10 +530,10 @@ public static AbstractIntegerAssert given(Integer actual) { *} * * @param actual the actual ints' array to be validated. - * @return the {@link AbstractIntArrayAssert} assertion object to be used for validation. + * @return the {@link IntArrayAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractIntArrayAssert given(int[] actual) { + public static IntArrayAssert given(int[] actual) { return assumeThat(actual); } @@ -588,10 +588,10 @@ public static Int2DArrayAssert given(int[][] actual) { *} * * @param actual the actual {@link BigInteger} value to be validated. - * @return the {@link AbstractBigIntegerAssert} assertion object to be used for validation. + * @return the {@link BigIntegerAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractBigIntegerAssert given(BigInteger actual) { + public static BigIntegerAssert given(BigInteger actual) { return assumeThat(actual); } @@ -617,10 +617,10 @@ public static AbstractBigIntegerAssert given(BigInteger actual) { *} * * @param actual the actual long value to be validated. - * @return the {@link AbstractLongAssert} assertion object to be used for validation. + * @return the {@link LongAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractLongAssert given(long actual) { + public static LongAssert given(long actual) { return assumeThat(actual); } @@ -646,10 +646,10 @@ public static AbstractLongAssert given(long actual) { *} * * @param actual the actual {@link Long} value to be validated. - * @return the {@link AbstractLongAssert} assertion object to be used for validation. + * @return the {@link LongAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractLongAssert given(Long actual) { + public static LongAssert given(Long actual) { return assumeThat(actual); } @@ -675,10 +675,10 @@ public static AbstractLongAssert given(Long actual) { *} * * @param actual the actual longs' array to be validated. - * @return the {@link AbstractLongArrayAssert} assertion object to be used for validation. + * @return the {@link LongArrayAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractLongArrayAssert given(long[] actual) { + public static LongArrayAssert given(long[] actual) { return assumeThat(actual); } @@ -733,10 +733,10 @@ public static Long2DArrayAssert given(long[][] actual) { *} * * @param actual the actual float value to be validated. - * @return the {@link AbstractFloatAssert} assertion object to be used for validation. + * @return the {@link FloatAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractFloatAssert given(float actual) { + public static FloatAssert given(float actual) { return assumeThat(actual); } @@ -762,10 +762,10 @@ public static AbstractFloatAssert given(float actual) { *} * * @param actual the actual {@link Float} value to be validated. - * @return the {@link AbstractFloatAssert} assertion object to be used for validation. + * @return the {@link FloatAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractFloatAssert given(Float actual) { + public static FloatAssert given(Float actual) { return assumeThat(actual); } @@ -791,10 +791,10 @@ public static AbstractFloatAssert given(Float actual) { *} * * @param actual the actual floats' array to be validated. - * @return the {@link AbstractFloatArrayAssert} assertion object to be used for validation. + * @return the {@link FloatArrayAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractFloatArrayAssert given(float[] actual) { + public static FloatArrayAssert given(float[] actual) { return assumeThat(actual); } @@ -849,10 +849,10 @@ public static Float2DArrayAssert given(float[][] actual) { *} * * @param actual the actual double value to be validated. - * @return the {@link AbstractDoubleAssert} assertion object to be used for validation. + * @return the {@link DoubleAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractDoubleAssert given(double actual) { + public static DoubleAssert given(double actual) { return assumeThat(actual); } @@ -878,10 +878,10 @@ public static AbstractDoubleAssert given(double actual) { *} * * @param actual the actual {@link Double} value to be validated. - * @return the {@link AbstractDoubleAssert} assertion object to be used for validation. + * @return the {@link DoubleAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractDoubleAssert given(Double actual) { + public static DoubleAssert given(Double actual) { return assumeThat(actual); } @@ -907,10 +907,10 @@ public static AbstractDoubleAssert given(Double actual) { *} * * @param actual the actual doubles' array to be validated. - * @return the {@link AbstractDoubleArrayAssert} assertion object to be used for validation. + * @return the {@link DoubleArrayAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractDoubleArrayAssert given(double[] actual) { + public static DoubleArrayAssert given(double[] actual) { return assumeThat(actual); } @@ -965,10 +965,10 @@ public static Double2DArrayAssert given(double[][] actual) { *} * * @param actual the actual {@link BigDecimal} value to be validated. - * @return the {@link AbstractBigDecimalAssert} assertion object to be used for validation. + * @return the {@link BigDecimalAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractBigDecimalAssert given(BigDecimal actual) { + public static BigDecimalAssert given(BigDecimal actual) { return assumeThat(actual); } @@ -994,10 +994,10 @@ public static AbstractBigDecimalAssert given(BigDecimal actual) { *} * * @param actual the actual char value to be validated. - * @return the {@link AbstractCharacterAssert} assertion object to be used for validation. + * @return the {@link CharacterAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractCharacterAssert given(char actual) { + public static CharacterAssert given(char actual) { return assumeThat(actual); } @@ -1023,10 +1023,10 @@ public static AbstractCharacterAssert given(char actual) { *} * * @param actual the actual {@link Character} value to be validated. - * @return the {@link AbstractCharacterAssert} assertion object to be used for validation. + * @return the {@link CharacterAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractCharacterAssert given(Character actual) { + public static CharacterAssert given(Character actual) { return assumeThat(actual); } @@ -1052,10 +1052,10 @@ public static AbstractCharacterAssert given(Character actual) { *} * * @param actual the actual chars' array to be validated. - * @return the {@link AbstractCharacterAssert} assertion object to be used for validation. + * @return the {@link CharacterAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractCharArrayAssert given(char[] actual) { + public static CharArrayAssert given(char[] actual) { return assumeThat(actual); } @@ -1110,10 +1110,10 @@ public static Char2DArrayAssert given(char[][] actual) { *} * * @param actual the actual {@link CharSequence} value to be validated. - * @return the {@link AbstractCharSequenceAssert} assertion object to be used for validation. + * @return the {@link CharSequenceAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractCharSequenceAssert given(CharSequence actual) { + public static CharSequenceAssert given(CharSequence actual) { return assumeThat(actual); } @@ -1139,10 +1139,10 @@ public static Char2DArrayAssert given(char[][] actual) { *} * * @param actual the actual {@link String} value to be validated. - * @return the {@link AbstractStringAssert} assertion object to be used for validation. + * @return the {@link StringAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractStringAssert given(String actual) { + public static StringAssert given(String actual) { return assumeThat(actual); } @@ -1168,10 +1168,10 @@ public static AbstractStringAssert given(String actual) { *} * * @param actual the actual {@link StringBuilder} value to be validated. - * @return the {@link AbstractCharSequenceAssert} assertion object to be used for validation. + * @return the {@link CharSequenceAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractCharSequenceAssert given(StringBuilder actual) { + public static CharSequenceAssert given(StringBuilder actual) { return assumeThat(actual); } @@ -1197,10 +1197,10 @@ public static AbstractStringAssert given(String actual) { *} * * @param actual the actual {@link StringBuffer} value to be validated. - * @return the {@link AbstractCharSequenceAssert} assertion object to be used for validation. + * @return the {@link CharSequenceAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractCharSequenceAssert given(StringBuffer actual) { + public static CharSequenceAssert given(StringBuffer actual) { return assumeThat(actual); } @@ -1226,10 +1226,10 @@ public static AbstractStringAssert given(String actual) { *} * * @param actual the actual {@link Class} value to be validated. - * @return the {@link AbstractClassAssert} assertion object to be used for validation. + * @return the {@link ClassAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractClassAssert given(Class actual) { + public static ClassAssert given(Class actual) { return assumeThat(actual); } @@ -1260,10 +1260,10 @@ public static AbstractClassAssert given(Class actual) { * * @param the type of the actual object. * @param actual the actual object to be validated. - * @return the {@link AbstractObjectAssert} assertion object to be used for validation. + * @return the {@link ObjectAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static ProxyableObjectAssert given(T actual) { + public static ObjectAssert given(T actual) { return assumeThat(actual); } @@ -1290,10 +1290,10 @@ public static ProxyableObjectAssert given(T actual) { * * @param the type of elements of the actual objects' array. * @param actual the actual objects' array to be validated.. - * @return the {@link AbstractObjectArrayAssert} assertion object to be used for validation. + * @return the {@link ObjectArrayAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static ProxyableObjectArrayAssert given(T[] actual) { + public static ObjectArrayAssert given(T[] actual) { return assumeThat(actual); } @@ -1343,10 +1343,10 @@ public static Object2DArrayAssert given(T[][] actual) { * * @param the type of the actual object. * @param actual the actual object to be validated. - * @return the {@link AbstractObjectAssert} assertion object to be used for validation. + * @return the {@link ObjectAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static ProxyableObjectAssert givenObject(T actual) { + public static ObjectAssert givenObject(T actual) { return assumeThat(actual); } @@ -1380,12 +1380,11 @@ public static ProxyableObjectAssert givenObject(T actual) { * * @param the type of the actual comparable value. * @param actual the actual {@link Comparable} value to be validated. - * @return the {@link AbstractComparableAssert} assertion object to be used for validation. + * @return the {@link GenericComparableAssert} assertion object to be used for validation. * @since 3.14.0 */ - @SuppressWarnings("unchecked") - public static > AbstractComparableAssert given(Comparable actual) { - // cast needed to call AbstractComparableAssert assumeThat(T actual) + public static > GenericComparableAssert given(T actual) { + // cast needed to call GenericComparableAssert assumeThat(T actual) return assumeThat((T) actual); } @@ -1411,10 +1410,10 @@ public static > AbstractComparableAssert g *} * * @param actual the actual {@link Throwable} value to be validated. - * @return the {@link AbstractThrowableAssert} assertion object to be used for validation. + * @return the {@link ThrowableAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractThrowableAssert given(Throwable actual) { + public static ThrowableAssert given(Throwable actual) { return assumeThat(actual); } @@ -1460,10 +1459,10 @@ public static > AbstractComparableAssert g *} * * @param lambda the {@link ThrowingCallable} or lambda with the code that may raise a throwable to be validated. - * @return the {@link AbstractThrowableAssert} assertion object to be used for validation. + * @return the {@link ThrowableAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractThrowableAssert givenCode(ThrowingCallable lambda) { + public static ThrowableAssert givenCode(ThrowingCallable lambda) { return assumeThatCode(lambda); } @@ -1490,10 +1489,10 @@ public static > AbstractComparableAssert g * * @param the type of elements of actual iterable value. * @param actual the actual {@link Iterable} value to be validated. - * @return the {@link AbstractIterableAssert} assertion object to be used for validation. + * @return the {@link IterableAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static ProxyableIterableAssert given(Iterable actual) { + public static IterableAssert given(Iterable actual) { return assumeThat(actual); } @@ -1520,7 +1519,7 @@ public static ProxyableIterableAssert given(Iterable the type of elements of actual iterator value. * @param actual the actual {@link Iterator} value to be validated. - * @return the {@link AbstractIteratorAssert} assertion object to be used for validation. + * @return the {@link IteratorAssert} assertion object to be used for validation. * @since 3.14.0 */ public static IteratorAssert given(Iterator actual) { @@ -1550,10 +1549,10 @@ public static IteratorAssert given(Iterator the type of elements of actual list value. * @param actual the actual {@link List} value to be validated. - * @return the {@link AbstractListAssert} assertion object to be used for validation. + * @return the {@link ListAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static FactoryBasedNavigableListAssert, List, ELEMENT, ObjectAssert> given(List actual) { + public static ListAssert given(List actual) { return assumeThat(actual); } @@ -1581,10 +1580,10 @@ public static FactoryBasedNavigableListAssert the type of keys in the actual map value. * @param the type of values in the actual map value. * @param actual the actual {@link Map} value to be validated. - * @return the {@link AbstractMapAssert} assertion object to be used for validation. + * @return the {@link MapAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractMapAssert given(Map actual) { + public static MapAssert given(Map actual) { return assumeThat(actual); } @@ -1611,10 +1610,10 @@ public static FactoryBasedNavigableListAssert the type of the value contained in the actual predicate value. * @param actual the actual {@link Predicate} value to be validated. - * @return the {@link AbstractPredicateAssert} assertion object to be used for validation. + * @return the {@link PredicateAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static ProxyablePredicateAssert given(Predicate actual) { + public static PredicateAssert given(Predicate actual) { return assumeThat(actual); } @@ -1731,7 +1730,6 @@ public static DoublePredicateAssert given(DoublePredicate actual) { * @return the {@link OptionalAssert} assertion object to be used for validation. * @since 3.14.0 */ - @SuppressWarnings("unchecked") public static OptionalAssert given(Optional actual) { return assumeThat(actual); } @@ -1846,11 +1844,10 @@ public static OptionalDoubleAssert given(OptionalDouble actual) { * * @param the type of the value contained in the actual stream value. * @param actual the actual {@link Stream} value to be validated. - * @return the {@link AbstractListAssert} assertion object to be used for validation. + * @return the {@link ListAssert} assertion object to be used for validation. * @since 3.14.0 */ - @SuppressWarnings("unchecked") - public static AbstractListAssert, ELEMENT, ObjectAssert> given(Stream actual) { + public static ListAssert given(Stream actual) { return assumeThat(actual); } @@ -1876,11 +1873,10 @@ public static AbstractListAssert, ELEMENT, *} * * @param actual the actual {@link IntStream} value to be validated. - * @return the {@link AbstractListAssert} assertion object to be used for validation. + * @return the {@link ListAssert} assertion object to be used for validation. * @since 3.14.0 */ - @SuppressWarnings("unchecked") - public static AbstractListAssert, Integer, ObjectAssert> given(IntStream actual) { + public static ListAssert given(IntStream actual) { return assumeThat(actual); } @@ -1906,10 +1902,10 @@ public static AbstractListAssert, Integer, ObjectAsse * * @param the type of the elements * @param actual the actual {@link Spliterator} value to be validated. - * @return the {@link AbstractSpliteratorAssert} assertion object to be used for validation. + * @return the {@link SpliteratorAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractSpliteratorAssert given(Spliterator actual) { + public static SpliteratorAssert given(Spliterator actual) { return assumeThat(actual); } @@ -1935,11 +1931,10 @@ public static AbstractSpliteratorAssert given(Spliterator< *} * * @param actual the actual {@link LongStream} value to be validated. - * @return the {@link AbstractListAssert} assertion object to be used for validation. + * @return the {@link ListAssert} assertion object to be used for validation. * @since 3.14.0 */ - @SuppressWarnings("unchecked") - public static AbstractListAssert, Long, ObjectAssert> given(LongStream actual) { + public static ListAssert given(LongStream actual) { return assumeThat(actual); } @@ -1965,11 +1960,10 @@ public static AbstractListAssert, Long, ObjectAssert * * @param actual the actual {@link DoubleStream} value to be validated. - * @return the {@link AbstractListAssert} assertion object to be used for validation. + * @return the {@link ListAssert} assertion object to be used for validation. * @since 3.14.0 */ - @SuppressWarnings("unchecked") - public static AbstractListAssert, Double, ObjectAssert> given(DoubleStream actual) { + public static ListAssert given(DoubleStream actual) { return assumeThat(actual); } @@ -1996,11 +1990,10 @@ public static AbstractListAssert, Double, ObjectAssert * * @param the type of the value contained in the actual future value. * @param future the {@link Future} value to be validated. - * @return the {@link AbstractFutureAssert} assertion object to be used for validation. + * @return the {@link FutureAssert} assertion object to be used for validation. * @since 3.14.0 */ - @SuppressWarnings("unchecked") - public static AbstractFutureAssert, RESULT> given(Future future) { + public static FutureAssert given(Future future) { return assumeThat(future); } @@ -2027,10 +2020,9 @@ public static AbstractListAssert, Double, ObjectAssert * * @param the type of the value contained in the actual future value. * @param future the {@link CompletableFuture} value to be validated. - * @return the {@link AbstractCompletableFutureAssert} assertion object to be used for validation. + * @return the {@link CompletableFutureAssert} assertion object to be used for validation. * @since 3.14.0 */ - @SuppressWarnings("unchecked") public static CompletableFutureAssert given(CompletableFuture future) { return assumeThat(future); } @@ -2061,10 +2053,9 @@ public static CompletableFutureAssert given(CompletableFuture the type of the value contained in the actual future value. * @param stage the {@link CompletionStage} value to be validated. - * @return the {@link AbstractCompletableFutureAssert} assertion object to be used for validation. + * @return the {@link CompletableFutureAssert} assertion object to be used for validation. * @since 3.14.0 */ - @SuppressWarnings("unchecked") public static CompletableFutureAssert given(CompletionStage stage) { return assumeThat(stage); } @@ -2192,7 +2183,6 @@ public static AtomicIntegerArrayAssert given(AtomicIntegerArray actual) { * @return the {@link AtomicIntegerFieldUpdaterAssert} assertion object to be used for validation. * @since 3.14.0 */ - @SuppressWarnings("unchecked") public static AtomicIntegerFieldUpdaterAssert given(AtomicIntegerFieldUpdater actual) { return assumeThat(actual); } @@ -2320,7 +2310,6 @@ public static AtomicLongArrayAssert given(AtomicLongArray actual) { * @return the {@link AtomicLongFieldUpdaterAssert} assertion object to be used for validation. * @since 3.14.0 */ - @SuppressWarnings("unchecked") public static AtomicLongFieldUpdaterAssert given(AtomicLongFieldUpdater actual) { return assumeThat(actual); } @@ -2351,7 +2340,6 @@ public static AtomicLongFieldUpdaterAssert given(AtomicLongFiel * @return the {@link AtomicReferenceAssert} assertion object to be used for validation. * @since 3.14.0 */ - @SuppressWarnings("unchecked") public static AtomicReferenceAssert given(AtomicReference actual) { return assumeThat(actual); } @@ -2382,7 +2370,6 @@ public static AtomicReferenceAssert given(AtomicReference * @return the {@link AtomicReferenceArrayAssert} assertion object to be used for validation. * @since 3.14.0 */ - @SuppressWarnings("unchecked") public static AtomicReferenceArrayAssert given(AtomicReferenceArray actual) { return assumeThat(actual); } @@ -2424,7 +2411,6 @@ public static AtomicReferenceArrayAssert given(AtomicReferenc * @return the {@link AtomicReferenceFieldUpdaterAssert} assertion object to be used for validation. * @since 3.14.0 */ - @SuppressWarnings("unchecked") public static AtomicReferenceFieldUpdaterAssert given(AtomicReferenceFieldUpdater actual) { return assumeThat(actual); } @@ -2455,7 +2441,6 @@ public static AtomicReferenceFieldUpdaterAssert g * @return the {@link AtomicMarkableReferenceAssert} assertion object to be used for validation. * @since 3.14.0 */ - @SuppressWarnings("unchecked") public static AtomicMarkableReferenceAssert given(AtomicMarkableReference actual) { return assumeThat(actual); } @@ -2486,7 +2471,6 @@ public static AtomicMarkableReferenceAssert given(AtomicMarkableR * @return the {@link AtomicStampedReferenceAssert} assertion object to be used for validation. * @since 3.14.0 */ - @SuppressWarnings("unchecked") public static AtomicStampedReferenceAssert given(AtomicStampedReference actual) { return assumeThat(actual); } @@ -2513,10 +2497,10 @@ public static AtomicStampedReferenceAssert given(AtomicStampedRef *} * * @param actual the actual {@link Date} value to be validated. - * @return the {@link AbstractDateAssert} assertion object to be used for validation. + * @return the {@link DateAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractDateAssert given(Date actual) { + public static DateAssert given(Date actual) { return assumeThat(actual); } @@ -2542,10 +2526,10 @@ public static AbstractDateAssert given(Date actual) { *} * * @param actual the actual {@link LocalDate} value to be validated. - * @return the {@link AbstractLocalDateAssert} assertion object to be used for validation. + * @return the {@link LocalDateAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractLocalDateAssert given(LocalDate actual) { + public static LocalDateAssert given(LocalDate actual) { return assumeThat(actual); } @@ -2571,10 +2555,10 @@ public static AbstractLocalDateAssert given(LocalDate actual) { *} * * @param actual the actual {@link LocalTime} value to be validated. - * @return the {@link AbstractLocalTimeAssert} assertion object to be used for validation. + * @return the {@link LocalTimeAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractLocalTimeAssert given(LocalTime actual) { + public static LocalTimeAssert given(LocalTime actual) { return assumeThat(actual); } @@ -2600,10 +2584,10 @@ public static AbstractLocalTimeAssert given(LocalTime actual) { *} * * @param actual the actual {@link OffsetTime} value to be validated. - * @return the {@link AbstractOffsetTimeAssert} assertion object to be used for validation. + * @return the {@link OffsetTimeAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractOffsetTimeAssert given(OffsetTime actual) { + public static OffsetTimeAssert given(OffsetTime actual) { return assumeThat(actual); } @@ -2629,10 +2613,10 @@ public static AbstractOffsetTimeAssert given(OffsetTime actual) { *} * * @param actual the actual {@link LocalDateTime} value to be validated. - * @return the {@link AbstractLocalDateTimeAssert} assertion object to be used for validation. + * @return the {@link LocalDateTimeAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractLocalDateTimeAssert given(LocalDateTime actual) { + public static LocalDateTimeAssert given(LocalDateTime actual) { return assumeThat(actual); } @@ -2658,10 +2642,10 @@ public static AbstractLocalDateTimeAssert given(LocalDateTime actual) { *} * * @param actual the actual {@link Instant} value to be validated. - * @return the {@link AbstractInstantAssert} assertion object to be used for validation. + * @return the {@link InstantAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractInstantAssert given(Instant actual) { + public static InstantAssert given(Instant actual) { return assumeThat(actual); } @@ -2672,7 +2656,7 @@ public static AbstractInstantAssert given(Instant actual) { * @return the created assertion object. * @since 3.15.0 */ - public static AbstractDurationAssert given(Duration actual) { + public static DurationAssert given(Duration actual) { return assumeThat(actual); } @@ -2683,7 +2667,7 @@ public static AbstractDurationAssert given(Duration actual) { * @return the created assertion object. * @since 3.17.0 */ - public static AbstractPeriodAssert given(Period actual) { + public static PeriodAssert given(Period actual) { return assumeThat(actual); } @@ -2709,10 +2693,10 @@ public static AbstractPeriodAssert given(Period actual) { *} * * @param actual the actual {@link OffsetDateTime} value to be validated. - * @return the {@link AbstractOffsetDateTimeAssert} assertion object to be used for validation. + * @return the {@link OffsetDateTimeAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractOffsetDateTimeAssert given(OffsetDateTime actual) { + public static OffsetDateTimeAssert given(OffsetDateTime actual) { return assumeThat(actual); } @@ -2738,10 +2722,10 @@ public static AbstractOffsetDateTimeAssert given(OffsetDateTime actual) { *} * * @param actual the actual {@link ZonedDateTime} value to be validated. - * @return the {@link AbstractZonedDateTimeAssert} assertion object to be used for validation. + * @return the {@link ZonedDateTimeAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractZonedDateTimeAssert given(ZonedDateTime actual) { + public static ZonedDateTimeAssert given(ZonedDateTime actual) { return assumeThat(actual); } @@ -2767,10 +2751,10 @@ public static AbstractZonedDateTimeAssert given(ZonedDateTime actual) { *} * * @param actual the actual {@link InputStream} value to be validated. - * @return the {@link AbstractInputStreamAssert} assertion object to be used for validation. + * @return the {@link InputStreamAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractInputStreamAssert given(InputStream actual) { + public static InputStreamAssert given(InputStream actual) { return assumeThat(actual); } @@ -2796,10 +2780,10 @@ public static AbstractZonedDateTimeAssert given(ZonedDateTime actual) { *} * * @param actual the actual {@link File} value to be validated. - * @return the {@link AbstractFileAssert} assertion object to be used for validation. + * @return the {@link FileAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractFileAssert given(File actual) { + public static FileAssert given(File actual) { return assumeThat(actual); } @@ -2825,10 +2809,10 @@ public static AbstractFileAssert given(File actual) { *} * * @param actual the actual {@link Path} value to be validated. - * @return the {@link AbstractPathAssert} assertion object to be used for validation. + * @return the {@link PathAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractPathAssert given(Path actual) { + public static PathAssert given(Path actual) { return assumeThat(actual); } @@ -2854,10 +2838,10 @@ public static AbstractPathAssert given(Path actual) { *} * * @param actual the actual {@link URI} value to be validated. - * @return the {@link AbstractUriAssert} assertion object to be used for validation. + * @return the {@link UriAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractUriAssert given(URI actual) { + public static UriAssert given(URI actual) { return assumeThat(actual); } @@ -2883,10 +2867,10 @@ public static AbstractUriAssert given(URI actual) { *} * * @param actual the actual {@link URL} value to be validated. - * @return the {@link AbstractUrlAssert} assertion object to be used for validation. + * @return the {@link UrlAssert} assertion object to be used for validation. * @since 3.14.0 */ - public static AbstractUrlAssert given(URL actual) { + public static UrlAssert given(URL actual) { return assumeThat(actual); } } diff --git a/src/main/java/org/assertj/core/api/BDDSoftAssertionsProvider.java b/src/main/java/org/assertj/core/api/BDDSoftAssertionsProvider.java index 461875c467a..0cb7b243faf 100644 --- a/src/main/java/org/assertj/core/api/BDDSoftAssertionsProvider.java +++ b/src/main/java/org/assertj/core/api/BDDSoftAssertionsProvider.java @@ -249,8 +249,8 @@ default CompletableFutureAssert then(CompletionStage ac */ @SuppressWarnings("unchecked") @CheckReturnValue - default ProxyablePredicateAssert then(Predicate actual) { - return proxy(ProxyablePredicateAssert.class, Predicate.class, actual); + default PredicateAssert then(Predicate actual) { + return proxy(PredicateAssert.class, Predicate.class, actual); } /** @@ -302,8 +302,8 @@ default LongPredicateAssert then(LongPredicate actual) { */ @SuppressWarnings("unchecked") @CheckReturnValue - default AbstractListAssert, ELEMENT, ObjectAssert> then(Stream actual) { - return proxy(ProxyableListAssert.class, Stream.class, actual); + default ListAssert then(Stream actual) { + return proxy(ListAssert.class, Stream.class, actual); } /** @@ -318,8 +318,8 @@ default AbstractListAssert, ELEMENT, Object */ @SuppressWarnings("unchecked") @CheckReturnValue - default AbstractListAssert, Double, ObjectAssert> then(DoubleStream actual) { - return proxy(ProxyableListAssert.class, DoubleStream.class, actual); + default ListAssert then(DoubleStream actual) { + return proxy(ListAssert.class, DoubleStream.class, actual); } /** @@ -334,8 +334,8 @@ default AbstractListAssert, Double, ObjectAssert, Long, ObjectAssert> then(LongStream actual) { - return proxy(ProxyableListAssert.class, LongStream.class, actual); + default ListAssert then(LongStream actual) { + return proxy(ListAssert.class, LongStream.class, actual); } /** @@ -350,8 +350,8 @@ default AbstractListAssert, Long, ObjectAssert> th */ @SuppressWarnings("unchecked") @CheckReturnValue - default AbstractListAssert, Integer, ObjectAssert> then(IntStream actual) { - return proxy(ProxyableListAssert.class, IntStream.class, actual); + default ListAssert then(IntStream actual) { + return proxy(ListAssert.class, IntStream.class, actual); } /** diff --git a/src/main/java/org/assertj/core/api/ClassAssert.java b/src/main/java/org/assertj/core/api/ClassAssert.java index f678d4e84fa..71ecabd410c 100644 --- a/src/main/java/org/assertj/core/api/ClassAssert.java +++ b/src/main/java/org/assertj/core/api/ClassAssert.java @@ -12,8 +12,6 @@ */ package org.assertj.core.api; -import java.lang.annotation.Annotation; - /** * Assertion methods for {@code Class}es. *

    @@ -29,13 +27,4 @@ public ClassAssert(Class actual) { super(actual, ClassAssert.class); } - // override method to annotate it with @SafeVarargs, we unfortunately can't do that in AbstractClassAssert as it is - // used in soft assertions which need to be able to proxy method - @SafeVarargs requiring method to be final prevents - // using proxies. - - @SafeVarargs - @Override - public final ClassAssert hasAnnotations(Class... annotations) { - return super.hasAnnotations(annotations); - } } diff --git a/src/main/java/org/assertj/core/api/Condition.java b/src/main/java/org/assertj/core/api/Condition.java index cb7e62481f9..a6bda762ab6 100644 --- a/src/main/java/org/assertj/core/api/Condition.java +++ b/src/main/java/org/assertj/core/api/Condition.java @@ -13,6 +13,8 @@ package org.assertj.core.api; import static java.util.Objects.requireNonNull; +import static org.assertj.core.api.Condition.Status.FAIL; +import static org.assertj.core.api.Condition.Status.SUCCESS; import java.util.function.Predicate; @@ -30,6 +32,24 @@ */ public class Condition implements Descriptable> { + /** + * Describes the condition status after being evaluated. + */ + public enum Status { + SUCCESS("[✓]"), FAIL("[✗]"); + + public final String label; + + Status(String label) { + this.label = label; + } + + @Override + public String toString() { + return this.label; + } + } + @VisibleForTesting Description description; @@ -115,6 +135,21 @@ public Description description() { return description; } + /** + * Returns the description of this condition with its status failed or success. + * + * @param actual the instance to evaluate the condition status against. + * @return the description of this condition with its status. + */ + public Description conditionDescriptionWithStatus(T actual) { + Status status = status(actual); + return new TextDescription(status.label + " " + description().value()); + } + + protected Status status(T actual) { + return matches(actual) ? SUCCESS : FAIL; + } + /** * Verifies that the given value satisfies this condition. * diff --git a/src/main/java/org/assertj/core/api/DefaultAssertionErrorCollector.java b/src/main/java/org/assertj/core/api/DefaultAssertionErrorCollector.java index c8b08197932..c92235e5992 100644 --- a/src/main/java/org/assertj/core/api/DefaultAssertionErrorCollector.java +++ b/src/main/java/org/assertj/core/api/DefaultAssertionErrorCollector.java @@ -12,9 +12,12 @@ */ package org.assertj.core.api; +import static java.lang.String.format; import static java.util.Collections.synchronizedList; import static java.util.Collections.unmodifiableList; +import static java.util.stream.Collectors.toList; +import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.List; import java.util.Optional; @@ -67,7 +70,9 @@ public void collectAssertionError(AssertionError error) { */ @Override public List assertionErrorsCollected() { - return delegate != null ? delegate.assertionErrorsCollected() : unmodifiableList(collectedAssertionErrors); + List errors = delegate != null ? delegate.assertionErrorsCollected() + : unmodifiableList(collectedAssertionErrors); + return decorateErrorsCollected(errors); } /** @@ -126,4 +131,87 @@ public void succeeded() { public boolean wasSuccess() { return delegate == null ? wasSuccess : delegate.wasSuccess(); } -} \ No newline at end of file + + /** + * Modifies collected errors. Override to customize modification. + * @param the supertype to use in the list return value + * @param errors list of errors to decorate + * @return decorated list + */ + protected List decorateErrorsCollected(List errors) { + return addLineNumberToErrorMessages(errors); + } + + private static List addLineNumberToErrorMessages(List errors) { + return errors.stream() + .map(DefaultAssertionErrorCollector::addLineNumberToErrorMessage) + .collect(toList()); + } + + private static T addLineNumberToErrorMessage(T error) { + StackTraceElement testStackTraceElement = getFirstStackTraceElementFromTest(error.getStackTrace()); + if (testStackTraceElement != null) { + try { + return createNewInstanceWithLineNumberInErrorMessage(error, testStackTraceElement); + } catch (@SuppressWarnings("unused") SecurityException | ReflectiveOperationException ignored) {} + } + return error; + } + + private static T createNewInstanceWithLineNumberInErrorMessage(T error, + StackTraceElement testStackTraceElement) throws ReflectiveOperationException { + @SuppressWarnings("unchecked") + Constructor constructor = (Constructor) error.getClass().getConstructor(String.class, + Throwable.class); + T errorWithLineNumber = constructor.newInstance(buildErrorMessageWithLineNumber(error.getMessage(), + testStackTraceElement), + error.getCause()); + errorWithLineNumber.setStackTrace(error.getStackTrace()); + for (Throwable suppressed : error.getSuppressed()) { + errorWithLineNumber.addSuppressed(suppressed); + } + return errorWithLineNumber; + } + + private static String buildErrorMessageWithLineNumber(String originalErrorMessage, StackTraceElement testStackTraceElement) { + String testClassName = simpleClassNameOf(testStackTraceElement); + String testName = testStackTraceElement.getMethodName(); + int lineNumber = testStackTraceElement.getLineNumber(); + return format("%s%nat %s.%s(%s.java:%s)", originalErrorMessage, testClassName, testName, testClassName, lineNumber); + } + + private static String simpleClassNameOf(StackTraceElement testStackTraceElement) { + String className = testStackTraceElement.getClassName(); + return className.substring(className.lastIndexOf('.') + 1); + } + + private static StackTraceElement getFirstStackTraceElementFromTest(StackTraceElement[] stacktrace) { + for (StackTraceElement element : stacktrace) { + String className = element.getClassName(); + if (isProxiedAssertionClass(className) + || className.startsWith("sun.reflect") + || className.startsWith("jdk.internal.reflect") + || className.startsWith("java.") + || className.startsWith("javax.") + || className.startsWith("org.junit.") + || className.startsWith("org.eclipse.jdt.internal.junit.") + || className.startsWith("org.eclipse.jdt.internal.junit4.") + || className.startsWith("org.eclipse.jdt.internal.junit5.") + || className.startsWith("com.intellij.junit5.") + || className.startsWith("com.intellij.rt.execution.junit.") + || className.startsWith("com.intellij.rt.junit.") // since IntelliJ IDEA build 193.2956.37 + || className.startsWith("org.apache.maven.surefire") + || className.startsWith("org.pitest.") + || className.startsWith("org.assertj")) { + continue; + } + return element; + } + return null; + } + + private static boolean isProxiedAssertionClass(String className) { + return className.contains("$ByteBuddy$"); + } + +} diff --git a/src/main/java/org/assertj/core/api/Descriptable.java b/src/main/java/org/assertj/core/api/Descriptable.java index 5752388c665..51b6aa4ecd5 100644 --- a/src/main/java/org/assertj/core/api/Descriptable.java +++ b/src/main/java/org/assertj/core/api/Descriptable.java @@ -46,7 +46,7 @@ public interface Descriptable { * } catch (AssertionError e) { * assertThat(e).hasMessage("[check Frodo's age]\n * expected: 33\n - * but was : 50"); + * but was: 50"); * } * * @param description the new description to set. @@ -82,7 +82,7 @@ default SELF as(String description, Object... args) { * { * assertThat(e).hasMessage("[check Frodo's age]\n * expected: 33\n - * but was : 50"); + * but was: 50"); * } * * @param descriptionSupplier the description {@link Supplier}. diff --git a/src/main/java/org/assertj/core/api/Fail.java b/src/main/java/org/assertj/core/api/Fail.java index 97f5fd9ac72..030b34f023e 100644 --- a/src/main/java/org/assertj/core/api/Fail.java +++ b/src/main/java/org/assertj/core/api/Fail.java @@ -13,7 +13,7 @@ package org.assertj.core.api; import org.assertj.core.internal.Failures; - +import org.assertj.core.util.CanIgnoreReturnValue; /** * Common failures. @@ -41,6 +41,7 @@ public static void setRemoveAssertJRelatedElementsFromStackTrace(boolean removeA * @return nothing, it's just to be used in doSomething(optional.orElse(() -> fail("boom")));. * @throws AssertionError with the given message. */ + @CanIgnoreReturnValue public static T fail(String failureMessage) { throw Failures.instance().failure(failureMessage); } @@ -54,6 +55,7 @@ public static T fail(String failureMessage) { * @return nothing, it's just to be used in doSomething(optional.orElse(() -> fail("b%s", ""oom)));. * @throws AssertionError with the given built message. */ + @CanIgnoreReturnValue public static T fail(String failureMessage, Object... args) { return fail(String.format(failureMessage, args)); } @@ -67,6 +69,7 @@ public static T fail(String failureMessage, Object... args) { * @return nothing, it's just to be used in doSomething(optional.orElse(() -> fail("boom", cause)));. * @throws AssertionError with the given message and with the {@link Throwable} that caused the failure. */ + @CanIgnoreReturnValue public static T fail(String failureMessage, Throwable realCause) { AssertionError error = Failures.instance().failure(failureMessage); error.initCause(realCause); @@ -85,6 +88,7 @@ public static T fail(String failureMessage, Throwable realCause) { * * {@link Fail#shouldHaveThrown(Class)} can be used as a replacement. */ + @CanIgnoreReturnValue public static T failBecauseExceptionWasNotThrown(Class throwableClass) { return shouldHaveThrown(throwableClass); } @@ -99,6 +103,7 @@ public static T failBecauseExceptionWasNotThrown(Class * @throws AssertionError with a message explaining that a {@link Throwable} of given class was expected to be thrown but had * not been. */ + @CanIgnoreReturnValue public static T shouldHaveThrown(Class throwableClass) { throw Failures.instance().expectedThrowableNotThrown(throwableClass); } diff --git a/src/main/java/org/assertj/core/api/FloatingPointNumberAssert.java b/src/main/java/org/assertj/core/api/FloatingPointNumberAssert.java index b45578c484b..ad9a145feab 100644 --- a/src/main/java/org/assertj/core/api/FloatingPointNumberAssert.java +++ b/src/main/java/org/assertj/core/api/FloatingPointNumberAssert.java @@ -154,6 +154,10 @@ public interface FloatingPointNumberAssert InstanceOfAssertFactory> optional /** * {@link InstanceOfAssertFactory} for a {@link BigDecimal}. */ - InstanceOfAssertFactory> BIG_DECIMAL = new InstanceOfAssertFactory<>(BigDecimal.class, + InstanceOfAssertFactory BIG_DECIMAL = new InstanceOfAssertFactory<>(BigDecimal.class, Assertions::assertThat); /** * {@link InstanceOfAssertFactory} for a {@link BigInteger}. */ - InstanceOfAssertFactory> BIG_INTEGER = new InstanceOfAssertFactory<>(BigInteger.class, + InstanceOfAssertFactory BIG_INTEGER = new InstanceOfAssertFactory<>(BigInteger.class, Assertions::assertThat); /** @@ -214,7 +214,7 @@ static InstanceOfAssertFactory> optional * * @since 3.13.2 */ - InstanceOfAssertFactory> URI_TYPE = new InstanceOfAssertFactory<>(URI.class, + InstanceOfAssertFactory URI_TYPE = new InstanceOfAssertFactory<>(URI.class, Assertions::assertThat); /** @@ -225,19 +225,19 @@ static InstanceOfAssertFactory> optional * * @since 3.13.2 */ - InstanceOfAssertFactory> URL_TYPE = new InstanceOfAssertFactory<>(URL.class, + InstanceOfAssertFactory URL_TYPE = new InstanceOfAssertFactory<>(URL.class, Assertions::assertThat); /** * {@link InstanceOfAssertFactory} for a {@code boolean} or its corresponding boxed type {@link Boolean}. */ - InstanceOfAssertFactory> BOOLEAN = new InstanceOfAssertFactory<>(Boolean.class, + InstanceOfAssertFactory BOOLEAN = new InstanceOfAssertFactory<>(Boolean.class, Assertions::assertThat); /** * {@link InstanceOfAssertFactory} for a {@code boolean} array. */ - InstanceOfAssertFactory> BOOLEAN_ARRAY = new InstanceOfAssertFactory<>(boolean[].class, + InstanceOfAssertFactory BOOLEAN_ARRAY = new InstanceOfAssertFactory<>(boolean[].class, Assertions::assertThat); /** @@ -249,13 +249,13 @@ static InstanceOfAssertFactory> optional /** * {@link InstanceOfAssertFactory} for a {@code byte} or its corresponding boxed type {@link Byte}. */ - InstanceOfAssertFactory> BYTE = new InstanceOfAssertFactory<>(Byte.class, + InstanceOfAssertFactory BYTE = new InstanceOfAssertFactory<>(Byte.class, Assertions::assertThat); /** * {@link InstanceOfAssertFactory} for a {@code byte} array. */ - InstanceOfAssertFactory> BYTE_ARRAY = new InstanceOfAssertFactory<>(byte[].class, + InstanceOfAssertFactory BYTE_ARRAY = new InstanceOfAssertFactory<>(byte[].class, Assertions::assertThat); /** @@ -267,13 +267,13 @@ static InstanceOfAssertFactory> optional /** * {@link InstanceOfAssertFactory} for a {@code char} or its corresponding boxed type {@link Character}. */ - InstanceOfAssertFactory> CHARACTER = new InstanceOfAssertFactory<>(Character.class, + InstanceOfAssertFactory CHARACTER = new InstanceOfAssertFactory<>(Character.class, Assertions::assertThat); /** * {@link InstanceOfAssertFactory} for a {@code char} array. */ - InstanceOfAssertFactory> CHAR_ARRAY = new InstanceOfAssertFactory<>(char[].class, + InstanceOfAssertFactory CHAR_ARRAY = new InstanceOfAssertFactory<>(char[].class, Assertions::assertThat); /** @@ -292,13 +292,13 @@ static InstanceOfAssertFactory> optional /** * {@link InstanceOfAssertFactory} for a {@code double} or its corresponding boxed type {@link Double}. */ - InstanceOfAssertFactory> DOUBLE = new InstanceOfAssertFactory<>(Double.class, + InstanceOfAssertFactory DOUBLE = new InstanceOfAssertFactory<>(Double.class, Assertions::assertThat); /** * {@link InstanceOfAssertFactory} for a {@code double} array. */ - InstanceOfAssertFactory> DOUBLE_ARRAY = new InstanceOfAssertFactory<>(double[].class, + InstanceOfAssertFactory DOUBLE_ARRAY = new InstanceOfAssertFactory<>(double[].class, Assertions::assertThat); /** @@ -310,7 +310,7 @@ static InstanceOfAssertFactory> optional /** * {@link InstanceOfAssertFactory} for a {@link File}. */ - InstanceOfAssertFactory> FILE = new InstanceOfAssertFactory<>(File.class, + InstanceOfAssertFactory FILE = new InstanceOfAssertFactory<>(File.class, Assertions::assertThat); /** @@ -338,19 +338,19 @@ static InstanceOfAssertFactory> future(Cla /** * {@link InstanceOfAssertFactory} for an {@link InputStream}. */ - InstanceOfAssertFactory> INPUT_STREAM = new InstanceOfAssertFactory<>(InputStream.class, + InstanceOfAssertFactory INPUT_STREAM = new InstanceOfAssertFactory<>(InputStream.class, Assertions::assertThat); /** * {@link InstanceOfAssertFactory} for a {@code float} or its corresponding boxed type {@link Float}. */ - InstanceOfAssertFactory> FLOAT = new InstanceOfAssertFactory<>(Float.class, + InstanceOfAssertFactory FLOAT = new InstanceOfAssertFactory<>(Float.class, Assertions::assertThat); /** * {@link InstanceOfAssertFactory} for a {@code float} array. */ - InstanceOfAssertFactory> FLOAT_ARRAY = new InstanceOfAssertFactory<>(float[].class, + InstanceOfAssertFactory FLOAT_ARRAY = new InstanceOfAssertFactory<>(float[].class, Assertions::assertThat); /** @@ -362,13 +362,13 @@ static InstanceOfAssertFactory> future(Cla /** * {@link InstanceOfAssertFactory} for an {@code integer} or its corresponding boxed type {@link Integer}. */ - InstanceOfAssertFactory> INTEGER = new InstanceOfAssertFactory<>(Integer.class, + InstanceOfAssertFactory INTEGER = new InstanceOfAssertFactory<>(Integer.class, Assertions::assertThat); /** * {@link InstanceOfAssertFactory} for an {@code int} array. */ - InstanceOfAssertFactory> INT_ARRAY = new InstanceOfAssertFactory<>(int[].class, + InstanceOfAssertFactory INT_ARRAY = new InstanceOfAssertFactory<>(int[].class, Assertions::assertThat); /** @@ -380,13 +380,13 @@ static InstanceOfAssertFactory> future(Cla /** * {@link InstanceOfAssertFactory} for a {@code long} or its corresponding boxed type {@link Long}. */ - InstanceOfAssertFactory> LONG = new InstanceOfAssertFactory<>(Long.class, + InstanceOfAssertFactory LONG = new InstanceOfAssertFactory<>(Long.class, Assertions::assertThat); /** * {@link InstanceOfAssertFactory} for a {@code long} array. */ - InstanceOfAssertFactory> LONG_ARRAY = new InstanceOfAssertFactory<>(long[].class, + InstanceOfAssertFactory LONG_ARRAY = new InstanceOfAssertFactory<>(long[].class, Assertions::assertThat); /** @@ -452,13 +452,13 @@ static InstanceOfAssertFactory> SHORT = new InstanceOfAssertFactory<>(Short.class, + InstanceOfAssertFactory SHORT = new InstanceOfAssertFactory<>(Short.class, Assertions::assertThat); /** * {@link InstanceOfAssertFactory} for a {@code short} array. */ - InstanceOfAssertFactory> SHORT_ARRAY = new InstanceOfAssertFactory<>(short[].class, + InstanceOfAssertFactory SHORT_ARRAY = new InstanceOfAssertFactory<>(short[].class, Assertions::assertThat); /** @@ -470,49 +470,49 @@ static InstanceOfAssertFactory> DATE = new InstanceOfAssertFactory<>(Date.class, + InstanceOfAssertFactory DATE = new InstanceOfAssertFactory<>(Date.class, Assertions::assertThat); /** * {@link InstanceOfAssertFactory} for a {@link ZonedDateTime}. */ - InstanceOfAssertFactory> ZONED_DATE_TIME = new InstanceOfAssertFactory<>(ZonedDateTime.class, + InstanceOfAssertFactory ZONED_DATE_TIME = new InstanceOfAssertFactory<>(ZonedDateTime.class, Assertions::assertThat); /** * {@link InstanceOfAssertFactory} for a {@link LocalDateTime}. */ - InstanceOfAssertFactory> LOCAL_DATE_TIME = new InstanceOfAssertFactory<>(LocalDateTime.class, + InstanceOfAssertFactory LOCAL_DATE_TIME = new InstanceOfAssertFactory<>(LocalDateTime.class, Assertions::assertThat); /** * {@link InstanceOfAssertFactory} for an {@link OffsetDateTime}. */ - InstanceOfAssertFactory> OFFSET_DATE_TIME = new InstanceOfAssertFactory<>(OffsetDateTime.class, + InstanceOfAssertFactory OFFSET_DATE_TIME = new InstanceOfAssertFactory<>(OffsetDateTime.class, Assertions::assertThat); /** * {@link InstanceOfAssertFactory} for an {@link OffsetTime}. */ - InstanceOfAssertFactory> OFFSET_TIME = new InstanceOfAssertFactory<>(OffsetTime.class, + InstanceOfAssertFactory OFFSET_TIME = new InstanceOfAssertFactory<>(OffsetTime.class, Assertions::assertThat); /** * {@link InstanceOfAssertFactory} for a {@link LocalTime}. */ - InstanceOfAssertFactory> LOCAL_TIME = new InstanceOfAssertFactory<>(LocalTime.class, + InstanceOfAssertFactory LOCAL_TIME = new InstanceOfAssertFactory<>(LocalTime.class, Assertions::assertThat); /** * {@link InstanceOfAssertFactory} for a {@link LocalDate}. */ - InstanceOfAssertFactory> LOCAL_DATE = new InstanceOfAssertFactory<>(LocalDate.class, + InstanceOfAssertFactory LOCAL_DATE = new InstanceOfAssertFactory<>(LocalDate.class, Assertions::assertThat); /** * {@link InstanceOfAssertFactory} for an {@link Instant}. */ - InstanceOfAssertFactory> INSTANT = new InstanceOfAssertFactory<>(Instant.class, + InstanceOfAssertFactory INSTANT = new InstanceOfAssertFactory<>(Instant.class, Assertions::assertThat); /** @@ -520,7 +520,7 @@ static InstanceOfAssertFactory> DURATION = new InstanceOfAssertFactory<>(Duration.class, + InstanceOfAssertFactory DURATION = new InstanceOfAssertFactory<>(Duration.class, Assertions::assertThat); /** @@ -528,7 +528,7 @@ static InstanceOfAssertFactory> PERIOD = new InstanceOfAssertFactory<>(Period.class, Assertions::assertThat); + InstanceOfAssertFactory PERIOD = new InstanceOfAssertFactory<>(Period.class, Assertions::assertThat); /** * {@link InstanceOfAssertFactory} for an {@link AtomicBoolean}. @@ -727,31 +727,31 @@ static InstanceOfAssertFactory> THROWABLE = new InstanceOfAssertFactory<>(Throwable.class, + InstanceOfAssertFactory THROWABLE = new InstanceOfAssertFactory<>(Throwable.class, Assertions::assertThat); /** * {@link InstanceOfAssertFactory} for a {@link CharSequence}. */ - InstanceOfAssertFactory> CHAR_SEQUENCE = new InstanceOfAssertFactory<>(CharSequence.class, + InstanceOfAssertFactory CHAR_SEQUENCE = new InstanceOfAssertFactory<>(CharSequence.class, Assertions::assertThat); /** * {@link InstanceOfAssertFactory} for a {@link StringBuilder}. */ - InstanceOfAssertFactory> STRING_BUILDER = new InstanceOfAssertFactory<>(StringBuilder.class, + InstanceOfAssertFactory STRING_BUILDER = new InstanceOfAssertFactory<>(StringBuilder.class, Assertions::assertThat); /** * {@link InstanceOfAssertFactory} for a {@link StringBuffer}. */ - InstanceOfAssertFactory> STRING_BUFFER = new InstanceOfAssertFactory<>(StringBuffer.class, + InstanceOfAssertFactory STRING_BUFFER = new InstanceOfAssertFactory<>(StringBuffer.class, Assertions::assertThat); /** * {@link InstanceOfAssertFactory} for a {@link String}. */ - InstanceOfAssertFactory> STRING = new InstanceOfAssertFactory<>(String.class, + InstanceOfAssertFactory STRING = new InstanceOfAssertFactory<>(String.class, Assertions::assertThat); /** @@ -863,7 +863,7 @@ static InstanceOfAssertFactory> stream(Cla /** * {@link InstanceOfAssertFactory} for a {@link Path}. */ - InstanceOfAssertFactory> PATH = new InstanceOfAssertFactory<>(Path.class, + InstanceOfAssertFactory PATH = new InstanceOfAssertFactory<>(Path.class, Assertions::assertThat); /** @@ -919,7 +919,7 @@ static InstanceOfAssertFactory> map(Class keyType * @param comparableType the comparable type instance. * @return the factory instance. */ - static > InstanceOfAssertFactory> comparable(Class comparableType) { + static > InstanceOfAssertFactory> comparable(Class comparableType) { return new InstanceOfAssertFactory<>(comparableType, Assertions::assertThat); } diff --git a/src/main/java/org/assertj/core/api/InstanceOfAssertFactory.java b/src/main/java/org/assertj/core/api/InstanceOfAssertFactory.java index 1d4f591a635..fb8d6cf06ae 100644 --- a/src/main/java/org/assertj/core/api/InstanceOfAssertFactory.java +++ b/src/main/java/org/assertj/core/api/InstanceOfAssertFactory.java @@ -36,8 +36,8 @@ public class InstanceOfAssertFactory> imp * @param assertFactory the {@code AssertFactory} to decorate. */ public InstanceOfAssertFactory(Class type, AssertFactory assertFactory) { - this.type = requireNonNull(type, shouldNotBeNull("type").create()); - this.assertFactory = requireNonNull(assertFactory, shouldNotBeNull("assertFactory").create()); + this.type = requireNonNull(type, shouldNotBeNull("type")::create); + this.assertFactory = requireNonNull(assertFactory, shouldNotBeNull("assertFactory")::create); } Class getType() { diff --git a/src/main/java/org/assertj/core/api/IterableAssert.java b/src/main/java/org/assertj/core/api/IterableAssert.java index 0ec90e00871..291f31e1ebb 100644 --- a/src/main/java/org/assertj/core/api/IterableAssert.java +++ b/src/main/java/org/assertj/core/api/IterableAssert.java @@ -15,12 +15,7 @@ import static java.util.stream.Collectors.toList; import java.util.Iterator; -import java.util.List; -import java.util.function.Consumer; -import java.util.function.Function; -import org.assertj.core.api.iterable.ThrowingExtractor; -import org.assertj.core.groups.Tuple; import org.assertj.core.util.Streams; /** @@ -54,129 +49,4 @@ static Iterable toIterable(Iterator iterator) { return Streams.stream(iterator).collect(toList()); } - @Override - @SafeVarargs - public final IterableAssert contains(ELEMENT... values) { - return super.contains(values); - } - - @Override - @SafeVarargs - public final IterableAssert containsOnly(ELEMENT... values) { - return super.containsOnly(values); - } - - @Override - @SafeVarargs - public final IterableAssert containsOnlyOnce(ELEMENT... values) { - return super.containsOnlyOnce(values); - } - - @Override - @SafeVarargs - public final IterableAssert containsExactly(ELEMENT... values) { - return super.containsExactly(values); - } - - @Override - @SafeVarargs - public final IterableAssert containsExactlyInAnyOrder(ELEMENT... values) { - return super.containsExactlyInAnyOrder(values); - } - - @Override - @SafeVarargs - public final IterableAssert containsAnyOf(ELEMENT... values) { - return super.containsAnyOf(values); - } - - @Override - @SafeVarargs - public final IterableAssert isSubsetOf(ELEMENT... values) { - return super.isSubsetOf(values); - } - - @Override - @SafeVarargs - public final IterableAssert containsSequence(ELEMENT... sequence) { - return super.containsSequence(sequence); - } - - @Override - @SafeVarargs - public final IterableAssert doesNotContainSequence(ELEMENT... sequence) { - return super.doesNotContainSequence(sequence); - } - - @Override - @SafeVarargs - public final IterableAssert containsSubsequence(ELEMENT... sequence) { - return super.containsSubsequence(sequence); - } - - @Override - @SafeVarargs - public final IterableAssert doesNotContainSubsequence(ELEMENT... sequence) { - return super.doesNotContainSubsequence(sequence); - } - - @Override - @SafeVarargs - public final IterableAssert doesNotContain(ELEMENT... values) { - return super.doesNotContain(values); - } - - @Override - @SafeVarargs - public final IterableAssert endsWith(ELEMENT first, ELEMENT... rest) { - return super.endsWith(first, rest); - } - - @Override - @SafeVarargs - public final AbstractListAssert, Object, ObjectAssert> flatExtracting(ThrowingExtractor... extractors) { - return super.flatExtracting(extractors); - } - - @Override - @SafeVarargs - public final AbstractListAssert, Object, ObjectAssert> flatMap(ThrowingExtractor... mappers) { - return super.flatMap(mappers); - } - - @Override - @SafeVarargs - public final AbstractListAssert, Object, ObjectAssert> flatExtracting(Function... extractors) { - return super.flatExtracting(extractors); - } - - @Override - @SafeVarargs - public final AbstractListAssert, Object, ObjectAssert> flatMap(Function... mappers) { - return super.flatMap(mappers); - } - - @Override - @SafeVarargs - public final AbstractListAssert, Tuple, ObjectAssert> extracting(Function... extractors) { - return super.extracting(extractors); - } - - @Override - @SafeVarargs - public final AbstractListAssert, Tuple, ObjectAssert> map(Function... mappers) { - return super.extracting(mappers); - } - - @Override - @SafeVarargs - public final IterableAssert satisfiesExactly(Consumer... requirements) { - return super.satisfiesExactly(requirements); - } - - @Override - @SafeVarargs - public final IterableAssert satisfiesExactlyInAnyOrder(Consumer... requirements) { - return super.satisfiesExactlyInAnyOrder(requirements); - } } diff --git a/src/main/java/org/assertj/core/api/Java6Assertions.java b/src/main/java/org/assertj/core/api/Java6Assertions.java index ea50248dcc5..6b147bfc3ba 100644 --- a/src/main/java/org/assertj/core/api/Java6Assertions.java +++ b/src/main/java/org/assertj/core/api/Java6Assertions.java @@ -234,7 +234,7 @@ public static AtomicStampedReferenceAssert assertThat(AtomicStamp * @param actual the actual value. * @return the created assertion object. */ - public static AbstractBigDecimalAssert assertThat(BigDecimal actual) { + public static BigDecimalAssert assertThat(BigDecimal actual) { return new BigDecimalAssert(actual); } @@ -245,7 +245,7 @@ public static AbstractBigDecimalAssert assertThat(BigDecimal actual) { * @return the created assertion object. * @since 2.7.0 / 3.7.0 */ - public static AbstractBigIntegerAssert assertThat(BigInteger actual) { + public static BigIntegerAssert assertThat(BigInteger actual) { return new BigIntegerAssert(actual); } @@ -255,7 +255,7 @@ public static AbstractBigIntegerAssert assertThat(BigInteger actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractUriAssert assertThat(URI actual) { + public static UriAssert assertThat(URI actual) { return new UriAssert(actual); } @@ -265,7 +265,7 @@ public static AbstractUriAssert assertThat(URI actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractUrlAssert assertThat(URL actual) { + public static UrlAssert assertThat(URL actual) { return new UrlAssert(actual); } @@ -275,7 +275,7 @@ public static AbstractUrlAssert assertThat(URL actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractBooleanAssert assertThat(boolean actual) { + public static BooleanAssert assertThat(boolean actual) { return new BooleanAssert(actual); } @@ -285,7 +285,7 @@ public static AbstractBooleanAssert assertThat(boolean actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractBooleanAssert assertThat(Boolean actual) { + public static BooleanAssert assertThat(Boolean actual) { return new BooleanAssert(actual); } @@ -295,7 +295,7 @@ public static AbstractBooleanAssert assertThat(Boolean actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractBooleanArrayAssert assertThat(boolean[] actual) { + public static BooleanArrayAssert assertThat(boolean[] actual) { return new BooleanArrayAssert(actual); } @@ -316,7 +316,7 @@ public static Boolean2DArrayAssert assertThat(boolean[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractByteAssert assertThat(byte actual) { + public static ByteAssert assertThat(byte actual) { return new ByteAssert(actual); } @@ -326,7 +326,7 @@ public static AbstractByteAssert assertThat(byte actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractByteAssert assertThat(Byte actual) { + public static ByteAssert assertThat(Byte actual) { return new ByteAssert(actual); } @@ -336,7 +336,7 @@ public static AbstractByteAssert assertThat(Byte actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractByteArrayAssert assertThat(byte[] actual) { + public static ByteArrayAssert assertThat(byte[] actual) { return new ByteArrayAssert(actual); } @@ -357,7 +357,7 @@ public static Byte2DArrayAssert assertThat(byte[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractCharacterAssert assertThat(char actual) { + public static CharacterAssert assertThat(char actual) { return new CharacterAssert(actual); } @@ -367,7 +367,7 @@ public static AbstractCharacterAssert assertThat(char actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractCharArrayAssert assertThat(char[] actual) { + public static CharArrayAssert assertThat(char[] actual) { return new CharArrayAssert(actual); } @@ -388,7 +388,7 @@ public static Char2DArrayAssert assertThat(char[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractCharacterAssert assertThat(Character actual) { + public static CharacterAssert assertThat(Character actual) { return new CharacterAssert(actual); } @@ -398,7 +398,7 @@ public static AbstractCharacterAssert assertThat(Character actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractClassAssert assertThat(Class actual) { + public static ClassAssert assertThat(Class actual) { return new ClassAssert(actual); } @@ -410,7 +410,7 @@ public static AbstractClassAssert assertThat(Class actual) { * @param actual the actual value. * @return the created assertion object. */ - public static > AbstractComparableAssert assertThat(T actual) { + public static > GenericComparableAssert assertThat(T actual) { return new GenericComparableAssert<>(actual); } @@ -421,7 +421,7 @@ public static > AbstractComparableAssert a * @param actual the actual value. * @return the created assertion object. */ - public static AbstractIterableAssert, T, ObjectAssert> assertThat(Iterable actual) { + public static IterableAssert assertThat(Iterable actual) { return new IterableAssert<>(actual); } @@ -444,7 +444,7 @@ public static AbstractIterableAssert, T, ObjectAsse * @param actual the actual value. * @return the created assertion object. */ - public static AbstractIteratorAssert assertThat(Iterator actual) { + public static IteratorAssert assertThat(Iterator actual) { return new IteratorAssert<>(actual); } @@ -454,7 +454,7 @@ public static AbstractIteratorAssert assertThat(Iterator * @param actual the actual value. * @return the created assertion object. */ - public static AbstractDoubleAssert assertThat(double actual) { + public static DoubleAssert assertThat(double actual) { return new DoubleAssert(actual); } @@ -464,7 +464,7 @@ public static AbstractDoubleAssert assertThat(double actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractDoubleAssert assertThat(Double actual) { + public static DoubleAssert assertThat(Double actual) { return new DoubleAssert(actual); } @@ -474,7 +474,7 @@ public static AbstractDoubleAssert assertThat(Double actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractDoubleArrayAssert assertThat(double[] actual) { + public static DoubleArrayAssert assertThat(double[] actual) { return new DoubleArrayAssert(actual); } @@ -495,7 +495,7 @@ public static Double2DArrayAssert assertThat(double[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractFileAssert assertThat(File actual) { + public static FileAssert assertThat(File actual) { return new FileAssert(actual); } @@ -508,7 +508,7 @@ public static AbstractFileAssert assertThat(File actual) { * @return the created assertion object. * @since 2.7.0 / 3.7.0 */ - public static AbstractFutureAssert, RESULT> assertThat(Future actual) { + public static FutureAssert assertThat(Future actual) { return new FutureAssert<>(actual); } @@ -518,7 +518,7 @@ public static AbstractFileAssert assertThat(File actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractInputStreamAssert assertThat(InputStream actual) { + public static InputStreamAssert assertThat(InputStream actual) { return new InputStreamAssert(actual); } @@ -528,7 +528,7 @@ public static AbstractFileAssert assertThat(File actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractFloatAssert assertThat(float actual) { + public static FloatAssert assertThat(float actual) { return new FloatAssert(actual); } @@ -538,7 +538,7 @@ public static AbstractFloatAssert assertThat(float actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractFloatAssert assertThat(Float actual) { + public static FloatAssert assertThat(Float actual) { return new FloatAssert(actual); } @@ -548,7 +548,7 @@ public static AbstractFloatAssert assertThat(Float actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractFloatArrayAssert assertThat(float[] actual) { + public static FloatArrayAssert assertThat(float[] actual) { return new FloatArrayAssert(actual); } @@ -569,7 +569,7 @@ public static Float2DArrayAssert assertThat(float[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractIntegerAssert assertThat(int actual) { + public static IntegerAssert assertThat(int actual) { return new IntegerAssert(actual); } @@ -579,7 +579,7 @@ public static AbstractIntegerAssert assertThat(int actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractIntArrayAssert assertThat(int[] actual) { + public static IntArrayAssert assertThat(int[] actual) { return new IntArrayAssert(actual); } @@ -600,7 +600,7 @@ public static Int2DArrayAssert assertThat(int[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractIntegerAssert assertThat(Integer actual) { + public static IntegerAssert assertThat(Integer actual) { return new IntegerAssert(actual); } @@ -611,7 +611,7 @@ public static AbstractIntegerAssert assertThat(Integer actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractListAssert, T, ObjectAssert> assertThat(List actual) { + public static ListAssert assertThat(List actual) { return new ListAssert<>(actual); } @@ -620,9 +620,10 @@ public static AbstractListAssert, T, ObjectAssert> a * in order to perform assertions on it. *

    * Navigational methods provided:

      - *
    • {@link AbstractIterableAssert#first() first()}
    • - *
    • {@link AbstractIterableAssert#last() last()}
    • - *
    • {@link AbstractIterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#first() first()}
    • + *
    • {@link IterableAssert#last() last()}
    • + *
    • {@link IterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#elements(int...) element(int...)}
    • *
    *

    * The available assertions after navigating to an element depend on the {@code ELEMENT_ASSERT} parameter of the given @@ -664,9 +665,10 @@ FactoryBasedNavigableIterableAssert assertTh * in order to perform assertions on it. *

    * Navigational methods provided:

      - *
    • {@link AbstractIterableAssert#first() first()}
    • - *
    • {@link AbstractIterableAssert#last() last()}
    • - *
    • {@link AbstractIterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#first() first()}
    • + *
    • {@link IterableAssert#last() last()}
    • + *
    • {@link IterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#elements(int...) element(int...)}
    • *
    *

    * The available assertions after navigating to an element depend on the given {@code assertClass} @@ -699,9 +701,10 @@ ClassBasedNavigableIterableAssert assertThat * in order to perform assertions on it. *

    * Navigational methods provided:

      - *
    • {@link AbstractIterableAssert#first() first()}
    • - *
    • {@link AbstractIterableAssert#last() last()}
    • - *
    • {@link AbstractIterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#first() first()}
    • + *
    • {@link IterableAssert#last() last()}
    • + *
    • {@link IterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#elements(int...) element(int...)}
    • *
    *

    * The available assertions after navigating to an element depend on the {@code ELEMENT_ASSERT} parameter of the given @@ -742,9 +745,10 @@ FactoryBasedNavigableListAssert assertThat(L * in order to perform assertions on it. *

    * Navigational methods provided:

      - *
    • {@link AbstractIterableAssert#first() first()}
    • - *
    • {@link AbstractIterableAssert#last() last()}
    • - *
    • {@link AbstractIterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#first() first()}
    • + *
    • {@link IterableAssert#last() last()}
    • + *
    • {@link IterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#elements(int...) element(int...)}
    • *
    *

    * The available assertions after navigating to an element depend on the given {@code assertClass} @@ -778,7 +782,7 @@ ClassBasedNavigableListAssert assertThat(Lis * @param actual the actual value. * @return the created assertion object. */ - public static AbstractLongAssert assertThat(long actual) { + public static LongAssert assertThat(long actual) { return new LongAssert(actual); } @@ -788,7 +792,7 @@ public static AbstractLongAssert assertThat(long actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractLongAssert assertThat(Long actual) { + public static LongAssert assertThat(Long actual) { return new LongAssert(actual); } @@ -798,7 +802,7 @@ public static AbstractLongAssert assertThat(Long actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractLongArrayAssert assertThat(long[] actual) { + public static LongArrayAssert assertThat(long[] actual) { return new LongArrayAssert(actual); } @@ -820,7 +824,7 @@ public static Long2DArrayAssert assertThat(long[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractObjectAssert assertThat(T actual) { + public static ObjectAssert assertThat(T actual) { return new ObjectAssert<>(actual); } @@ -902,7 +906,7 @@ public static T assertThat(final AssertProvider component) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractObjectArrayAssert assertThat(T[] actual) { + public static ObjectArrayAssert assertThat(T[] actual) { return new ObjectArrayAssert<>(actual); } @@ -939,7 +943,7 @@ public static MapAssert assertThat(Map actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractShortAssert assertThat(short actual) { + public static ShortAssert assertThat(short actual) { return new ShortAssert(actual); } @@ -949,7 +953,7 @@ public static AbstractShortAssert assertThat(short actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractShortAssert assertThat(Short actual) { + public static ShortAssert assertThat(Short actual) { return new ShortAssert(actual); } @@ -959,7 +963,7 @@ public static AbstractShortAssert assertThat(Short actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractShortArrayAssert assertThat(short[] actual) { + public static ShortArrayAssert assertThat(short[] actual) { return new ShortArrayAssert(actual); } @@ -980,7 +984,7 @@ public static Short2DArrayAssert assertThat(short[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractCharSequenceAssert assertThat(CharSequence actual) { + public static CharSequenceAssert assertThat(CharSequence actual) { return new CharSequenceAssert(actual); } @@ -991,7 +995,7 @@ public static Short2DArrayAssert assertThat(short[][] actual) { * @return the created assertion object. * @since 3.11.0 */ - public static AbstractCharSequenceAssert assertThat(StringBuilder actual) { + public static CharSequenceAssert assertThat(StringBuilder actual) { return new CharSequenceAssert(actual); } @@ -1002,7 +1006,7 @@ public static Short2DArrayAssert assertThat(short[][] actual) { * @return the created assertion object. * @since 3.11.0 */ - public static AbstractCharSequenceAssert assertThat(StringBuffer actual) { + public static CharSequenceAssert assertThat(StringBuffer actual) { return new CharSequenceAssert(actual); } @@ -1012,7 +1016,7 @@ public static Short2DArrayAssert assertThat(short[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractStringAssert assertThat(String actual) { + public static StringAssert assertThat(String actual) { return new StringAssert(actual); } @@ -1022,7 +1026,7 @@ public static AbstractStringAssert assertThat(String actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractDateAssert assertThat(Date actual) { + public static DateAssert assertThat(Date actual) { return new DateAssert(actual); } @@ -1032,7 +1036,7 @@ public static AbstractDateAssert assertThat(Date actual) { * @param actual the actual value. * @return the created {@link ThrowableAssert}. */ - public static AbstractThrowableAssert assertThat(Throwable actual) { + public static ThrowableAssert assertThat(Throwable actual) { return new ThrowableAssert(actual); } @@ -1075,7 +1079,7 @@ public static AbstractDateAssert assertThat(Date actual) { * @return The captured exception or null if none was raised by the callable. */ @CanIgnoreReturnValue - public static AbstractThrowableAssert assertThatThrownBy(ThrowingCallable shouldRaiseThrowable) { + public static ThrowableAssert assertThatThrownBy(ThrowingCallable shouldRaiseThrowable) { return new ThrowableAssert(catchThrowable(shouldRaiseThrowable)).hasBeenThrown(); } @@ -1112,7 +1116,7 @@ public static AbstractDateAssert assertThat(Date actual) { * @since 3.9.0 */ @CanIgnoreReturnValue - public static AbstractThrowableAssert assertThatThrownBy(ThrowingCallable shouldRaiseThrowable, + public static ThrowableAssert assertThatThrownBy(ThrowingCallable shouldRaiseThrowable, String description, Object... args) { return assertThat(catchThrowable(shouldRaiseThrowable)).as(description, args).hasBeenThrown(); } @@ -1164,7 +1168,7 @@ public static AbstractDateAssert assertThat(Date actual) { * @return The captured exception or null if none was raised by the callable. * @since 3.7.0 */ - public static AbstractThrowableAssert assertThatCode(ThrowingCallable shouldRaiseOrNotThrowable) { + public static ThrowableAssert assertThatCode(ThrowingCallable shouldRaiseOrNotThrowable) { return assertThat(catchThrowable(shouldRaiseOrNotThrowable)); } @@ -1185,7 +1189,7 @@ public static AbstractDateAssert assertThat(Date actual) { * @return the created assertion object. * @since 3.12.0 */ - public AbstractObjectAssert assertThatObject(T actual) { + public ObjectAssert assertThatObject(T actual) { return assertThat(actual); } diff --git a/src/main/java/org/assertj/core/api/Java6BDDAssertions.java b/src/main/java/org/assertj/core/api/Java6BDDAssertions.java index 766d39bbbc4..3b2bf90f6f8 100644 --- a/src/main/java/org/assertj/core/api/Java6BDDAssertions.java +++ b/src/main/java/org/assertj/core/api/Java6BDDAssertions.java @@ -202,7 +202,7 @@ public static AtomicStampedReferenceAssert then(AtomicStampedRefe * @param actual the actual value. * @return the created assertion object. */ - public static AbstractBigDecimalAssert then(BigDecimal actual) { + public static BigDecimalAssert then(BigDecimal actual) { return assertThat(actual); } @@ -213,7 +213,7 @@ public static AbstractBigDecimalAssert then(BigDecimal actual) { * @return the created assertion object. * @since 2.7.0 / 3.7.0 */ - public static AbstractBigIntegerAssert then(BigInteger actual) { + public static BigIntegerAssert then(BigInteger actual) { return assertThat(actual); } @@ -223,7 +223,7 @@ public static AbstractBigIntegerAssert then(BigInteger actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractBooleanAssert then(boolean actual) { + public static BooleanAssert then(boolean actual) { return assertThat(actual); } @@ -233,7 +233,7 @@ public static AbstractBooleanAssert then(boolean actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractBooleanAssert then(Boolean actual) { + public static BooleanAssert then(Boolean actual) { return assertThat(actual); } @@ -243,7 +243,7 @@ public static AbstractBooleanAssert then(Boolean actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractBooleanArrayAssert then(boolean[] actual) { + public static BooleanArrayAssert then(boolean[] actual) { return assertThat(actual); } @@ -264,7 +264,7 @@ public static Boolean2DArrayAssert then(boolean[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractByteAssert then(byte actual) { + public static ByteAssert then(byte actual) { return assertThat(actual); } @@ -274,7 +274,7 @@ public static AbstractByteAssert then(byte actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractByteAssert then(Byte actual) { + public static ByteAssert then(Byte actual) { return assertThat(actual); } @@ -284,7 +284,7 @@ public static AbstractByteAssert then(Byte actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractByteArrayAssert then(byte[] actual) { + public static ByteArrayAssert then(byte[] actual) { return assertThat(actual); } @@ -305,7 +305,7 @@ public static Byte2DArrayAssert then(byte[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractCharacterAssert then(char actual) { + public static CharacterAssert then(char actual) { return assertThat(actual); } @@ -315,7 +315,7 @@ public static AbstractCharacterAssert then(char actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractCharArrayAssert then(char[] actual) { + public static CharArrayAssert then(char[] actual) { return assertThat(actual); } @@ -336,7 +336,7 @@ public static Char2DArrayAssert then(char[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractCharacterAssert then(Character actual) { + public static CharacterAssert then(Character actual) { return assertThat(actual); } @@ -346,7 +346,7 @@ public static AbstractCharacterAssert then(Character actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractClassAssert then(Class actual) { + public static ClassAssert then(Class actual) { return assertThat(actual); } @@ -358,7 +358,7 @@ public static AbstractClassAssert then(Class actual) { * @param actual the actual value. * @return the created assertion object. */ - public static > AbstractComparableAssert then(T actual) { + public static > GenericComparableAssert then(T actual) { return assertThat(actual); } @@ -369,7 +369,7 @@ public static > AbstractComparableAssert t * @param actual the actual value. * @return the created assertion object. */ - public static AbstractIterableAssert, T, ObjectAssert> then(Iterable actual) { + public static IterableAssert then(Iterable actual) { return assertThat(actual); } @@ -392,7 +392,7 @@ public static AbstractIterableAssert, T, ObjectAsse * @param actual the actual value. * @return the created assertion object. */ - public static AbstractIteratorAssert then(Iterator actual) { + public static IteratorAssert then(Iterator actual) { return assertThat(actual); } @@ -401,9 +401,10 @@ public static AbstractIteratorAssert then(Iterator actual * in order to perform assertions on it. *

    * Navigational methods provided:

      - *
    • {@link AbstractIterableAssert#first() first()}
    • - *
    • {@link AbstractIterableAssert#last() last()}
    • - *
    • {@link AbstractIterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#first() first()}
    • + *
    • {@link IterableAssert#last() last()}
    • + *
    • {@link IterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#elements(int...) element(int...)}
    • *
    *

    * The available assertions after navigating to an element depend on the {@code ELEMENT_ASSERT} parameter of the given @@ -444,9 +445,10 @@ FactoryBasedNavigableIterableAssert then(Ite * in order to perform assertions on it. *

    * Navigational methods provided:

      - *
    • {@link AbstractIterableAssert#first() first()}
    • - *
    • {@link AbstractIterableAssert#last() last()}
    • - *
    • {@link AbstractIterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#first() first()}
    • + *
    • {@link IterableAssert#last() last()}
    • + *
    • {@link IterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#elements(int...) element(int...)}
    • *
    *

    * The available assertions after navigating to an element depend on the given {@code assertClass} @@ -478,9 +480,10 @@ ClassBasedNavigableIterableAssert then(ACTUA * in order to perform assertions on it. *

    * Navigational methods provided:

      - *
    • {@link AbstractIterableAssert#first() first()}
    • - *
    • {@link AbstractIterableAssert#last() last()}
    • - *
    • {@link AbstractIterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#first() first()}
    • + *
    • {@link IterableAssert#last() last()}
    • + *
    • {@link IterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#elements(int...) element(int...)}
    • *
    *

    * The available assertions after navigating to an element depend on the {@code ELEMENT_ASSERT} parameter of the given @@ -520,9 +523,10 @@ FactoryBasedNavigableListAssert then(List * Navigational methods provided:

      - *
    • {@link AbstractIterableAssert#first() first()}
    • - *
    • {@link AbstractIterableAssert#last() last()}
    • - *
    • {@link AbstractIterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#first() first()}
    • + *
    • {@link IterableAssert#last() last()}
    • + *
    • {@link IterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#elements(int...) element(int...)}
    • *
    *

    * The available assertions after navigating to an element depend on the given {@code assertClass} @@ -557,7 +561,7 @@ ClassBasedNavigableListAssert then(List then(double actual) { + public static DoubleAssert then(double actual) { return assertThat(actual); } @@ -567,7 +571,7 @@ public static AbstractDoubleAssert then(double actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractDoubleAssert then(Double actual) { + public static DoubleAssert then(Double actual) { return assertThat(actual); } @@ -577,7 +581,7 @@ public static AbstractDoubleAssert then(Double actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractDoubleArrayAssert then(double[] actual) { + public static DoubleArrayAssert then(double[] actual) { return assertThat(actual); } @@ -598,7 +602,7 @@ public static Double2DArrayAssert then(double[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractFileAssert then(File actual) { + public static FileAssert then(File actual) { return assertThat(actual); } @@ -610,7 +614,7 @@ public static AbstractFileAssert then(File actual) { * @return the created assertion object * @since 2.7.0 / 3.7.0 */ - public static AbstractFutureAssert, RESULT> then(Future actual) { + public static FutureAssert then(Future actual) { return assertThat(actual); } @@ -620,7 +624,7 @@ public static AbstractFileAssert then(File actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractInputStreamAssert then(InputStream actual) { + public static InputStreamAssert then(InputStream actual) { return assertThat(actual); } @@ -630,7 +634,7 @@ public static AbstractFileAssert then(File actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractFloatAssert then(float actual) { + public static FloatAssert then(float actual) { return assertThat(actual); } @@ -640,7 +644,7 @@ public static AbstractFloatAssert then(float actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractFloatAssert then(Float actual) { + public static FloatAssert then(Float actual) { return assertThat(actual); } @@ -650,7 +654,7 @@ public static AbstractFloatAssert then(Float actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractFloatArrayAssert then(float[] actual) { + public static FloatArrayAssert then(float[] actual) { return assertThat(actual); } @@ -660,7 +664,7 @@ public static AbstractFloatArrayAssert then(float[] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractIntegerAssert then(int actual) { + public static IntegerAssert then(int actual) { return assertThat(actual); } @@ -670,7 +674,7 @@ public static AbstractIntegerAssert then(int actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractIntArrayAssert then(int[] actual) { + public static IntArrayAssert then(int[] actual) { return assertThat(actual); } @@ -701,7 +705,7 @@ public static Float2DArrayAssert then(float[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractIntegerAssert then(Integer actual) { + public static IntegerAssert then(Integer actual) { return assertThat(actual); } @@ -712,7 +716,7 @@ public static AbstractIntegerAssert then(Integer actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractListAssert, T, ObjectAssert> then(List actual) { + public static ListAssert then(List actual) { return assertThat(actual); } @@ -722,7 +726,7 @@ public static AbstractListAssert, T, ObjectAssert> t * @param actual the actual value. * @return the created assertion object. */ - public static AbstractLongAssert then(long actual) { + public static LongAssert then(long actual) { return assertThat(actual); } @@ -732,7 +736,7 @@ public static AbstractLongAssert then(long actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractLongAssert then(Long actual) { + public static LongAssert then(Long actual) { return assertThat(actual); } @@ -742,7 +746,7 @@ public static AbstractLongAssert then(Long actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractLongArrayAssert then(long[] actual) { + public static LongArrayAssert then(long[] actual) { return assertThat(actual); } @@ -764,7 +768,7 @@ public static Long2DArrayAssert then(long[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractObjectAssert then(T actual) { + public static ObjectAssert then(T actual) { return assertThat(actual); } @@ -775,7 +779,7 @@ public static AbstractObjectAssert then(T actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractObjectArrayAssert then(T[] actual) { + public static ObjectArrayAssert then(T[] actual) { return assertThat(actual); } @@ -809,7 +813,7 @@ public static MapAssert then(Map actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractShortAssert then(short actual) { + public static ShortAssert then(short actual) { return assertThat(actual); } @@ -819,7 +823,7 @@ public static AbstractShortAssert then(short actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractShortAssert then(Short actual) { + public static ShortAssert then(Short actual) { return assertThat(actual); } @@ -829,7 +833,7 @@ public static AbstractShortAssert then(Short actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractShortArrayAssert then(short[] actual) { + public static ShortArrayAssert then(short[] actual) { return assertThat(actual); } @@ -850,7 +854,7 @@ public static Short2DArrayAssert then(short[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractCharSequenceAssert then(CharSequence actual) { + public static CharSequenceAssert then(CharSequence actual) { return assertThat(actual); } @@ -861,7 +865,7 @@ public static Short2DArrayAssert then(short[][] actual) { * @return the created assertion object. * @since 3.11.0 */ - public static AbstractCharSequenceAssert then(StringBuilder actual) { + public static CharSequenceAssert then(StringBuilder actual) { return assertThat(actual); } @@ -872,7 +876,7 @@ public static Short2DArrayAssert then(short[][] actual) { * @return the created assertion object. * @since 3.11.0 */ - public static AbstractCharSequenceAssert then(StringBuffer actual) { + public static CharSequenceAssert then(StringBuffer actual) { return assertThat(actual); } @@ -882,7 +886,7 @@ public static Short2DArrayAssert then(short[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractStringAssert then(String actual) { + public static StringAssert then(String actual) { return assertThat(actual); } @@ -892,7 +896,7 @@ public static AbstractStringAssert then(String actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractDateAssert then(Date actual) { + public static DateAssert then(Date actual) { return assertThat(actual); } @@ -902,7 +906,7 @@ public static AbstractDateAssert then(Date actual) { * @param actual the actual value. * @return the created assertion Throwable. */ - public static AbstractThrowableAssert then(Throwable actual) { + public static ThrowableAssert then(Throwable actual) { return assertThat(actual); } @@ -947,7 +951,7 @@ public static AbstractDateAssert then(Date actual) { * @return The captured exception or null if none was raised by the callable. */ @CanIgnoreReturnValue - public static AbstractThrowableAssert thenThrownBy(ThrowingCallable shouldRaiseThrowable) { + public static ThrowableAssert thenThrownBy(ThrowingCallable shouldRaiseThrowable) { return Assertions.assertThatThrownBy(shouldRaiseThrowable); } @@ -984,7 +988,7 @@ public static AbstractDateAssert then(Date actual) { * @since 3.9.0 */ @CanIgnoreReturnValue - public static AbstractThrowableAssert thenThrownBy(ThrowingCallable shouldRaiseThrowable, + public static ThrowableAssert thenThrownBy(ThrowingCallable shouldRaiseThrowable, String description, Object... args) { return assertThat(catchThrowable(shouldRaiseThrowable)).as(description, args).hasBeenThrown(); } @@ -1024,7 +1028,7 @@ public static AbstractDateAssert then(Date actual) { * @return The captured exception or null if none was raised by the callable. * @since 3.7.0 */ - public AbstractThrowableAssert thenCode(ThrowingCallable shouldRaiseOrNotThrowable) { + public ThrowableAssert thenCode(ThrowingCallable shouldRaiseOrNotThrowable) { return then(catchThrowable(shouldRaiseOrNotThrowable)); } @@ -1034,7 +1038,7 @@ public static AbstractDateAssert then(Date actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractUriAssert then(URI actual) { + public static UriAssert then(URI actual) { return assertThat(actual); } @@ -1044,7 +1048,7 @@ public static AbstractUriAssert then(URI actual) { * @param actual the actual value. * @return the created assertion object. */ - public static AbstractUrlAssert then(URL actual) { + public static UrlAssert then(URL actual) { return assertThat(actual); } @@ -1140,7 +1144,7 @@ protected Java6BDDAssertions() {} * @return the created assertion object. * @since 3.12.0 */ - public static AbstractObjectAssert thenObject(T actual) { + public static ObjectAssert thenObject(T actual) { return then(actual); } } diff --git a/src/main/java/org/assertj/core/api/Java6BDDSoftAssertionsProvider.java b/src/main/java/org/assertj/core/api/Java6BDDSoftAssertionsProvider.java index 96197f6ace2..fa9ed711fd5 100644 --- a/src/main/java/org/assertj/core/api/Java6BDDSoftAssertionsProvider.java +++ b/src/main/java/org/assertj/core/api/Java6BDDSoftAssertionsProvider.java @@ -205,8 +205,8 @@ default CharacterAssert then(Character actual) { * @param actual the actual value. * @return the created assertion object. */ - default ProxyableClassAssert then(Class actual) { - return proxy(ProxyableClassAssert.class, Class.class, actual); + default ClassAssert then(Class actual) { + return proxy(ClassAssert.class, Class.class, actual); } /** @@ -218,7 +218,7 @@ default ProxyableClassAssert then(Class actual) { * @return the created assertion object. */ @SuppressWarnings("unchecked") - default > AbstractComparableAssert then(T actual) { + default > GenericComparableAssert then(T actual) { return proxy(GenericComparableAssert.class, Comparable.class, actual); } @@ -230,14 +230,14 @@ default > AbstractComparableAssert then(T * @return the created assertion object. */ @SuppressWarnings("unchecked") - default ProxyableIterableAssert then(Iterable actual) { - return proxy(ProxyableIterableAssert.class, Iterable.class, actual); + default IterableAssert then(Iterable actual) { + return proxy(IterableAssert.class, Iterable.class, actual); } /** * Creates a new instance of {@link IteratorAssert}. *

    - * This is a breaking change in version 3.12.0: this method used to return an {@link ProxyableIterableAssert}. + * This is a breaking change in version 3.12.0: this method used to return an {@link IterableAssert}. * * @param the type of elements. * @param actual the actual value. @@ -412,8 +412,8 @@ default IntegerAssert then(Integer actual) { * @return the created assertion object. */ @SuppressWarnings("unchecked") - default ProxyableListAssert then(List actual) { - return proxy(ProxyableListAssert.class, List.class, actual); + default ListAssert then(List actual) { + return proxy(ListAssert.class, List.class, actual); } /** @@ -465,8 +465,8 @@ default Long2DArrayAssert then(long[][] actual) { * @return the created assertion object. */ @SuppressWarnings("unchecked") - default ProxyableObjectAssert then(T actual) { - return proxy(ProxyableObjectAssert.class, Object.class, actual); + default ObjectAssert then(T actual) { + return proxy(ObjectAssert.class, Object.class, actual); } /** @@ -477,8 +477,8 @@ default ProxyableObjectAssert then(T actual) { * @return the created assertion object. */ @SuppressWarnings("unchecked") - default ProxyableObjectArrayAssert then(T[] actual) { - return proxy(ProxyableObjectArrayAssert.class, Object[].class, actual); + default ObjectArrayAssert then(T[] actual) { + return proxy(ObjectArrayAssert.class, Object[].class, actual); } /** @@ -505,8 +505,8 @@ default Object2DArrayAssert then(T[][] actual) { * @return the created assertion object. */ @SuppressWarnings("unchecked") - default ProxyableMapAssert then(Map actual) { - return proxy(ProxyableMapAssert.class, Map.class, actual); + default MapAssert then(Map actual) { + return proxy(MapAssert.class, Map.class, actual); } /** @@ -802,7 +802,7 @@ default ThrowableAssert then(Throwable actual) { * @return The captured exception or null if none was raised by the callable. */ @CanIgnoreReturnValue - default AbstractThrowableAssert thenThrownBy(ThrowingCallable shouldRaiseThrowable) { + default ThrowableAssert thenThrownBy(ThrowingCallable shouldRaiseThrowable) { return then(catchThrowable(shouldRaiseThrowable)).hasBeenThrown(); } @@ -840,7 +840,7 @@ default ThrowableAssert then(Throwable actual) { * @since 3.9.0 */ @CanIgnoreReturnValue - default AbstractThrowableAssert thenThrownBy(ThrowingCallable shouldRaiseThrowable, + default ThrowableAssert thenThrownBy(ThrowingCallable shouldRaiseThrowable, String description, Object... args) { return then(catchThrowable(shouldRaiseThrowable)).as(description, args).hasBeenThrown(); } @@ -880,7 +880,7 @@ default ThrowableAssert then(Throwable actual) { * @return The captured exception or null if none was raised by the callable. * @since 3.7.0 */ - default AbstractThrowableAssert thenCode(ThrowingCallable shouldRaiseOrNotThrowable) { + default ThrowableAssert thenCode(ThrowingCallable shouldRaiseOrNotThrowable) { return then(catchThrowable(shouldRaiseOrNotThrowable)); } @@ -905,7 +905,7 @@ default ThrowableAssert then(Throwable actual) { * @return the created assertion object. * @since 3.12.0 */ - default ProxyableObjectAssert thenObject(T actual) { + default ObjectAssert thenObject(T actual) { return then(actual); } @@ -925,7 +925,7 @@ default UriAssert then(URI actual) { * @param actual the actual value. * @return the created assertion object. */ - default AbstractUrlAssert then(URL actual) { + default UrlAssert then(URL actual) { return proxy(UrlAssert.class, URL.class, actual); } diff --git a/src/main/java/org/assertj/core/api/Java6StandardSoftAssertionsProvider.java b/src/main/java/org/assertj/core/api/Java6StandardSoftAssertionsProvider.java index 8ca813c5314..014ae6246c8 100644 --- a/src/main/java/org/assertj/core/api/Java6StandardSoftAssertionsProvider.java +++ b/src/main/java/org/assertj/core/api/Java6StandardSoftAssertionsProvider.java @@ -203,8 +203,8 @@ default CharacterAssert assertThat(Character actual) { * @param actual the actual value. * @return the created assertion object. */ - default ProxyableClassAssert assertThat(Class actual) { - return proxy(ProxyableClassAssert.class, Class.class, actual); + default ClassAssert assertThat(Class actual) { + return proxy(ClassAssert.class, Class.class, actual); } /** @@ -216,7 +216,7 @@ default ProxyableClassAssert assertThat(Class actual) { * @return the created assertion object. */ @SuppressWarnings("unchecked") - default > AbstractComparableAssert assertThat(T actual) { + default > GenericComparableAssert assertThat(T actual) { return proxy(GenericComparableAssert.class, Comparable.class, actual); } @@ -230,14 +230,14 @@ default > AbstractComparableAssert assertT * @return the created assertion object. */ @SuppressWarnings("unchecked") - default ProxyableIterableAssert assertThat(Iterable actual) { - return proxy(ProxyableIterableAssert.class, Iterable.class, actual); + default IterableAssert assertThat(Iterable actual) { + return proxy(IterableAssert.class, Iterable.class, actual); } /** * Creates a new instance of {@link IteratorAssert}. *

    - * This is a breaking change in version 3.12.0: this method used to return an {@link ProxyableIterableAssert}. + * This is a breaking change in version 3.12.0: this method used to return an {@link IterableAssert}. * * @param the actual element's type. * @param actual the actual value. @@ -413,8 +413,8 @@ default IntegerAssert assertThat(Integer actual) { * @return the created assertion object. */ @SuppressWarnings("unchecked") - default ProxyableListAssert assertThat(List actual) { - return proxy(ProxyableListAssert.class, List.class, actual); + default ListAssert assertThat(List actual) { + return proxy(ListAssert.class, List.class, actual); } /** @@ -466,8 +466,8 @@ default Long2DArrayAssert assertThat(long[][] actual) { * @return the created assertion object. */ @SuppressWarnings("unchecked") - default ProxyableObjectAssert assertThat(T actual) { - return proxy(ProxyableObjectAssert.class, Object.class, actual); + default ObjectAssert assertThat(T actual) { + return proxy(ObjectAssert.class, Object.class, actual); } /** @@ -478,8 +478,8 @@ default ProxyableObjectAssert assertThat(T actual) { * @return the created assertion object. */ @SuppressWarnings("unchecked") - default ProxyableObjectArrayAssert assertThat(T[] actual) { - return proxy(ProxyableObjectArrayAssert.class, Object[].class, actual); + default ObjectArrayAssert assertThat(T[] actual) { + return proxy(ObjectArrayAssert.class, Object[].class, actual); } /** @@ -506,8 +506,8 @@ default Object2DArrayAssert assertThat(T[][] actual) { * @return the created assertion object. */ @SuppressWarnings("unchecked") - default ProxyableMapAssert assertThat(Map actual) { - return proxy(ProxyableMapAssert.class, Map.class, actual); + default MapAssert assertThat(Map actual) { + return proxy(MapAssert.class, Map.class, actual); } /** @@ -784,7 +784,7 @@ default ThrowableAssert assertThat(Throwable actual) { * @return The captured exception or null if none was raised by the callable. */ @CanIgnoreReturnValue - default AbstractThrowableAssert assertThatThrownBy(ThrowingCallable shouldRaiseThrowable) { + default ThrowableAssert assertThatThrownBy(ThrowingCallable shouldRaiseThrowable) { return assertThat(catchThrowable(shouldRaiseThrowable)).hasBeenThrown(); } @@ -822,7 +822,7 @@ default ThrowableAssert assertThat(Throwable actual) { * @since 3.9.0 */ @CanIgnoreReturnValue - default AbstractThrowableAssert assertThatThrownBy(ThrowingCallable shouldRaiseThrowable, + default ThrowableAssert assertThatThrownBy(ThrowingCallable shouldRaiseThrowable, String description, Object... args) { return assertThat(catchThrowable(shouldRaiseThrowable)).as(description, args).hasBeenThrown(); } @@ -868,7 +868,7 @@ default ThrowableAssert assertThat(Throwable actual) { * @return The captured exception or null if none was raised by the callable. * @since 3.7.0 */ - default AbstractThrowableAssert assertThatCode(ThrowingCallable shouldRaiseOrNotThrowable) { + default ThrowableAssert assertThatCode(ThrowingCallable shouldRaiseOrNotThrowable) { return assertThat(catchThrowable(shouldRaiseOrNotThrowable)); } @@ -893,7 +893,7 @@ default ThrowableAssert assertThat(Throwable actual) { * @return the created assertion object. * @since 3.12.0 */ - default ProxyableObjectAssert assertThatObject(T actual) { + default ObjectAssert assertThatObject(T actual) { return assertThat(actual); } @@ -913,7 +913,7 @@ default UriAssert assertThat(URI actual) { * @param actual the actual value. * @return the created assertion object. */ - default AbstractUrlAssert assertThat(URL actual) { + default UrlAssert assertThat(URL actual) { return proxy(UrlAssert.class, URL.class, actual); } } diff --git a/src/main/java/org/assertj/core/api/ListAssert.java b/src/main/java/org/assertj/core/api/ListAssert.java index 61d30780d4c..29f2e0e37f9 100644 --- a/src/main/java/org/assertj/core/api/ListAssert.java +++ b/src/main/java/org/assertj/core/api/ListAssert.java @@ -19,16 +19,12 @@ import java.util.AbstractList; import java.util.Iterator; import java.util.List; -import java.util.function.Consumer; -import java.util.function.Function; import java.util.stream.BaseStream; import java.util.stream.DoubleStream; import java.util.stream.IntStream; import java.util.stream.LongStream; import java.util.stream.Stream; -import org.assertj.core.api.iterable.ThrowingExtractor; -import org.assertj.core.groups.Tuple; import org.assertj.core.internal.Failures; import org.assertj.core.util.VisibleForTesting; @@ -175,10 +171,11 @@ public ListAssert isNotSameAs(Object expected) { } @Override - @SafeVarargs - public final ListAssert startsWith(ELEMENT... sequence) { + protected ListAssert startsWithForProxy(ELEMENT[] sequence) { if (!(actual instanceof ListFromStream)) { - return super.startsWith(sequence); + // don't call super.startsWith(sequence) which would lead to a stack overflow + iterables.assertStartsWith(info, actual, sequence); + return myself; } objects.assertNotNull(info, actual); checkIsNotNull(sequence); @@ -246,130 +243,4 @@ public ELEMENT get(int index) { } - @Override - @SafeVarargs - public final ListAssert contains(ELEMENT... values) { - return super.contains(values); - } - - @Override - @SafeVarargs - public final ListAssert containsOnly(ELEMENT... values) { - return super.containsOnly(values); - } - - @Override - @SafeVarargs - public final ListAssert containsOnlyOnce(ELEMENT... values) { - return super.containsOnlyOnce(values); - } - - @Override - @SafeVarargs - public final ListAssert containsExactly(ELEMENT... values) { - return super.containsExactly(values); - } - - @Override - @SafeVarargs - public final ListAssert containsExactlyInAnyOrder(ELEMENT... values) { - return super.containsExactlyInAnyOrder(values); - } - - @Override - @SafeVarargs - public final ListAssert containsAnyOf(ELEMENT... values) { - return super.containsAnyOf(values); - } - - @Override - @SafeVarargs - public final ListAssert isSubsetOf(ELEMENT... values) { - return super.isSubsetOf(values); - } - - @Override - @SafeVarargs - public final ListAssert containsSequence(ELEMENT... sequence) { - return super.containsSequence(sequence); - } - - @Override - @SafeVarargs - public final ListAssert doesNotContainSequence(ELEMENT... sequence) { - return super.doesNotContainSequence(sequence); - } - - @Override - @SafeVarargs - public final ListAssert containsSubsequence(ELEMENT... sequence) { - return super.containsSubsequence(sequence); - } - - @Override - @SafeVarargs - public final ListAssert doesNotContainSubsequence(ELEMENT... sequence) { - return super.doesNotContainSubsequence(sequence); - } - - @Override - @SafeVarargs - public final ListAssert doesNotContain(ELEMENT... values) { - return super.doesNotContain(values); - } - - @Override - @SafeVarargs - public final ListAssert endsWith(ELEMENT first, ELEMENT... rest) { - return super.endsWith(first, rest); - } - - @Override - @SafeVarargs - public final AbstractListAssert, Tuple, ObjectAssert> extracting(Function... extractors) { - return super.extracting(extractors); - } - - @Override - @SafeVarargs - public final AbstractListAssert, Tuple, ObjectAssert> map(Function... mappers) { - return super.map(mappers); - } - - @Override - @SafeVarargs - public final AbstractListAssert, Object, ObjectAssert> flatExtracting(ThrowingExtractor... extractors) { - return super.flatExtracting(extractors); - } - - @Override - @SafeVarargs - public final AbstractListAssert, Object, ObjectAssert> flatMap(ThrowingExtractor... mappers) { - return super.flatMap(mappers); - } - - @Override - @SafeVarargs - public final AbstractListAssert, Object, ObjectAssert> flatExtracting(Function... extractors) { - return super.flatExtracting(extractors); - } - - @Override - @SafeVarargs - public final AbstractListAssert, Object, ObjectAssert> flatMap(Function... mappers) { - return super.flatMap(mappers); - } - - @Override - @SafeVarargs - public final ListAssert satisfiesExactly(Consumer... requirements) { - return super.satisfiesExactly(requirements); - } - - @Override - @SafeVarargs - public final ListAssert satisfiesExactlyInAnyOrder(Consumer... requirements) { - return super.satisfiesExactlyInAnyOrder(requirements); - } - } diff --git a/src/main/java/org/assertj/core/api/MapAssert.java b/src/main/java/org/assertj/core/api/MapAssert.java index 74b5d13c845..dde2fc43a30 100644 --- a/src/main/java/org/assertj/core/api/MapAssert.java +++ b/src/main/java/org/assertj/core/api/MapAssert.java @@ -12,11 +12,7 @@ */ package org.assertj.core.api; -import java.util.List; import java.util.Map; -import java.util.function.Function; - -import org.assertj.core.groups.Tuple; /** * Assertions for {@link Map}s. @@ -36,80 +32,4 @@ public MapAssert(Map actual) { super(actual, MapAssert.class); } - // override methods to annotate them with @SafeVarargs, we unfortunately can't do that in AbstractMapAssert as it is - // used in soft assertions which need to be able to proxy method - @SafeVarargs requiring method to be final prevents - // using proxies. - - @SafeVarargs - @Override - public final MapAssert contains(Map.Entry... entries) { - return super.contains(entries); - } - - @SafeVarargs - @Override - public final MapAssert containsAnyOf(Map.Entry... entries) { - return super.containsAnyOf(entries); - } - - @SafeVarargs - @Override - public final MapAssert containsOnly(Map.Entry... entries) { - return super.containsOnly(entries); - } - - @SafeVarargs - @Override - public final MapAssert containsExactly(Map.Entry... entries) { - return super.containsExactly(entries); - } - - @SafeVarargs - @Override - public final MapAssert containsKeys(KEY... keys) { - return super.containsKeys(keys); - } - - @SafeVarargs - @Override - public final MapAssert containsOnlyKeys(KEY... keys) { - return super.containsOnlyKeys(keys); - } - - @SafeVarargs - @Override - public final MapAssert containsValues(VALUE... values) { - return super.containsValues(values); - } - - @SafeVarargs - @Override - public final MapAssert doesNotContainKeys(KEY... keys) { - return super.doesNotContainKeys(keys); - } - - @SafeVarargs - @Override - public final MapAssert doesNotContain(Map.Entry... entries) { - return super.doesNotContain(entries); - } - - @SafeVarargs - @Override - public final AbstractListAssert, Object, ObjectAssert> extracting(Function, ?>... extractors) { - return super.extracting(extractors); - } - - @SafeVarargs - @Override - public final AbstractListAssert, VALUE, ObjectAssert> extractingByKeys(KEY... keys) { - return super.extractingByKeys(keys); - } - - @SafeVarargs - @Override - public final AbstractListAssert, Tuple, ObjectAssert> extractingFromEntries(Function, Object>... extractors) { - return super.extractingFromEntries(extractors); - } - } diff --git a/src/main/java/org/assertj/core/api/ObjectArrayAssert.java b/src/main/java/org/assertj/core/api/ObjectArrayAssert.java index 499b0074456..7f7819c50db 100644 --- a/src/main/java/org/assertj/core/api/ObjectArrayAssert.java +++ b/src/main/java/org/assertj/core/api/ObjectArrayAssert.java @@ -14,12 +14,7 @@ import static org.assertj.core.util.Arrays.array; -import java.util.List; import java.util.concurrent.atomic.AtomicReferenceArray; -import java.util.function.Consumer; -import java.util.function.Function; - -import org.assertj.core.groups.Tuple; /** * Assertion methods for arrays of objects. @@ -50,100 +45,4 @@ protected ObjectArrayAssert newObjectArrayAssert(ELEMENT[] array) { return new ObjectArrayAssert<>(array); } - @Override - @SafeVarargs - public final AbstractListAssert, Tuple, ObjectAssert> extracting(Function... extractors) { - return super.extracting(extractors); - } - - @Override - @SafeVarargs - public final ObjectArrayAssert contains(ELEMENT... values) { - return super.contains(values); - } - - @Override - @SafeVarargs - public final ObjectArrayAssert containsOnly(ELEMENT... values) { - return super.containsOnly(values); - } - - @Override - @SafeVarargs - public final ObjectArrayAssert containsOnlyOnce(ELEMENT... values) { - return super.containsOnlyOnce(values); - } - - @Override - @SafeVarargs - public final ObjectArrayAssert containsExactly(ELEMENT... values) { - return super.containsExactly(values); - } - - @Override - @SafeVarargs - public final ObjectArrayAssert containsExactlyInAnyOrder(ELEMENT... values) { - return super.containsExactlyInAnyOrder(values); - } - - @Override - @SafeVarargs - public final ObjectArrayAssert containsAnyOf(ELEMENT... values) { - return super.containsAnyOf(values); - } - - @Override - @SafeVarargs - public final ObjectArrayAssert isSubsetOf(ELEMENT... values) { - return super.isSubsetOf(values); - } - - @Override - @SafeVarargs - public final ObjectArrayAssert containsSequence(ELEMENT... sequence) { - return super.containsSequence(sequence); - } - - @Override - @SafeVarargs - public final ObjectArrayAssert doesNotContainSequence(ELEMENT... sequence) { - return super.doesNotContainSequence(sequence); - } - - @Override - @SafeVarargs - public final ObjectArrayAssert containsSubsequence(ELEMENT... sequence) { - return super.containsSubsequence(sequence); - } - - @Override - @SafeVarargs - public final ObjectArrayAssert doesNotContainSubsequence(ELEMENT... sequence) { - return super.doesNotContainSubsequence(sequence); - } - - @Override - @SafeVarargs - public final ObjectArrayAssert doesNotContain(ELEMENT... values) { - return super.doesNotContain(values); - } - - @Override - @SafeVarargs - public final ObjectArrayAssert endsWith(ELEMENT first, ELEMENT... rest) { - return super.endsWith(first, rest); - } - - @Override - @SafeVarargs - public final ObjectArrayAssert satisfiesExactly(Consumer... requirements) { - return super.satisfiesExactly(requirements); - } - - @Override - @SafeVarargs - public final ObjectArrayAssert satisfiesExactlyInAnyOrder(Consumer... requirements) { - return super.satisfiesExactlyInAnyOrder(requirements); - } - } diff --git a/src/main/java/org/assertj/core/api/ObjectAssert.java b/src/main/java/org/assertj/core/api/ObjectAssert.java index 36f7d37227d..561b46ce3df 100644 --- a/src/main/java/org/assertj/core/api/ObjectAssert.java +++ b/src/main/java/org/assertj/core/api/ObjectAssert.java @@ -12,11 +12,7 @@ */ package org.assertj.core.api; -import java.util.List; import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Function; - -import org.assertj.core.util.CheckReturnValue; /** * Assertion methods for {@link Object}s. @@ -39,12 +35,4 @@ public ObjectAssert(ACTUAL actual) { public ObjectAssert(AtomicReference actual) { this(actual == null ? null: actual.get()); } - - @Override - @CheckReturnValue - @SafeVarargs - public final AbstractListAssert, Object, ObjectAssert> extracting(Function... extractors) { - return super.extracting(extractors); - } - } diff --git a/src/main/java/org/assertj/core/api/ObjectEnumerableAssert.java b/src/main/java/org/assertj/core/api/ObjectEnumerableAssert.java index 9b39f6867f2..d146fbc0597 100644 --- a/src/main/java/org/assertj/core/api/ObjectEnumerableAssert.java +++ b/src/main/java/org/assertj/core/api/ObjectEnumerableAssert.java @@ -57,7 +57,7 @@ public interface ObjectEnumerableAssertin order.
    @@ -171,7 +171,7 @@ public interface ObjectEnumerableAssertin any order.
    @@ -196,7 +196,7 @@ public interface ObjectEnumerableAssertin any order.
    @@ -250,7 +250,7 @@ public interface ObjectEnumerableAssertwithout extra values between the sequence values. @@ -304,7 +304,7 @@ public interface ObjectEnumerableAssert * - * @param types the expected classes and interfaces + * @param expectedTypes the expected types * @return {@code this} assertion object. * @throws NullPointerException if the given argument is {@code null}. * @throws AssertionError if the actual group is {@code null}. * @throws AssertionError if not all elements of the actual group are instances of one of the given types * @since 2.7.0 / 3.7.0 */ - SELF hasOnlyElementsOfTypes(Class... types); + SELF hasOnlyElementsOfTypes(Class... expectedTypes); + + /** + * Verifies that the actual elements are of the given types in the given order, there should be as many expected types as there are actual elements. + *

    + * Example: + *

     Iterable<Object> list = Arrays.asList(1, "a", "b", 1.00);
    +   *
    +   * // assertion succeeds
    +   * assertThat(list).hasExactlyElementsOfTypes(Integer.class, String.class, String.class, Double.class);
    +   *
    +   * // assertions fail
    +   * // missing second String type
    +   * assertThat(list).hasExactlyElementsOfTypes(Integer.class, String.class, Double.class);
    +   * // no Float type in actual
    +   * assertThat(list).hasExactlyElementsOfTypes(Float.class, String.class, String.class, Double.class);
    +   * // correct types but wrong order
    +   * assertThat(list).hasExactlyElementsOfTypes(String.class, Integer.class, String.class, Double.class);
    +   * // actual has more elements than the specified expected types
    +   * assertThat(list).hasExactlyElementsOfTypes(String.class);
    + * + * @param expectedTypes the expected types + * @return {@code this} assertion object. + * @throws NullPointerException if the given type array is {@code null}. + * @throws AssertionError if actual is {@code null}. + * @throws AssertionError if the actual elements types don't exactly match the given ones (in the given order). + */ + SELF hasExactlyElementsOfTypes(Class... expectedTypes); /** * Verifies that at least one element in the actual {@code Object} group has the specified type (matching @@ -1196,7 +1223,7 @@ public interface ObjectEnumerableAssert... allRequirements); + SELF satisfiesExactly(Consumer... allRequirements); /** * Verifies that at least one combination of iterable elements exists that satisfies the consumers in order (there must be as @@ -1368,7 +1395,7 @@ public interface ObjectEnumerableAssert... allRequirements); + SELF satisfiesExactlyInAnyOrder(Consumer... allRequirements); /** * Verifies whether any elements match the provided {@link Predicate}. @@ -1464,7 +1491,7 @@ public interface ObjectEnumerableAssert actual) { super(actual, PredicateAssert.class); } - @SafeVarargs - @Override - public final PredicateAssert accepts(T... values) { - return super.accepts(values); - } - - @SafeVarargs - @Override - public final PredicateAssert rejects(T... values) { - return super.rejects(values); - } - } diff --git a/src/main/java/org/assertj/core/api/ProxifyMethodChangingTheObjectUnderTest.java b/src/main/java/org/assertj/core/api/ProxifyMethodChangingTheObjectUnderTest.java index 6f533e68f61..3ea4db2948b 100644 --- a/src/main/java/org/assertj/core/api/ProxifyMethodChangingTheObjectUnderTest.java +++ b/src/main/java/org/assertj/core/api/ProxifyMethodChangingTheObjectUnderTest.java @@ -151,7 +151,7 @@ private static Class actualClass(Object currentAssert) { if (currentAssert instanceof LongAssert) return Long.class; if (currentAssert instanceof LongPredicateAssert) return LongPredicate.class; if (currentAssert instanceof MapAssert) return Map.class; - if (currentAssert instanceof ObjectAssert || currentAssert instanceof ProxyableObjectAssert) return Object.class; + if (currentAssert instanceof ObjectAssert) return Object.class; if (currentAssert instanceof OffsetDateTimeAssert) return OffsetDateTime.class; if (currentAssert instanceof OffsetTimeAssert) return OffsetTime.class; if (currentAssert instanceof OptionalAssert) return Optional.class; diff --git a/src/main/java/org/assertj/core/api/ProxyableIterableAssert.java b/src/main/java/org/assertj/core/api/ProxyableIterableAssert.java deleted file mode 100644 index 29b8d824696..00000000000 --- a/src/main/java/org/assertj/core/api/ProxyableIterableAssert.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - * Copyright 2012-2021 the original author or authors. - */ -package org.assertj.core.api; - -import java.util.List; - -/** - * Concrete assertions for {@link Iterable}s without any final methods to allow proxying. - * - * @author Gaël LHEZ - * @since 2.5.1 / 3.5.1 - */ -public class ProxyableIterableAssert extends - FactoryBasedNavigableIterableAssert, Iterable, ELEMENT, ObjectAssert> { - - public ProxyableIterableAssert(Iterable actual) { - super(actual, ProxyableIterableAssert.class, new ObjectAssertFactory<>()); - } - - @Override - protected AbstractListAssert, ELEMENT2, ObjectAssert> newListAssertInstance(List newActual) { - return new ProxyableListAssert<>(newActual); - } - - @Override - protected ProxyableIterableAssert newAbstractIterableAssert(Iterable iterable) { - return new ProxyableIterableAssert<>(iterable); - } - -} diff --git a/src/main/java/org/assertj/core/api/ProxyableListAssert.java b/src/main/java/org/assertj/core/api/ProxyableListAssert.java deleted file mode 100644 index 3be3f94835d..00000000000 --- a/src/main/java/org/assertj/core/api/ProxyableListAssert.java +++ /dev/null @@ -1,241 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - * Copyright 2012-2021 the original author or authors. - */ -package org.assertj.core.api; - -import static org.assertj.core.error.ShouldStartWith.shouldStartWith; -import static org.assertj.core.internal.CommonValidations.checkIsNotNull; -import static org.assertj.core.util.Lists.newArrayList; - -import java.util.AbstractList; -import java.util.Iterator; -import java.util.List; -import java.util.stream.BaseStream; -import java.util.stream.DoubleStream; -import java.util.stream.IntStream; -import java.util.stream.LongStream; -import java.util.stream.Stream; - -import org.assertj.core.internal.Failures; -import org.assertj.core.util.VisibleForTesting; - -/** - * Concrete assertions for {@link List}s without any final methods to allow proxying. - * - * @author Gaël LHEZ - * @since 2.5.1 / 3.5.1 - */ -public class ProxyableListAssert extends - FactoryBasedNavigableListAssert, List, ELEMENT, ObjectAssert> { - - public ProxyableListAssert(List actual) { - super(actual, ProxyableListAssert.class, new ObjectAssertFactory<>()); - } - - @Override - protected AbstractListAssert, ELEMENT2, ObjectAssert> newListAssertInstance(List newActual) { - return new ProxyableListAssert<>(newActual); - } - - // constructors are used indirectly by assumeThat/ soft assertThat methods taking streams - - protected ProxyableListAssert(Stream actual) { - this(actual == null ? null : new ProxyableListAssert.ListFromStream<>(actual)); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - protected ProxyableListAssert(IntStream actual) { - this(actual == null ? null : new ProxyableListAssert.ListFromStream(actual)); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - protected ProxyableListAssert(LongStream actual) { - this(actual == null ? null : new ProxyableListAssert.ListFromStream(actual)); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - protected ProxyableListAssert(DoubleStream actual) { - this(actual == null ? null : new ProxyableListAssert.ListFromStream(actual)); - } - - @Override - protected ProxyableListAssert newAbstractIterableAssert(Iterable iterable) { - return new ProxyableListAssert<>(newArrayList(iterable)); - } - - @Override - public ProxyableListAssert isEqualTo(Object expected) { - if (actual instanceof ProxyableListAssert.ListFromStream && asListFromStream().stream == expected) { - return myself; - } - return super.isEqualTo(expected); - } - - @Override - public ProxyableListAssert isInstanceOf(Class type) { - if (actual instanceof ProxyableListAssert.ListFromStream) { - objects.assertIsInstanceOf(info, asListFromStream().stream, type); - return myself; - } - return super.isInstanceOf(type); - } - - @Override - public ProxyableListAssert isInstanceOfAny(Class... types) { - if (actual instanceof ProxyableListAssert.ListFromStream) { - objects.assertIsInstanceOfAny(info, asListFromStream().stream, types); - return myself; - } - return super.isInstanceOfAny(types); - } - - @Override - public ProxyableListAssert isOfAnyClassIn(Class... types) { - if (actual instanceof ProxyableListAssert.ListFromStream) { - objects.assertIsOfAnyClassIn(info, asListFromStream().stream, types); - return myself; - } - return super.isOfAnyClassIn(types); - } - - @Override - public ProxyableListAssert isExactlyInstanceOf(Class type) { - if (actual instanceof ProxyableListAssert.ListFromStream) { - objects.assertIsExactlyInstanceOf(info, asListFromStream().stream, type); - return myself; - } - return super.isExactlyInstanceOf(type); - } - - @Override - public ProxyableListAssert isNotInstanceOf(Class type) { - if (actual instanceof ProxyableListAssert.ListFromStream) { - objects.assertIsNotInstanceOf(info, asListFromStream().stream, type); - return myself; - } - return super.isNotInstanceOf(type); - } - - @Override - public ProxyableListAssert isNotInstanceOfAny(Class... types) { - if (actual instanceof ProxyableListAssert.ListFromStream) { - objects.assertIsNotInstanceOfAny(info, asListFromStream().stream, types); - return myself; - } - return super.isNotInstanceOfAny(types); - } - - @Override - public ProxyableListAssert isNotOfAnyClassIn(Class... types) { - if (actual instanceof ProxyableListAssert.ListFromStream) { - objects.assertIsNotOfAnyClassIn(info, asListFromStream().stream, types); - return myself; - } - return super.isNotOfAnyClassIn(types); - } - - @Override - public ProxyableListAssert isNotExactlyInstanceOf(Class type) { - if (actual instanceof ProxyableListAssert.ListFromStream) { - objects.assertIsNotExactlyInstanceOf(info, asListFromStream().stream, type); - return myself; - } - return super.isNotExactlyInstanceOf(type); - } - - @Override - public ProxyableListAssert isSameAs(Object expected) { - if (actual instanceof ProxyableListAssert.ListFromStream) { - objects.assertSame(info, asListFromStream().stream, expected); - return myself; - } - return super.isSameAs(expected); - } - - @Override - public ProxyableListAssert isNotSameAs(Object expected) { - if (actual instanceof ProxyableListAssert.ListFromStream) { - objects.assertNotSame(info, asListFromStream().stream, expected); - return myself; - } - return super.isNotSameAs(expected); - } - - @Override - public ProxyableListAssert startsWith(@SuppressWarnings("unchecked") ELEMENT... sequence) { - if (!(actual instanceof ProxyableListAssert.ListFromStream)) { - return super.startsWith(sequence); - } - objects.assertNotNull(info, actual); - checkIsNotNull(sequence); - // NO SUPPORT FOR infinite streams as it prevents chaining other assertions afterward, it requires to consume the - // Stream partially, if you chain another assertion, the stream is already consumed. - Iterator iterator = asListFromStream().stream().iterator(); - if (sequence.length == 0 && iterator.hasNext()) throw new AssertionError("actual is not empty"); - int i = 0; - while (iterator.hasNext()) { - if (i >= sequence.length) break; - if (iterables.getComparisonStrategy().areEqual(iterator.next(), sequence[i++])) continue; - throw actualDoesNotStartWithSequence(info, sequence); - } - if (sequence.length > i) { - // sequence has more elements than actual - throw actualDoesNotStartWithSequence(info, sequence); - } - return myself; - } - - private AssertionError actualDoesNotStartWithSequence(AssertionInfo info, Object[] sequence) { - return Failures.instance() - .failure(info, shouldStartWith("Stream under test", sequence, iterables.getComparisonStrategy())); - } - - @SuppressWarnings("rawtypes") - private ProxyableListAssert.ListFromStream asListFromStream() { - return (ProxyableListAssert.ListFromStream) actual; - } - - @VisibleForTesting - static class ListFromStream> extends AbstractList { - private BaseStream stream; - private List list; - - public ListFromStream(BaseStream stream) { - this.stream = stream; - } - - @Override - public Stream stream() { - initList(); - return list.stream(); - } - - private List initList() { - if (list == null) list = newArrayList(stream.iterator()); - return list; - } - - @Override - public int size() { - initList(); - return list.size(); - } - - @Override - public ELEMENT get(int index) { - initList(); - return list.get(index); - } - - } - -} diff --git a/src/main/java/org/assertj/core/api/ProxyableObjectArrayAssert.java b/src/main/java/org/assertj/core/api/ProxyableObjectArrayAssert.java deleted file mode 100644 index 0544068d526..00000000000 --- a/src/main/java/org/assertj/core/api/ProxyableObjectArrayAssert.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - * Copyright 2012-2021 the original author or authors. - */ -package org.assertj.core.api; - -import static org.assertj.core.util.Arrays.array; - -import java.util.List; -import java.util.concurrent.atomic.AtomicReferenceArray; - -/** - * Concrete assertions for arrays of objects without any final methods to allow proxying. - */ -public class ProxyableObjectArrayAssert extends AbstractObjectArrayAssert, ELEMENT> { - - public ProxyableObjectArrayAssert(ELEMENT[] actual) { - super(actual, ProxyableObjectArrayAssert.class); - } - - public ProxyableObjectArrayAssert(AtomicReferenceArray actual) { - this(array(actual)); - } - - public ProxyableObjectArrayAssert(ProxyableObjectArrayAssert actual) { - this(actual.actual); - } - - @Override - protected ProxyableObjectArrayAssert newObjectArrayAssert(ELEMENT[] array) { - return new ProxyableObjectArrayAssert<>(array); - } - - @Override - protected AbstractListAssert, E, ObjectAssert> newListAssertInstance(List newActual) { - return new ProxyableListAssert<>(newActual); - } - -} diff --git a/src/main/java/org/assertj/core/api/ProxyableObjectAssert.java b/src/main/java/org/assertj/core/api/ProxyableObjectAssert.java deleted file mode 100644 index dcb62ba158b..00000000000 --- a/src/main/java/org/assertj/core/api/ProxyableObjectAssert.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - * Copyright 2012-2021 the original author or authors. - */ -package org.assertj.core.api; - -import java.util.List; -import java.util.concurrent.atomic.AtomicReference; - -/** - * Concrete assertions for {@link Object}s without any final methods to allow proxying. - */ -public class ProxyableObjectAssert extends AbstractObjectAssert, ACTUAL> { - - public ProxyableObjectAssert(ACTUAL actual) { - super(actual, ProxyableObjectAssert.class); - } - - public ProxyableObjectAssert(AtomicReference actual) { - this(actual == null ? null: actual.get()); - } - - @Override - protected AbstractListAssert, ELEMENT, ObjectAssert> newListAssertInstance(List newActual) { - return new ProxyableListAssert<>(newActual); - } - - @Override - protected AbstractObjectAssert newObjectAssert(T objectUnderTest) { - return new ProxyableObjectAssert<>(objectUnderTest); - } -} diff --git a/src/main/java/org/assertj/core/api/RecursiveComparisonAssert.java b/src/main/java/org/assertj/core/api/RecursiveComparisonAssert.java index 24f18336e63..67c5b23139d 100644 --- a/src/main/java/org/assertj/core/api/RecursiveComparisonAssert.java +++ b/src/main/java/org/assertj/core/api/RecursiveComparisonAssert.java @@ -221,6 +221,63 @@ public SELF isNotEqualTo(Object other) { return myself; } + /** + * Makes the recursive comparison to only compare given actual fields and their subfields (no other fields will be compared). + *

    + * Specifying a field will make all its subfields to be compared, for example specifying {@code person} will lead to compare + * {@code person.name}, {@code person.address} and all other Person fields.
    + * On the other hand if you specify {@code person.name}, {@code person} won't be compared but {@code person.name} will be. + *

    + * The fields are specified by name, not by value, for example you can specify {@code person.name} but not {@code "Jack"} + * as {@code "Jack"} is not a field value. + *

    + * {@code comparingOnlyFields} can be combined with ignoring fields methods to restrict further the fields actually compared, + * the resulting compared fields = {specified compared fields} {@code -} {specified ignored fields}.
    For example if the specified compared fields = {"foo", "bar", "baz"} + * and the ignored fields = {"bar"} then only {"foo", "baz"} fields will be compared. + *

    + * Usage example: + *

     public class Person {
    +   *   String name;
    +   *   double height;
    +   *   Home home = new Home();
    +   * }
    +   *
    +   * public class Home {
    +   *   Address address = new Address();
    +   * }
    +   *
    +   * public static class Address {
    +   *   int number;
    +   *   String street;
    +   * }
    +   *
    +   * Person sherlock = new Person("Sherlock", 1.80);
    +   * sherlock.home.address.street = "Baker Street";
    +   * sherlock.home.address.number = 221;
    +   *
    +   * Person moriarty = new Person("Moriarty", 1.80);
    +   * moriarty.home.address.street = "Butcher Street";
    +   * moriarty.home.address.number = 221;
    +   *
    +   *
    +   * // assertion succeeds as name and home.address.street fields are not compared.
    +   * assertThat(sherlock).usingRecursiveComparison()
    +   *                     .comparingOnlyFields("height", "home.address.number")
    +   *                     .isEqualTo(moriarty);
    +   *
    +   * // assertion fails as home.address.street fields differ.
    +   * assertThat(sherlock).usingRecursiveComparison()
    +   *                     .comparingOnlyFields("height", "home")
    +   *                     .isEqualTo(moriarty);
    + * + * @param fieldNamesToCompare the fields of the object under test to compare in the comparison. + * @return this {@link RecursiveComparisonAssert} to chain other methods. + */ + public SELF comparingOnlyFields(String... fieldNamesToCompare) { + recursiveComparisonConfiguration.compareOnlyFields(fieldNamesToCompare); + return myself; + } + /** * Makes the recursive comparison to ignore all actual null fields (but note that the expected object null fields are used in the comparison). *

    @@ -366,7 +423,7 @@ public SELF ignoringExpectedNullFields() { /** * Makes the recursive comparison to ignore the given object under test fields. Nested fields can be specified like this: {@code home.address.street}. *

    - * The given fieldNamesToIgnore are matched agains field names, not field values. + * The given fieldNamesToIgnore are matched against field names, not field values. *

    * Example: *

     public class Person {
    diff --git a/src/main/java/org/assertj/core/api/SoftProxies.java b/src/main/java/org/assertj/core/api/SoftProxies.java
    index 3d6d154846f..08e0b237791 100644
    --- a/src/main/java/org/assertj/core/api/SoftProxies.java
    +++ b/src/main/java/org/assertj/core/api/SoftProxies.java
    @@ -13,13 +13,16 @@
     package org.assertj.core.api;
     
     import static net.bytebuddy.matcher.ElementMatchers.any;
    +import static net.bytebuddy.matcher.ElementMatchers.isProtected;
     import static net.bytebuddy.matcher.ElementMatchers.isPublic;
     import static net.bytebuddy.matcher.ElementMatchers.named;
    +import static net.bytebuddy.matcher.ElementMatchers.namedOneOf;
     import static net.bytebuddy.matcher.ElementMatchers.not;
     import static org.assertj.core.api.ClassLoadingStrategyFactory.classLoadingStrategy;
     
     import java.lang.reflect.Constructor;
     import java.lang.reflect.InvocationTargetException;
    +import java.util.stream.Stream;
     
     import org.assertj.core.api.ClassLoadingStrategyFactory.ClassLoadingStrategyPair;
     import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration;
    @@ -39,29 +42,31 @@
     
     class SoftProxies {
     
    -  private static final Junction METHODS_CHANGING_THE_OBJECT_UNDER_TEST = methodsNamed("asInstanceOf").or(named("asList"))
    -                                                                                                                        .or(named("asString"))
    -                                                                                                                        .or(named("asHexString"))
    -                                                                                                                        .or(named("decodedAsBase64"))
    -                                                                                                                        .or(named("encodedAsBase64"))
    -                                                                                                                        .or(named("extracting"))
    -                                                                                                                        .or(named("extractingByKey"))
    -                                                                                                                        .or(named("extractingByKeys"))
    -                                                                                                                        .or(named("extractingFromEntries"))
    -                                                                                                                        .or(named("extractingResultOf"))
    -                                                                                                                        .or(named("filteredOn"))
    -                                                                                                                        .or(named("filteredOnAssertions"))
    -                                                                                                                        .or(named("filteredOnNull"))
    -                                                                                                                        .or(named("flatExtracting"))
    -                                                                                                                        .or(named("flatMap"))
    -                                                                                                                        .or(named("get"))
    -                                                                                                                        .or(named("getCause"))
    -                                                                                                                        .or(named("getRootCause"))
    -                                                                                                                        .or(named("map"))
    -                                                                                                                        .or(named("size"))
    -                                                                                                                        .or(named("succeedsWithin"))
    -                                                                                                                        .or(named("toAssert"))
    -                                                                                                                        .or(named("usingRecursiveComparison"));
    +  private static final Junction METHODS_CHANGING_THE_OBJECT_UNDER_TEST = methodsChangingTheObjectUnderTestNamed("asInstanceOf",
    +                                                                                                                                   "asList",
    +                                                                                                                                   "asString",
    +                                                                                                                                   "asHexString",
    +                                                                                                                                   "decodedAsBase64",
    +                                                                                                                                   "encodedAsBase64",
    +                                                                                                                                   "extracting",
    +                                                                                                                                   "extractingByKey",
    +                                                                                                                                   "extractingByKeys",
    +                                                                                                                                   "extractingFromEntries",
    +                                                                                                                                   "extractingResultOf",
    +                                                                                                                                   "filteredOn",
    +                                                                                                                                   "filteredOnAssertions",
    +                                                                                                                                   "filteredOnNull",
    +                                                                                                                                   "flatExtracting",
    +                                                                                                                                   "flatMap",
    +                                                                                                                                   "get",
    +                                                                                                                                   "getCause",
    +                                                                                                                                   "getRootCause",
    +                                                                                                                                   "map",
    +                                                                                                                                   "newAbstractIterableAssert",
    +                                                                                                                                   "size",
    +                                                                                                                                   "succeedsWithin",
    +                                                                                                                                   "toAssert",
    +                                                                                                                                   "usingRecursiveComparison");
     
       private static final Junction METHODS_NOT_TO_PROXY = methodsNamed("as").or(named("clone"))
                                                                                                 .or(named("describedAs"))
    @@ -169,10 +174,10 @@ static  Class generateProxyClass(Class assertClass) {
                          .defineField(ProxifyMethodChangingTheObjectUnderTest.FIELD_NAME,
                                       ProxifyMethodChangingTheObjectUnderTest.class,
                                       Visibility.PRIVATE)
    -                     .method(METHODS_CHANGING_THE_OBJECT_UNDER_TEST.and(isPublic()))
    +                     .method(METHODS_CHANGING_THE_OBJECT_UNDER_TEST)
                          .intercept(PROXIFY_METHOD_CHANGING_THE_OBJECT_UNDER_TEST)
                          .defineField(ErrorCollector.FIELD_NAME, ErrorCollector.class, Visibility.PRIVATE)
    -                     .method(any().and(not(METHODS_CHANGING_THE_OBJECT_UNDER_TEST.and(isPublic())))
    +                     .method(any().and(not(METHODS_CHANGING_THE_OBJECT_UNDER_TEST))
                                       .and(not(METHODS_NOT_TO_PROXY)))
                          .intercept(ERROR_COLLECTOR)
                          .implement(AssertJProxySetup.class)
    @@ -184,7 +189,19 @@ static  Class generateProxyClass(Class assertClass) {
                          .getLoaded();
       }
     
    -  private static Junction methodsNamed(String name) {
    -    return named(name);
    +  private static Junction methodsNamed(String... names) {
    +    return namedOneOf(names);
    +  }
    +
    +  private static Junction methodsChangingTheObjectUnderTestNamed(String... names) {
    +    Junction publicMethods = namedOneOf(names).and(isPublic());
    +
    +    String[] forProxyMethodNames = Stream.of(names)
    +                                         .map(name -> name + "ForProxy")
    +                                         .toArray(String[]::new);
    +    Junction forProxyProtectedMethods = namedOneOf(forProxyMethodNames).and(isProtected());
    +
    +    return publicMethods.or(forProxyProtectedMethods);
    +
       }
     }
    diff --git a/src/main/java/org/assertj/core/api/StandardSoftAssertionsProvider.java b/src/main/java/org/assertj/core/api/StandardSoftAssertionsProvider.java
    index 80799c8fc04..f8f9fe87970 100644
    --- a/src/main/java/org/assertj/core/api/StandardSoftAssertionsProvider.java
    +++ b/src/main/java/org/assertj/core/api/StandardSoftAssertionsProvider.java
    @@ -233,8 +233,8 @@ default  CompletableFutureAssert assertThat(CompletionStage ProxyablePredicateAssert assertThat(Predicate actual) {
    -    return proxy(ProxyablePredicateAssert.class, Predicate.class, actual);
    +  default  PredicateAssert assertThat(Predicate actual) {
    +    return proxy(PredicateAssert.class, Predicate.class, actual);
       }
     
       /**
    @@ -282,8 +282,8 @@ default LongPredicateAssert assertThat(LongPredicate actual) {
        * @return the created assertion object.
        */
       @SuppressWarnings("unchecked")
    -  default  AbstractListAssert, ELEMENT, ObjectAssert> assertThat(Stream actual) {
    -    return proxy(ProxyableListAssert.class, Stream.class, actual);
    +  default  ListAssert assertThat(Stream actual) {
    +    return proxy(ListAssert.class, Stream.class, actual);
       }
     
       /**
    @@ -297,8 +297,8 @@ default  AbstractListAssert, ELEMENT, Object
        * @return the created assertion object.
        */
       @SuppressWarnings("unchecked")
    -  default AbstractListAssert, Double, ObjectAssert> assertThat(DoubleStream actual) {
    -    return proxy(ProxyableListAssert.class, DoubleStream.class, actual);
    +  default ListAssert assertThat(DoubleStream actual) {
    +    return proxy(ListAssert.class, DoubleStream.class, actual);
       }
     
       /**
    @@ -312,8 +312,8 @@ default AbstractListAssert, Double, ObjectAssert, Long, ObjectAssert> assertThat(LongStream actual) {
    -    return proxy(ProxyableListAssert.class, LongStream.class, actual);
    +  default ListAssert assertThat(LongStream actual) {
    +    return proxy(ListAssert.class, LongStream.class, actual);
       }
     
       /**
    @@ -327,8 +327,8 @@ default AbstractListAssert, Long, ObjectAssert> as
        * @return the created assertion object.
        */
       @SuppressWarnings("unchecked")
    -  default AbstractListAssert, Integer, ObjectAssert> assertThat(IntStream actual) {
    -    return proxy(ProxyableListAssert.class, IntStream.class, actual);
    +  default ListAssert assertThat(IntStream actual) {
    +    return proxy(ListAssert.class, IntStream.class, actual);
       }
     
       /**
    diff --git a/src/main/java/org/assertj/core/api/ThrowableAssertAlternative.java b/src/main/java/org/assertj/core/api/ThrowableAssertAlternative.java
    index 5d7bfbf660c..067f190ef6a 100644
    --- a/src/main/java/org/assertj/core/api/ThrowableAssertAlternative.java
    +++ b/src/main/java/org/assertj/core/api/ThrowableAssertAlternative.java
    @@ -26,11 +26,12 @@
      * This class is linked with the {@link ThrowableTypeAssert} and allow to check that an exception
      * type is thrown by a lambda.
      */
    -public class ThrowableAssertAlternative extends AbstractAssert, T> {
    +public class ThrowableAssertAlternative
    +    extends AbstractObjectAssert, ACTUAL> {
     
       private ThrowableAssert delegate;
     
    -  public ThrowableAssertAlternative(final T actual) {
    +  public ThrowableAssertAlternative(final ACTUAL actual) {
         super(actual, ThrowableAssertAlternative.class);
         delegate = new ThrowableAssert(actual);
       }
    @@ -41,12 +42,12 @@ public ThrowableAssertAlternative(final T actual) {
        * Examples:
        * 
     Throwable illegalArgumentException = new IllegalArgumentException("wrong amount 123");
        *
    -   * // assertion will pass
    +   * // assertion succeeds:
        * assertThatExceptionOfType(Throwable.class)
        *           .isThrownBy(() -> {throw illegalArgumentException;})
        *           .withMessage("wrong amount 123");
        *
    -   * // assertion will fail
    +   * // assertion fails:
        * assertThatExceptionOfType(Throwable.class)
        *           .isThrownBy(() -> {throw illegalArgumentException;})
        *           .withMessage("wrong amount 123 euros");
    @@ -57,9 +58,9 @@ public ThrowableAssertAlternative(final T actual) { * @throws AssertionError if the message of the actual {@code Throwable} is not equal to the given one. * @see AbstractThrowableAssert#hasMessage(String) */ - public ThrowableAssertAlternative withMessage(String message) { + public ThrowableAssertAlternative withMessage(String message) { delegate.hasMessage(message); - return this; + return myself; } /** @@ -68,12 +69,12 @@ public ThrowableAssertAlternative withMessage(String message) { * Examples: *
     Throwable illegalArgumentException = new IllegalArgumentException("wrong amount 123");
        *
    -   * // assertion will pass
    +   * // assertion succeeds:
        * assertThatExceptionOfType(Throwable.class)
        *           .isThrownBy(() -> {throw illegalArgumentException;})
        *           .withMessage("wrong amount %s, "123");
        *
    -   * // assertion will fail
    +   * // assertion fails:
        * assertThatExceptionOfType(Throwable.class)
        *           .isThrownBy(() -> {throw illegalArgumentException;})
        *           .withMessage("wrong amount 123 euros");
    @@ -85,9 +86,9 @@ public ThrowableAssertAlternative withMessage(String message) { * @throws AssertionError if the message of the actual {@code Throwable} is not equal to the given one. * @see AbstractThrowableAssert#hasMessage(String) */ - public ThrowableAssertAlternative withMessage(String message, Object... parameters) { + public ThrowableAssertAlternative withMessage(String message, Object... parameters) { delegate.hasMessage(message, parameters); - return this; + return myself; } /** @@ -124,9 +125,9 @@ public ThrowableAssertAlternative withMessage(String message, Object... param * @throws AssertionError if the actual {@code Throwable} has not the given cause. * @see AbstractThrowableAssert#hasCause(Throwable) */ - public ThrowableAssertAlternative withCause(Throwable cause) { + public ThrowableAssertAlternative withCause(Throwable cause) { delegate.hasCause(cause); - return this; + return myself; } /** @@ -151,9 +152,9 @@ public ThrowableAssertAlternative withCause(Throwable cause) { * @throws AssertionError if the actual {@code Throwable} has a cause. * @see AbstractThrowableAssert#hasNoCause() */ - public ThrowableAssertAlternative withNoCause() { + public ThrowableAssertAlternative withNoCause() { delegate.hasNoCause(); - return this; + return myself; } /** @@ -162,12 +163,12 @@ public ThrowableAssertAlternative withNoCause() { * Examples: *
     Throwable illegalArgumentException = new IllegalArgumentException("wrong amount 123");
        *
    -   * // assertion will pass
    +   * // assertion succeeds:
        * assertThatExceptionOfType(Throwable.class)
        *           .isThrownBy(() -> {throw illegalArgumentException;})
        *           .withMessageStartingWith("wrong amount");
        *
    -   * // assertion will fail
    +   * // assertion fails:
        * assertThatExceptionOfType(Throwable.class)
        *           .isThrownBy(() -> {throw illegalArgumentException;})
        *           .withMessageStartingWith("right amount");
    @@ -178,9 +179,9 @@ public ThrowableAssertAlternative withNoCause() { * @throws AssertionError if the message of the actual {@code Throwable} does not start with the given description. * @see AbstractThrowableAssert#hasMessageStartingWith(String) */ - public ThrowableAssertAlternative withMessageStartingWith(String description) { + public ThrowableAssertAlternative withMessageStartingWith(String description) { delegate.hasMessageStartingWith(description); - return this; + return myself; } /** @@ -190,12 +191,12 @@ public ThrowableAssertAlternative withMessageStartingWith(String description) * Examples: *
     Throwable illegalArgumentException = new IllegalArgumentException("wrong amount 123");
        *
    -   * // assertion will pass
    +   * // assertion succeeds:
        * assertThatExceptionOfType(Throwable.class)
        *           .isThrownBy(() -> {throw illegalArgumentException;})
        *           .withMessageStartingWith("%s amount", "wrong");
        *
    -   * // assertion will fail
    +   * // assertion fails:
        * assertThatExceptionOfType(Throwable.class)
        *           .isThrownBy(() -> {throw illegalArgumentException;})
        *           .withMessageStartingWith("%s amount", "right");
    @@ -208,9 +209,9 @@ public ThrowableAssertAlternative withMessageStartingWith(String description) * @throws IllegalFormatException if the message contains an illegal syntax according to {@link String#format(String, Object...)}. * @see AbstractThrowableAssert#hasMessageStartingWith(String, Object...) */ - public ThrowableAssertAlternative withMessageStartingWith(String description, Object... parameters) { + public ThrowableAssertAlternative withMessageStartingWith(String description, Object... parameters) { delegate.hasMessageStartingWith(description, parameters); - return this; + return myself; } /** @@ -219,12 +220,12 @@ public ThrowableAssertAlternative withMessageStartingWith(String description, * Examples: *
     Throwable illegalArgumentException = new IllegalArgumentException("wrong amount 123");
        *
    -   * // assertion will pass
    +   * // assertion succeeds:
        * assertThatExceptionOfType(Throwable.class)
        *           .isThrownBy(() -> {throw illegalArgumentException;})
        *           .withMessageContaining("amount");
        *
    -   * // assertion will fail
    +   * // assertion fails:
        * assertThatExceptionOfType(Throwable.class)
        *           .isThrownBy(() -> {throw illegalArgumentException;})
        *           .withMessageContaining("456");
    @@ -235,9 +236,9 @@ public ThrowableAssertAlternative withMessageStartingWith(String description, * @throws AssertionError if the message of the actual {@code Throwable} does not contain the given description. * @see AbstractThrowableAssert#hasMessageContaining(String) */ - public ThrowableAssertAlternative withMessageContaining(String description) { + public ThrowableAssertAlternative withMessageContaining(String description) { delegate.hasMessageContaining(description); - return this; + return myself; } /** @@ -247,12 +248,12 @@ public ThrowableAssertAlternative withMessageContaining(String description) { * Examples: *
     Throwable illegalArgumentException = new IllegalArgumentException("wrong amount 123");
        *
    -   * // assertion will pass
    +   * // assertion succeeds:
        * assertThatExceptionOfType(Throwable.class)
        *           .isThrownBy(() -> {throw illegalArgumentException;})
        *           .withMessageContaining("%s", amount);
        *
    -   * // assertion will fail
    +   * // assertion fails:
        * assertThatExceptionOfType(Throwable.class)
        *           .isThrownBy(() -> {throw illegalArgumentException;})
        *           .withMessageContaining("%d", 456);
    @@ -265,9 +266,9 @@ public ThrowableAssertAlternative withMessageContaining(String description) { * @throws IllegalFormatException if the message contains an illegal syntax according to {@link String#format(String, Object...)}. * @see AbstractThrowableAssert#hasMessageContaining(String, Object...) */ - public ThrowableAssertAlternative withMessageContaining(String description, Object... parameters) { + public ThrowableAssertAlternative withMessageContaining(String description, Object... parameters) { delegate.hasMessageContaining(description, parameters); - return this; + return myself; } /** @@ -276,12 +277,12 @@ public ThrowableAssertAlternative withMessageContaining(String description, O * Examples: *
     Throwable illegalArgumentException = new IllegalArgumentException("wrong amount 123");
        *
    -   * // assertion will pass
    +   * // assertion succeeds:
        * assertThatExceptionOfType(Throwable.class)
        *           .isThrownBy(() -> {throw illegalArgumentException;})
        *           .withMessageContainingAll("amount", "123");
        *
    -   * // assertion will fail
    +   * // assertion fails:
        * assertThatExceptionOfType(Throwable.class)
        *           .isThrownBy(() -> {throw illegalArgumentException;})
        *           .withMessageContainingAll("456");
    @@ -292,9 +293,9 @@ public ThrowableAssertAlternative withMessageContaining(String description, O * @throws AssertionError if the message of the actual {@code Throwable} does not contain all the given values. * @see AbstractThrowableAssert#hasMessageContainingAll(CharSequence...) */ - public ThrowableAssertAlternative withMessageContainingAll(CharSequence... values) { + public ThrowableAssertAlternative withMessageContainingAll(CharSequence... values) { delegate.hasMessageContainingAll(values); - return this; + return myself; } /** @@ -310,7 +311,7 @@ public ThrowableAssertAlternative withMessageContainingAll(CharSequence... va * .isThrownBy(codeThrowing(new Exception())) * .withMessageNotContaining("bam"); * - * //assertion will fail + * //assertion fails: * assertThatExceptionOfType(Exception.class) * .isThrownBy(codeThrowing(new Exception("boom"))) * .withMessageNotContaining("boom");
    @@ -321,9 +322,9 @@ public ThrowableAssertAlternative withMessageContainingAll(CharSequence... va * @throws AssertionError if the message of the actual {@code Throwable} contains the given content. * @see AbstractThrowableAssert#hasMessageNotContaining(String) */ - public ThrowableAssertAlternative withMessageNotContaining(String content) { + public ThrowableAssertAlternative withMessageNotContaining(String content) { delegate.hasMessageNotContaining(content); - return this; + return myself; } /** @@ -339,7 +340,7 @@ public ThrowableAssertAlternative withMessageNotContaining(String content) { * .isThrownBy(codeThrowing(new Exception())) * .withMessageNotContainingAny("bam"); * - * // assertion will fail + * // assertion fails: * assertThatExceptionOfType(Exception.class) * .isThrownBy(codeThrowing(new Exception("boom"))) * .withMessageNotContainingAny("bam", "boom"); @@ -350,9 +351,9 @@ public ThrowableAssertAlternative withMessageNotContaining(String content) { * @throws AssertionError if the message of the actual {@code Throwable} contains any of the given values. * @see AbstractThrowableAssert#hasMessageNotContainingAny(CharSequence...) */ - public ThrowableAssertAlternative withMessageNotContainingAny(CharSequence... values) { + public ThrowableAssertAlternative withMessageNotContainingAny(CharSequence... values) { delegate.hasMessageNotContainingAny(values); - return this; + return myself; } /** @@ -361,12 +362,12 @@ public ThrowableAssertAlternative withMessageNotContainingAny(CharSequence... * Examples: *
     Throwable illegalArgumentException = new IllegalArgumentException("wrong amount 123");
        *
    -   * // assertion will pass
    +   * // assertion succeeds:
        * assertThatExceptionOfType(Throwable.class)
        *           .isThrownBy(() -> {throw illegalArgumentException;})
        *           .withStackTraceContaining("amount");
        *
    -   * // assertion will fail
    +   * // assertion fails:
        * assertThatExceptionOfType(Throwable.class)
        *           .isThrownBy(() -> {throw illegalArgumentException;})
        *           .withStackTraceContaining("456");
    @@ -377,9 +378,9 @@ public ThrowableAssertAlternative withMessageNotContainingAny(CharSequence... * @throws AssertionError if the stack trace of the actual {@code Throwable} does not contain the given description. * @see AbstractThrowableAssert#hasStackTraceContaining(String) */ - public ThrowableAssertAlternative withStackTraceContaining(String description) { + public ThrowableAssertAlternative withStackTraceContaining(String description) { delegate.hasStackTraceContaining(description); - return this; + return myself; } /** @@ -389,12 +390,12 @@ public ThrowableAssertAlternative withStackTraceContaining(String description * Examples: *
     Throwable illegalArgumentException = new IllegalArgumentException("wrong amount 123");
        *
    -   * // assertion will pass
    +   * // assertion succeeds:
        * assertThatExceptionOfType(Throwable.class)
        *           .isThrownBy(() -> {throw illegalArgumentException;})
        *           .withStackTraceContaining("%s", amount);
        *
    -   * // assertion will fail
    +   * // assertion fails:
        * assertThatExceptionOfType(Throwable.class)
        *           .isThrownBy(() -> {throw illegalArgumentException;})
        *           .withStackTraceContaining("%d", 456);
    @@ -407,9 +408,9 @@ public ThrowableAssertAlternative withStackTraceContaining(String description * @throws IllegalFormatException if the message contains an illegal syntax according to {@link String#format(String, Object...)}. * @see AbstractThrowableAssert#hasStackTraceContaining(String, Object...) */ - public ThrowableAssertAlternative withStackTraceContaining(String description, Object... parameters) { + public ThrowableAssertAlternative withStackTraceContaining(String description, Object... parameters) { delegate.hasStackTraceContaining(description, parameters); - return this; + return myself; } /** @@ -418,12 +419,12 @@ public ThrowableAssertAlternative withStackTraceContaining(String description * Examples: *
     Throwable illegalArgumentException = new IllegalArgumentException("wrong amount 123");
        *
    -   * // assertion will pass
    +   * // assertion succeeds:
        * assertThatExceptionOfType(Throwable.class)
        *           .isThrownBy(() -> {throw illegalArgumentException;})
        *           .withMessageMatching("wrong amount [0-9]*");
        *
    -   * // assertion will fail
    +   * // assertion fails:
        * assertThatExceptionOfType(Throwable.class)
        *           .isThrownBy(() -> {throw illegalArgumentException;})
        *           .withMessageMatching("wrong amount [0-9]* euros");
    @@ -435,9 +436,9 @@ public ThrowableAssertAlternative withStackTraceContaining(String description * @throws NullPointerException if the regex is null * @see AbstractThrowableAssert#hasMessageMatching(String) */ - public ThrowableAssertAlternative withMessageMatching(String regex) { + public ThrowableAssertAlternative withMessageMatching(String regex) { delegate.hasMessageMatching(regex); - return this; + return myself; } /** @@ -446,12 +447,12 @@ public ThrowableAssertAlternative withMessageMatching(String regex) { * Examples: *
     Throwable illegalArgumentException = new IllegalArgumentException("wrong amount 123");
        *
    -   * // assertion will pass
    +   * // assertion succeeds:
        * assertThatExceptionOfType(Throwable.class)
        *           .isThrownBy(() -> {throw illegalArgumentException;})
        *           .withMessageEndingWith("123");
        *
    -   * // assertion will fail
    +   * // assertion fails:
        * assertThatExceptionOfType(Throwable.class)
        *           .isThrownBy(() -> {throw illegalArgumentException;})
        *           .withMessageEndingWith("456");
    @@ -462,9 +463,9 @@ public ThrowableAssertAlternative withMessageMatching(String regex) { * @throws AssertionError if the message of the actual {@code Throwable} does not end with the given description. * @see AbstractThrowableAssert#hasMessageEndingWith(String) */ - public ThrowableAssertAlternative withMessageEndingWith(String description) { + public ThrowableAssertAlternative withMessageEndingWith(String description) { delegate.hasMessageEndingWith(description); - return this; + return myself; } /** @@ -474,12 +475,12 @@ public ThrowableAssertAlternative withMessageEndingWith(String description) { * Examples: *
     Throwable illegalArgumentException = new IllegalArgumentException("wrong amount 123");
        *
    -   * // assertion will pass
    +   * // assertion succeeds:
        * assertThatExceptionOfType(Throwable.class)
        *           .isThrownBy(() -> {throw illegalArgumentException;})
        *           .withMessageEndingWith("%d", 123);
        *
    -   * // assertion will fail
    +   * // assertion fails:
        * assertThatExceptionOfType(Throwable.class)
        *           .isThrownBy(() -> {throw illegalArgumentException;})
        *           .withMessageEndingWith("%d", 456);
    @@ -492,9 +493,9 @@ public ThrowableAssertAlternative withMessageEndingWith(String description) { * @throws IllegalFormatException if the message contains an illegal syntax according to {@link String#format(String, Object...)}. * @see AbstractThrowableAssert#hasMessageEndingWith(String, Object...) */ - public ThrowableAssertAlternative withMessageEndingWith(String description, Object... parameters) { + public ThrowableAssertAlternative withMessageEndingWith(String description, Object... parameters) { delegate.hasMessageEndingWith(description, parameters); - return this; + return myself; } /** @@ -503,7 +504,7 @@ public ThrowableAssertAlternative withMessageEndingWith(String description, O * Example: *
     Throwable throwable = new Throwable(new NullPointerException());
        *
    -   * // assertion will pass
    +   * // assertion succeeds:
        * assertThatExceptionOfType(Throwable.class)
        *           .isThrownBy(() -> {throw throwable;})
        *           .withCauseInstanceOf(NullPointerException.class);
    @@ -511,7 +512,7 @@ public ThrowableAssertAlternative withMessageEndingWith(String description, O
        *           .isThrownBy(() -> {throw throwable;})
        *           .withCauseInstanceOf(RuntimeException.class);
        *
    -   * // assertion will fail
    +   * // assertion fails:
        * assertThatExceptionOfType(Throwable.class)
        *           .isThrownBy(() -> {throw throwable;})
        *           .withCauseInstanceOf(IllegalArgumentException.class);
    @@ -524,9 +525,9 @@ public ThrowableAssertAlternative withMessageEndingWith(String description, O * @throws AssertionError if the cause of the actual {@code Throwable} is not an instance of the given type. * @see AbstractThrowableAssert#hasCauseInstanceOf(Class) */ - public ThrowableAssertAlternative withCauseInstanceOf(Class type) { + public ThrowableAssertAlternative withCauseInstanceOf(Class type) { delegate.hasCauseInstanceOf(type); - return this; + return myself; } /** @@ -535,7 +536,7 @@ public ThrowableAssertAlternative withCauseInstanceOf(Class Throwable throwable = new Throwable(new NullPointerException()); * - * // assertion will pass + * // assertion succeeds: * assertThatExceptionOfType(Throwable.class) * .isThrownBy(() -> {throw throwable;}) * .withCauseExactlyInstanceOf(NullPointerException.class); @@ -557,9 +558,9 @@ public ThrowableAssertAlternative withCauseInstanceOf(Class withCauseExactlyInstanceOf(Class type) { + public ThrowableAssertAlternative withCauseExactlyInstanceOf(Class type) { delegate.hasCauseExactlyInstanceOf(type); - return this; + return myself; } /** @@ -570,7 +571,7 @@ public ThrowableAssertAlternative withCauseExactlyInstanceOf(Class withCauseExactlyInstanceOf(Class @@ -591,9 +592,9 @@ public ThrowableAssertAlternative withCauseExactlyInstanceOf(Class withRootCauseInstanceOf(Class type) { + public ThrowableAssertAlternative withRootCauseInstanceOf(Class type) { delegate.hasRootCauseInstanceOf(type); - return this; + return myself; } /** @@ -604,12 +605,12 @@ public ThrowableAssertAlternative withRootCauseInstanceOf(Class withRootCauseInstanceOf(Class withRootCauseExactlyInstanceOf(Class type) { + public ThrowableAssertAlternative withRootCauseExactlyInstanceOf(Class type) { delegate.hasRootCauseExactlyInstanceOf(type); - return this; + return myself; } /** {@inheritDoc} */ @Override @CheckReturnValue - public ThrowableAssertAlternative describedAs(String description, Object... args) { + public ThrowableAssertAlternative describedAs(String description, Object... args) { delegate.describedAs(description, args); return super.describedAs(description, args); } @@ -642,7 +643,7 @@ public ThrowableAssertAlternative describedAs(String description, Object... a /** {@inheritDoc} */ @Override @CheckReturnValue - public ThrowableAssertAlternative describedAs(Description description) { + public ThrowableAssertAlternative describedAs(Description description) { delegate.describedAs(description); return super.describedAs(description); } @@ -658,7 +659,7 @@ public ThrowableAssertAlternative describedAs(Description description) { * @since 3.16.0 */ public ThrowableAssertAlternative havingCause() { - AbstractThrowableAssert causeAssert = delegate.getCause(); + AbstractThrowableAssert causeAssert = delegate.getCause(); return new ThrowableAssertAlternative<>(causeAssert.actual); } diff --git a/src/main/java/org/assertj/core/api/ThrowableTypeAssert.java b/src/main/java/org/assertj/core/api/ThrowableTypeAssert.java index ac9255a87ad..e1a6b11de2d 100644 --- a/src/main/java/org/assertj/core/api/ThrowableTypeAssert.java +++ b/src/main/java/org/assertj/core/api/ThrowableTypeAssert.java @@ -45,14 +45,14 @@ public ThrowableTypeAssert(final Class throwableType) { } /** - * Assert that an exception of type T is thrown by the {@code throwingCallable} + * Assert that an exception of type T is thrown by the {@code throwingCallable} * and allow to chain assertions on the thrown exception. *

    * Example: *

     assertThatExceptionOfType(IOException.class).isThrownBy(() -> { throw new IOException("boom!"); })
        *                                       .withMessage("boom!"); 
    * - * @param throwingCallable code throwing the exception of expected type + * @param throwingCallable code throwing the exception of expected type * @return return a {@link ThrowableAssertAlternative}. */ public ThrowableAssertAlternative isThrownBy(final ThrowingCallable throwingCallable) { diff --git a/src/main/java/org/assertj/core/api/WithAssertions.java b/src/main/java/org/assertj/core/api/WithAssertions.java index 51c39e900da..d3d72287dbd 100644 --- a/src/main/java/org/assertj/core/api/WithAssertions.java +++ b/src/main/java/org/assertj/core/api/WithAssertions.java @@ -334,7 +334,7 @@ default MapAssert assertThat(final Map actual) { * @param actual the actual value. * @return the created assertion object. */ - default AbstractShortAssert assertThat(final short actual) { + default ShortAssert assertThat(final short actual) { return Assertions.assertThat(actual); } @@ -344,7 +344,7 @@ default AbstractShortAssert assertThat(final short actual) { * @param actual the actual value. * @return the created assertion object. */ - default AbstractLongAssert assertThat(final long actual) { + default LongAssert assertThat(final long actual) { return Assertions.assertThat(actual); } @@ -354,7 +354,7 @@ default AbstractLongAssert assertThat(final long actual) { * @param actual the actual value. * @return the created assertion object. */ - default AbstractLongAssert assertThat(final Long actual) { + default LongAssert assertThat(final Long actual) { return Assertions.assertThat(actual); } @@ -364,7 +364,7 @@ default AbstractLongAssert assertThat(final Long actual) { * @param actual the actual value. * @return the created assertion object. */ - default AbstractLongArrayAssert assertThat(final long[] actual) { + default LongArrayAssert assertThat(final long[] actual) { return Assertions.assertThat(actual); } @@ -396,7 +396,7 @@ default ObjectAssert assertThat(final T actual) { * @param actual the actual value. * @return the created assertion object. */ - default AbstractStringAssert assertThat(final String actual) { + default StringAssert assertThat(final String actual) { return Assertions.assertThat(actual); } @@ -406,7 +406,7 @@ default AbstractStringAssert assertThat(final String actual) { * @param actual the actual value. * @return the created assertion object. */ - default AbstractDateAssert assertThat(final Date actual) { + default DateAssert assertThat(final Date actual) { return Assertions.assertThat(actual); } @@ -416,7 +416,7 @@ default AbstractDateAssert assertThat(final Date actual) { * @param actual the actual value. * @return the created {@link ThrowableAssert}. */ - default AbstractThrowableAssert assertThat(final Throwable actual) { + default ThrowableAssert assertThat(final Throwable actual) { return Assertions.assertThat(actual); } @@ -426,7 +426,7 @@ default AbstractDateAssert assertThat(final Date actual) { * @param actual the actual value. * @return the created assertion object. */ - default AbstractBigDecimalAssert assertThat(final BigDecimal actual) { + default BigDecimalAssert assertThat(final BigDecimal actual) { return Assertions.assertThat(actual); } @@ -437,7 +437,7 @@ default AbstractBigDecimalAssert assertThat(final BigDecimal actual) { * @return the created assertion object. * @since 2.7.0 / 3.7.0 */ - default AbstractBigIntegerAssert assertThat(BigInteger actual) { + default BigIntegerAssert assertThat(BigInteger actual) { return Assertions.assertThat(actual); } @@ -598,7 +598,7 @@ default AtomicStampedReferenceAssert assertThat(AtomicStampedRefe * @param actual the actual value. * @return the created assertion object. */ - default AbstractCharSequenceAssert assertThat(final CharSequence actual) { + default CharSequenceAssert assertThat(final CharSequence actual) { return Assertions.assertThat(actual); } @@ -609,7 +609,7 @@ default AtomicStampedReferenceAssert assertThat(AtomicStampedRefe * @return the created assertion object. * @since 3.11.0 */ - default AbstractCharSequenceAssert assertThat(final StringBuilder actual) { + default CharSequenceAssert assertThat(final StringBuilder actual) { return Assertions.assertThat(actual); } @@ -620,7 +620,7 @@ default AtomicStampedReferenceAssert assertThat(AtomicStampedRefe * @return the created assertion object. * @since 3.11.0 */ - default AbstractCharSequenceAssert assertThat(final StringBuffer actual) { + default CharSequenceAssert assertThat(final StringBuffer actual) { return Assertions.assertThat(actual); } @@ -630,7 +630,7 @@ default AtomicStampedReferenceAssert assertThat(AtomicStampedRefe * @param actual the actual value. * @return the created assertion object. */ - default AbstractShortArrayAssert assertThat(final short[] actual) { + default ShortArrayAssert assertThat(final short[] actual) { return Assertions.assertThat(actual); } @@ -651,7 +651,7 @@ default Short2DArrayAssert assertThat(final short[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - default AbstractShortAssert assertThat(final Short actual) { + default ShortAssert assertThat(final Short actual) { return Assertions.assertThat(actual); } @@ -671,7 +671,7 @@ default ClassAssert assertThat(final Class actual) { * @param actual the actual value. * @return the created assertion object. */ - default AbstractCharacterAssert assertThat(final Character actual) { + default CharacterAssert assertThat(final Character actual) { return Assertions.assertThat(actual); } @@ -681,7 +681,7 @@ default AbstractCharacterAssert assertThat(final Character actual) { * @param actual the actual value. * @return the created assertion object. */ - default AbstractCharArrayAssert assertThat(final char[] actual) { + default CharArrayAssert assertThat(final char[] actual) { return Assertions.assertThat(actual); } @@ -702,7 +702,7 @@ default Char2DArrayAssert assertThat(final char[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - default AbstractCharacterAssert assertThat(final char actual) { + default CharacterAssert assertThat(final char actual) { return Assertions.assertThat(actual); } @@ -714,7 +714,7 @@ default AbstractCharacterAssert assertThat(final char actual) { * @param actual the actual value. * @return the created assertion object. */ - default > AbstractComparableAssert assertThat(final T actual) { + default > GenericComparableAssert assertThat(final T actual) { return Assertions.assertThat(actual); } @@ -734,9 +734,10 @@ default IterableAssert assertThat(final Iterable actual) { * in order to perform assertions on it. *

    * Navigational methods provided:

      - *
    • {@link AbstractIterableAssert#first() first()}
    • - *
    • {@link AbstractIterableAssert#last() last()}
    • - *
    • {@link AbstractIterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#first() first()}
    • + *
    • {@link IterableAssert#last() last()}
    • + *
    • {@link IterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#elements(int...) element(int...)}
    • *
    *

    * The available assertions after navigating to an element depend on the {@code ELEMENT_ASSERT} parameter of the given @@ -798,9 +799,10 @@ default IteratorAssert assertThat(final Iterator actual) { * in order to perform assertions on it. *

    * Navigational methods provided:

      - *
    • {@link AbstractIterableAssert#first() first()}
    • - *
    • {@link AbstractIterableAssert#last() last()}
    • - *
    • {@link AbstractIterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#first() first()}
    • + *
    • {@link IterableAssert#last() last()}
    • + *
    • {@link IterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#elements(int...) element(int...)}
    • *
    *

    * The available assertions after navigating to an element depend on the given {@code assertClass} @@ -832,7 +834,7 @@ default , ELEMENT, ELEMENT_ASSERT ext * @param actual the actual value. * @return the created assertion object. */ - default AbstractBooleanAssert assertThat(final Boolean actual) { + default BooleanAssert assertThat(final Boolean actual) { return Assertions.assertThat(actual); } @@ -842,7 +844,7 @@ default AbstractBooleanAssert assertThat(final Boolean actual) { * @param actual the actual value. * @return the created assertion object. */ - default AbstractBooleanArrayAssert assertThat(final boolean[] actual) { + default BooleanArrayAssert assertThat(final boolean[] actual) { return Assertions.assertThat(actual); } @@ -863,7 +865,7 @@ default Boolean2DArrayAssert assertThat(final boolean[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - default AbstractByteAssert assertThat(final byte actual) { + default ByteAssert assertThat(final byte actual) { return Assertions.assertThat(actual); } @@ -873,7 +875,7 @@ default AbstractByteAssert assertThat(final byte actual) { * @param actual the actual value. * @return the created assertion object. */ - default AbstractByteAssert assertThat(final Byte actual) { + default ByteAssert assertThat(final Byte actual) { return Assertions.assertThat(actual); } @@ -883,7 +885,7 @@ default AbstractByteAssert assertThat(final Byte actual) { * @param actual the actual value. * @return the created assertion object. */ - default AbstractByteArrayAssert assertThat(final byte[] actual) { + default ByteArrayAssert assertThat(final byte[] actual) { return Assertions.assertThat(actual); } @@ -904,7 +906,7 @@ default Byte2DArrayAssert assertThat(final byte[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - default AbstractBooleanAssert assertThat(final boolean actual) { + default BooleanAssert assertThat(final boolean actual) { return Assertions.assertThat(actual); } @@ -914,7 +916,7 @@ default AbstractBooleanAssert assertThat(final boolean actual) { * @param actual the actual value. * @return the created assertion object. */ - default AbstractFloatAssert assertThat(final float actual) { + default FloatAssert assertThat(final float actual) { return Assertions.assertThat(actual); } @@ -924,7 +926,7 @@ default AbstractFloatAssert assertThat(final float actual) { * @param actual the actual value. * @return the created assertion object. */ - default AbstractInputStreamAssert assertThat(final InputStream actual) { + default InputStreamAssert assertThat(final InputStream actual) { return Assertions.assertThat(actual); } @@ -934,7 +936,7 @@ default AbstractFloatAssert assertThat(final float actual) { * @param actual the actual value. * @return the created assertion object. */ - default AbstractFileAssert assertThat(final File actual) { + default FileAssert assertThat(final File actual) { return Assertions.assertThat(actual); } @@ -957,7 +959,7 @@ default FutureAssert assertThat(Future actual) { * @param actual the path to test * @return the created assertion object */ - default AbstractPathAssert assertThat(final Path actual) { + default PathAssert assertThat(final Path actual) { return Assertions.assertThat(actual); } @@ -967,7 +969,7 @@ default AbstractPathAssert assertThat(final Path actual) { * @param actual the actual value. * @return the created assertion object. */ - default AbstractIntArrayAssert assertThat(final int[] actual) { + default IntArrayAssert assertThat(final int[] actual) { return Assertions.assertThat(actual); } @@ -988,7 +990,7 @@ default Int2DArrayAssert assertThat(final int[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - default AbstractFloatAssert assertThat(final Float actual) { + default FloatAssert assertThat(final Float actual) { return Assertions.assertThat(actual); } @@ -1009,7 +1011,7 @@ default Float2DArrayAssert assertThat(final float[][] actual) { * @param actual the actual value. * @return the created assertion object. */ - default AbstractIntegerAssert assertThat(final int actual) { + default IntegerAssert assertThat(final int actual) { return Assertions.assertThat(actual); } @@ -1019,7 +1021,7 @@ default AbstractIntegerAssert assertThat(final int actual) { * @param actual the actual value. * @return the created assertion object. */ - default AbstractFloatArrayAssert assertThat(final float[] actual) { + default FloatArrayAssert assertThat(final float[] actual) { return Assertions.assertThat(actual); } @@ -1029,7 +1031,7 @@ default AbstractFloatArrayAssert assertThat(final float[] actual) { * @param actual the actual value. * @return the created assertion object. */ - default AbstractIntegerAssert assertThat(final Integer actual) { + default IntegerAssert assertThat(final Integer actual) { return Assertions.assertThat(actual); } @@ -1039,7 +1041,7 @@ default AbstractIntegerAssert assertThat(final Integer actual) { * @param actual the actual value. * @return the created assertion object. */ - default AbstractDoubleAssert assertThat(final double actual) { + default DoubleAssert assertThat(final double actual) { return Assertions.assertThat(actual); } @@ -1049,7 +1051,7 @@ default AbstractDoubleAssert assertThat(final double actual) { * @param actual the actual value. * @return the created assertion object. */ - default AbstractDoubleAssert assertThat(final Double actual) { + default DoubleAssert assertThat(final Double actual) { return Assertions.assertThat(actual); } @@ -1069,9 +1071,10 @@ default ListAssert assertThat(final List actual) { * in order to perform assertions on it. *

    * Navigational methods provided:

      - *
    • {@link AbstractIterableAssert#first() first()}
    • - *
    • {@link AbstractIterableAssert#last() last()}
    • - *
    • {@link AbstractIterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#first() first()}
    • + *
    • {@link IterableAssert#last() last()}
    • + *
    • {@link IterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#elements(int...) element(int...)}
    • *
    *

    * The available assertions after navigating to an element depend on the given {@code assertClass} @@ -1102,9 +1105,10 @@ default , ELEMENT_ASSERT extends * in order to perform assertions on it. *

    * Navigational methods provided:

      - *
    • {@link AbstractIterableAssert#first() first()}
    • - *
    • {@link AbstractIterableAssert#last() last()}
    • - *
    • {@link AbstractIterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#first() first()}
    • + *
    • {@link IterableAssert#last() last()}
    • + *
    • {@link IterableAssert#element(int) element(index)}
    • + *
    • {@link IterableAssert#elements(int...) element(int...)}
    • *
    *

    * The available assertions after navigating to an element depend on the {@code ELEMENT_ASSERT} parameter of the given @@ -1265,7 +1269,7 @@ default ListAssert assertThat(IntStream actual) { * @param actual the actual value. * @return the created assertion object. */ - default AbstractDoubleArrayAssert assertThat(final double[] actual) { + default DoubleArrayAssert assertThat(final double[] actual) { return Assertions.assertThat(actual); } @@ -2270,7 +2274,7 @@ default void useDefaultDateFormatsOnly() { * @param actual the actual value. * @return the created assertion object. */ - default AbstractZonedDateTimeAssert assertThat(final ZonedDateTime actual) { + default ZonedDateTimeAssert assertThat(final ZonedDateTime actual) { return Assertions.assertThat(actual); } @@ -2351,7 +2355,7 @@ default OptionalLongAssert assertThat(final OptionalLong optional) { * @param localDateTime the actual value. * @return the created assertion object. */ - default AbstractLocalDateTimeAssert assertThat(final LocalDateTime localDateTime) { + default LocalDateTimeAssert assertThat(final LocalDateTime localDateTime) { return Assertions.assertThat(localDateTime); } @@ -2361,7 +2365,7 @@ default AbstractLocalDateTimeAssert assertThat(final LocalDateTime localDateT * @param localDate the actual value. * @return the created assertion object. */ - default AbstractLocalDateAssert assertThat(final LocalDate localDate) { + default LocalDateAssert assertThat(final LocalDate localDate) { return Assertions.assertThat(localDate); } @@ -2371,7 +2375,7 @@ default AbstractLocalDateAssert assertThat(final LocalDate localDate) { * @param localTime the actual value. * @return the created assertion object. */ - default AbstractLocalTimeAssert assertThat(final LocalTime localTime) { + default LocalTimeAssert assertThat(final LocalTime localTime) { return Assertions.assertThat(localTime); } @@ -2382,7 +2386,7 @@ default AbstractLocalTimeAssert assertThat(final LocalTime localTime) { * @return the created assertion object. * @since 3.7.0 */ - default AbstractInstantAssert assertThat(final Instant actual) { + default InstantAssert assertThat(final Instant actual) { return Assertions.assertThat(actual); } @@ -2393,7 +2397,7 @@ default AbstractInstantAssert assertThat(final Instant actual) { * @return the created assertion object. * @since 3.15.0 */ - default AbstractDurationAssert assertThat(final Duration actual) { + default DurationAssert assertThat(final Duration actual) { return Assertions.assertThat(actual); } @@ -2404,7 +2408,7 @@ default AbstractDurationAssert assertThat(final Duration actual) { * @return the created assertion object. * @since 3.17.0 */ - default AbstractPeriodAssert assertThat(final Period actual) { + default PeriodAssert assertThat(final Period actual) { return Assertions.assertThat(actual); } @@ -2414,7 +2418,7 @@ default AbstractPeriodAssert assertThat(final Period actual) { * @param offsetTime the actual value. * @return the created assertion object. */ - default AbstractOffsetTimeAssert assertThat(final OffsetTime offsetTime) { + default OffsetTimeAssert assertThat(final OffsetTime offsetTime) { return Assertions.assertThat(offsetTime); } @@ -2424,7 +2428,7 @@ default AbstractOffsetTimeAssert assertThat(final OffsetTime offsetTime) { * @param offsetDateTime the actual value. * @return the created assertion object. */ - default AbstractOffsetDateTimeAssert assertThat(final OffsetDateTime offsetDateTime) { + default OffsetDateTimeAssert assertThat(final OffsetDateTime offsetDateTime) { return Assertions.assertThat(offsetDateTime); } @@ -2457,7 +2461,7 @@ default AbstractOffsetDateTimeAssert assertThat(final OffsetDateTime offsetDa * @return the created {@link ThrowableAssert}. */ @CanIgnoreReturnValue - default AbstractThrowableAssert assertThatThrownBy(final ThrowingCallable shouldRaiseThrowable) { + default ThrowableAssert assertThatThrownBy(final ThrowingCallable shouldRaiseThrowable) { return Assertions.assertThatThrownBy(shouldRaiseThrowable); } @@ -2494,7 +2498,7 @@ default AbstractOffsetDateTimeAssert assertThat(final OffsetDateTime offsetDa * @since 3.9.0 */ @CanIgnoreReturnValue - default AbstractThrowableAssert assertThatThrownBy(ThrowingCallable shouldRaiseThrowable, + default ThrowableAssert assertThatThrownBy(ThrowingCallable shouldRaiseThrowable, String description, Object... args) { return assertThat(catchThrowable(shouldRaiseThrowable)).as(description, args).hasBeenThrown(); } @@ -2540,7 +2544,7 @@ default AbstractOffsetDateTimeAssert assertThat(final OffsetDateTime offsetDa * @return The captured exception or null if none was raised by the callable. * @since 3.7.0 */ - default AbstractThrowableAssert assertThatCode(ThrowingCallable shouldRaiseOrNotThrowable) { + default ThrowableAssert assertThatCode(ThrowingCallable shouldRaiseOrNotThrowable) { return assertThat(catchThrowable(shouldRaiseOrNotThrowable)); } @@ -2569,6 +2573,33 @@ default ObjectAssert assertThatObject(T actual) { return assertThat(actual); } + /** + * Uses the given instance as the instance under test for all the assertions expressed as the passed {@link Consumer}. + *

    + * This is useful to avoid repeating getting the instance to test, a bit like a with block which turns the target into + * the equivalent of {@code this} (as in Groovy for example). + *

    + * Example: + *

     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);
    +   *            });
    + *

    + * {@code assertWith} is variation of {@link AbstractAssert#satisfies(Consumer)} hopefully easier to find for some users. + * + * @param the type of the actual value. + * @param actual the actual value. + * @param requirements to assert on the actual object - must not be null. + * @return the created assertion object. + * @since 3.20.0 + */ + @CanIgnoreReturnValue + default ObjectAssert assertWith(T actual, Consumer requirements) { + return assertThat(actual).satisfies(requirements); + } + /** * Allows to catch an {@link Throwable} more easily when used with Java 8 lambdas. * @@ -2762,7 +2793,7 @@ default DoublePredicateAssert assertThat(final DoublePredicate actual) { * @param actual the actual value. * @return the created assertion object. */ - default AbstractUrlAssert assertThat(final URL actual) { + default UrlAssert assertThat(final URL actual) { return Assertions.assertThat(actual); } @@ -2772,7 +2803,7 @@ default AbstractUrlAssert assertThat(final URL actual) { * @param actual the actual value. * @return the created assertion object. */ - default AbstractUriAssert assertThat(final URI actual) { + default UriAssert assertThat(final URI actual) { return Assertions.assertThat(actual); } diff --git a/src/main/java/org/assertj/core/api/WithAssumptions.java b/src/main/java/org/assertj/core/api/WithAssumptions.java index 8c1b4e04e3f..3decfcbee55 100644 --- a/src/main/java/org/assertj/core/api/WithAssumptions.java +++ b/src/main/java/org/assertj/core/api/WithAssumptions.java @@ -84,7 +84,7 @@ public interface WithAssumptions { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default ProxyableObjectArrayAssert assumeThat(final T[] actual) { + default ObjectArrayAssert assumeThat(final T[] actual) { return Assumptions.assumeThat(actual); } @@ -109,7 +109,7 @@ default Object2DArrayAssert assumeThat(final T[][] actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractMapAssert assumeThat(final Map actual) { + default MapAssert assumeThat(final Map actual) { return Assumptions.assumeThat(actual); } @@ -120,7 +120,7 @@ default Object2DArrayAssert assumeThat(final T[][] actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractShortAssert assumeThat(final short actual) { + default ShortAssert assumeThat(final short actual) { return Assumptions.assumeThat(actual); } @@ -131,7 +131,7 @@ default AbstractShortAssert assumeThat(final short actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractLongAssert assumeThat(final long actual) { + default LongAssert assumeThat(final long actual) { return Assumptions.assumeThat(actual); } @@ -142,7 +142,7 @@ default AbstractLongAssert assumeThat(final long actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractLongAssert assumeThat(final Long actual) { + default LongAssert assumeThat(final Long actual) { return Assumptions.assumeThat(actual); } @@ -153,7 +153,7 @@ default AbstractLongAssert assumeThat(final Long actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractLongArrayAssert assumeThat(final long[] actual) { + default LongArrayAssert assumeThat(final long[] actual) { return Assumptions.assumeThat(actual); } @@ -176,7 +176,7 @@ default Long2DArrayAssert assumeThat(final long[][] actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default ProxyableObjectAssert assumeThat(final T actual) { + default ObjectAssert assumeThat(final T actual) { return Assumptions.assumeThat(actual); } @@ -187,7 +187,7 @@ default ProxyableObjectAssert assumeThat(final T actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractStringAssert assumeThat(final String actual) { + default StringAssert assumeThat(final String actual) { return Assumptions.assumeThat(actual); } @@ -198,7 +198,7 @@ default AbstractStringAssert assumeThat(final String actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractDateAssert assumeThat(final Date actual) { + default DateAssert assumeThat(final Date actual) { return Assumptions.assumeThat(actual); } @@ -209,7 +209,7 @@ default AbstractDateAssert assumeThat(final Date actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractThrowableAssert assumeThat(final Throwable actual) { + default ThrowableAssert assumeThat(final Throwable actual) { return Assumptions.assumeThat(actual); } @@ -220,7 +220,7 @@ default AbstractDateAssert assumeThat(final Date actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractBigDecimalAssert assumeThat(final BigDecimal actual) { + default BigDecimalAssert assumeThat(final BigDecimal actual) { return Assumptions.assumeThat(actual); } @@ -231,7 +231,7 @@ default AbstractBigDecimalAssert assumeThat(final BigDecimal actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractBigIntegerAssert assumeThat(BigInteger actual) { + default BigIntegerAssert assumeThat(BigInteger actual) { return Assumptions.assumeThat(actual); } @@ -393,7 +393,7 @@ default AtomicStampedReferenceAssert assumeThat(AtomicStampedRefe * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractCharSequenceAssert assumeThat(final CharSequence actual) { + default CharSequenceAssert assumeThat(final CharSequence actual) { return Assumptions.assumeThat(actual); } @@ -404,7 +404,7 @@ default AtomicStampedReferenceAssert assumeThat(AtomicStampedRefe * @return the created assumption for assertion object. * @since 3.11.0 */ - default AbstractCharSequenceAssert assumeThat(final StringBuilder actual) { + default CharSequenceAssert assumeThat(final StringBuilder actual) { return Assumptions.assumeThat(actual); } @@ -415,7 +415,7 @@ default AtomicStampedReferenceAssert assumeThat(AtomicStampedRefe * @return the created assumption for assertion object. * @since 3.11.0 */ - default AbstractCharSequenceAssert assumeThat(final StringBuffer actual) { + default CharSequenceAssert assumeThat(final StringBuffer actual) { return Assumptions.assumeThat(actual); } @@ -426,7 +426,7 @@ default AtomicStampedReferenceAssert assumeThat(AtomicStampedRefe * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractShortArrayAssert assumeThat(final short[] actual) { + default ShortArrayAssert assumeThat(final short[] actual) { return Assumptions.assumeThat(actual); } @@ -448,7 +448,7 @@ default Short2DArrayAssert assumeThat(final short[][] actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractShortAssert assumeThat(final Short actual) { + default ShortAssert assumeThat(final Short actual) { return Assumptions.assumeThat(actual); } @@ -459,7 +459,7 @@ default AbstractShortAssert assumeThat(final Short actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractClassAssert assumeThat(final Class actual) { + default ClassAssert assumeThat(final Class actual) { return Assumptions.assumeThat(actual); } @@ -470,7 +470,7 @@ default AbstractClassAssert assumeThat(final Class actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractCharacterAssert assumeThat(final Character actual) { + default CharacterAssert assumeThat(final Character actual) { return Assumptions.assumeThat(actual); } @@ -481,7 +481,7 @@ default AbstractCharacterAssert assumeThat(final Character actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractCharArrayAssert assumeThat(final char[] actual) { + default CharArrayAssert assumeThat(final char[] actual) { return Assumptions.assumeThat(actual); } @@ -503,7 +503,7 @@ default Char2DArrayAssert assumeThat(final char[][] actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractCharacterAssert assumeThat(final char actual) { + default CharacterAssert assumeThat(final char actual) { return Assumptions.assumeThat(actual); } @@ -515,7 +515,7 @@ default AbstractCharacterAssert assumeThat(final char actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default > AbstractComparableAssert assumeThat(final T actual) { + default > GenericComparableAssert assumeThat(final T actual) { return Assumptions.assumeThat(actual); } @@ -527,14 +527,14 @@ default > AbstractComparableAssert assumeT * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default ProxyableIterableAssert assumeThat(final Iterable actual) { + default IterableAssert assumeThat(final Iterable actual) { return Assumptions.assumeThat(actual); } /** * Creates a new instance of {@link IteratorAssert} assumption. *

    - * Breaking change in version 3.12.0: this method does not return anymore an {@link ProxyableIterableAssert} but an {@link IteratorAssert}. + * Breaking change in version 3.12.0: this method does not return anymore an {@link IterableAssert} but an {@link IteratorAssert}. * * @param the type of elements. * @param actual the actual value. @@ -552,7 +552,7 @@ default IteratorAssert assumeThat(final Iterator assumeThat(final Boolean actual) { + default BooleanAssert assumeThat(final Boolean actual) { return Assumptions.assumeThat(actual); } @@ -563,7 +563,7 @@ default AbstractBooleanAssert assumeThat(final Boolean actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractBooleanArrayAssert assumeThat(final boolean[] actual) { + default BooleanArrayAssert assumeThat(final boolean[] actual) { return Assumptions.assumeThat(actual); } @@ -585,7 +585,7 @@ default Boolean2DArrayAssert assumeThat(final boolean[][] actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractByteAssert assumeThat(final byte actual) { + default ByteAssert assumeThat(final byte actual) { return Assumptions.assumeThat(actual); } @@ -596,7 +596,7 @@ default AbstractByteAssert assumeThat(final byte actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractByteAssert assumeThat(final Byte actual) { + default ByteAssert assumeThat(final Byte actual) { return Assumptions.assumeThat(actual); } @@ -607,7 +607,7 @@ default AbstractByteAssert assumeThat(final Byte actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractByteArrayAssert assumeThat(final byte[] actual) { + default ByteArrayAssert assumeThat(final byte[] actual) { return Assumptions.assumeThat(actual); } @@ -629,7 +629,7 @@ default Byte2DArrayAssert assumeThat(final byte[][] actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractBooleanAssert assumeThat(final boolean actual) { + default BooleanAssert assumeThat(final boolean actual) { return Assumptions.assumeThat(actual); } @@ -640,7 +640,7 @@ default AbstractBooleanAssert assumeThat(final boolean actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractFloatAssert assumeThat(final float actual) { + default FloatAssert assumeThat(final float actual) { return Assumptions.assumeThat(actual); } @@ -651,7 +651,7 @@ default AbstractFloatAssert assumeThat(final float actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractInputStreamAssert assumeThat(final InputStream actual) { + default InputStreamAssert assumeThat(final InputStream actual) { return Assumptions.assumeThat(actual); } @@ -662,7 +662,7 @@ default AbstractFloatAssert assumeThat(final float actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractFileAssert assumeThat(final File actual) { + default FileAssert assumeThat(final File actual) { return Assumptions.assumeThat(actual); } @@ -675,7 +675,7 @@ default AbstractFileAssert assumeThat(final File actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractFutureAssert, RESULT> assumeThat(Future actual) { + default FutureAssert assumeThat(Future actual) { return Assumptions.assumeThat(actual); } @@ -686,7 +686,7 @@ default AbstractFileAssert assumeThat(final File actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractPathAssert assumeThat(final Path actual) { + default PathAssert assumeThat(final Path actual) { return Assumptions.assumeThat(actual); } @@ -697,7 +697,7 @@ default AbstractPathAssert assumeThat(final Path actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractIntArrayAssert assumeThat(final int[] actual) { + default IntArrayAssert assumeThat(final int[] actual) { return Assumptions.assumeThat(actual); } @@ -719,7 +719,7 @@ default Int2DArrayAssert assumeThat(final int[][] actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractFloatAssert assumeThat(final Float actual) { + default FloatAssert assumeThat(final Float actual) { return Assumptions.assumeThat(actual); } @@ -741,7 +741,7 @@ default Float2DArrayAssert assumeThat(final float[][] actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractIntegerAssert assumeThat(final int actual) { + default IntegerAssert assumeThat(final int actual) { return Assumptions.assumeThat(actual); } @@ -752,7 +752,7 @@ default AbstractIntegerAssert assumeThat(final int actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractFloatArrayAssert assumeThat(final float[] actual) { + default FloatArrayAssert assumeThat(final float[] actual) { return Assumptions.assumeThat(actual); } @@ -763,7 +763,7 @@ default AbstractFloatArrayAssert assumeThat(final float[] actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractIntegerAssert assumeThat(final Integer actual) { + default IntegerAssert assumeThat(final Integer actual) { return Assumptions.assumeThat(actual); } @@ -774,7 +774,7 @@ default AbstractIntegerAssert assumeThat(final Integer actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractDoubleAssert assumeThat(final double actual) { + default DoubleAssert assumeThat(final double actual) { return Assumptions.assumeThat(actual); } @@ -785,7 +785,7 @@ default AbstractDoubleAssert assumeThat(final double actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractDoubleAssert assumeThat(final Double actual) { + default DoubleAssert assumeThat(final Double actual) { return Assumptions.assumeThat(actual); } @@ -797,7 +797,7 @@ default AbstractDoubleAssert assumeThat(final Double actual) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default FactoryBasedNavigableListAssert, List, ELEMENT, ObjectAssert> assumeThat(List list) { + default ListAssert assumeThat(List list) { return Assumptions.assumeThat(list); } @@ -809,7 +809,7 @@ default FactoryBasedNavigableListAssert, * @return the created assumption for assertion object. * @since 3.9.0 */ - default AbstractListAssert, ELEMENT, ObjectAssert> assumeThat(Stream stream) { + default ListAssert assumeThat(Stream stream) { return Assumptions.assumeThat(stream); } @@ -820,7 +820,7 @@ default AbstractListAssert, ELEMENT, Object * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractListAssert, Double, ObjectAssert> assumeThat(DoubleStream doubleStream) { + default ListAssert assumeThat(DoubleStream doubleStream) { return Assumptions.assumeThat(doubleStream); } @@ -831,7 +831,7 @@ default AbstractListAssert, Double, ObjectAssert, Long, ObjectAssert> assumeThat(LongStream longStream) { + default ListAssert assumeThat(LongStream longStream) { return Assumptions.assumeThat(longStream); } @@ -842,7 +842,7 @@ default AbstractListAssert, Long, ObjectAssert> as * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractListAssert, Integer, ObjectAssert> assumeThat(IntStream intStream) { + default ListAssert assumeThat(IntStream intStream) { return Assumptions.assumeThat(intStream); } @@ -853,7 +853,7 @@ default AbstractListAssert, Integer, ObjectAssert assumeThat(final double[] actual) { + default DoubleArrayAssert assumeThat(final double[] actual) { return Assumptions.assumeThat(actual); } @@ -875,7 +875,7 @@ default Double2DArrayAssert assumeThat(final double[][] actual) { * @return the created assumption for assertion object. * @since 3.9.0 */ - default AbstractZonedDateTimeAssert assumeThat(final ZonedDateTime zonedDateTime) { + default ZonedDateTimeAssert assumeThat(final ZonedDateTime zonedDateTime) { return Assumptions.assumeThat(zonedDateTime); } @@ -958,7 +958,7 @@ default OptionalLongAssert assumeThat(final OptionalLong optionalLong) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractLocalDateTimeAssert assumeThat(final LocalDateTime localDateTime) { + default LocalDateTimeAssert assumeThat(final LocalDateTime localDateTime) { return Assumptions.assumeThat(localDateTime); } @@ -969,7 +969,7 @@ default AbstractLocalDateTimeAssert assumeThat(final LocalDateTime localDateT * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractLocalDateAssert assumeThat(final LocalDate localDate) { + default LocalDateAssert assumeThat(final LocalDate localDate) { return Assumptions.assumeThat(localDate); } @@ -980,7 +980,7 @@ default AbstractLocalDateAssert assumeThat(final LocalDate localDate) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractLocalTimeAssert assumeThat(final LocalTime localTime) { + default LocalTimeAssert assumeThat(final LocalTime localTime) { return Assumptions.assumeThat(localTime); } @@ -991,7 +991,7 @@ default AbstractLocalTimeAssert assumeThat(final LocalTime localTime) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractInstantAssert assumeThat(final Instant instant) { + default InstantAssert assumeThat(final Instant instant) { return Assumptions.assumeThat(instant); } @@ -1002,7 +1002,7 @@ default AbstractInstantAssert assumeThat(final Instant instant) { * @return the created assumption for assertion object. * @since 3.15.0 */ - default AbstractDurationAssert assumeThat(final Duration duration) { + default DurationAssert assumeThat(final Duration duration) { return Assumptions.assumeThat(duration); } @@ -1013,7 +1013,7 @@ default AbstractDurationAssert assumeThat(final Duration duration) { * @return the created assumption for assertion object. * @since 3.17.0 */ - default AbstractPeriodAssert assumeThat(final Period period) { + default PeriodAssert assumeThat(final Period period) { return Assumptions.assumeThat(period); } @@ -1024,7 +1024,7 @@ default AbstractPeriodAssert assumeThat(final Period period) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractOffsetTimeAssert assumeThat(final OffsetTime offsetTime) { + default OffsetTimeAssert assumeThat(final OffsetTime offsetTime) { return Assumptions.assumeThat(offsetTime); } @@ -1035,7 +1035,7 @@ default AbstractOffsetTimeAssert assumeThat(final OffsetTime offsetTime) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractOffsetDateTimeAssert assumeThat(final OffsetDateTime offsetDateTime) { + default OffsetDateTimeAssert assumeThat(final OffsetDateTime offsetDateTime) { return Assumptions.assumeThat(offsetDateTime); } @@ -1053,7 +1053,7 @@ default AbstractOffsetDateTimeAssert assumeThat(final OffsetDateTime offsetDa * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractThrowableAssert assumeThatThrownBy(final ThrowingCallable shouldRaiseThrowable) { + default ThrowableAssert assumeThatThrownBy(final ThrowingCallable shouldRaiseThrowable) { return Assumptions.assumeThatThrownBy(shouldRaiseThrowable); } @@ -1078,7 +1078,7 @@ default AbstractOffsetDateTimeAssert assumeThat(final OffsetDateTime offsetDa * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractThrowableAssert assumeThatCode(ThrowingCallable shouldRaiseOrNotThrowable) { + default ThrowableAssert assumeThatCode(ThrowingCallable shouldRaiseOrNotThrowable) { return assumeThat(catchThrowable(shouldRaiseOrNotThrowable)); } @@ -1100,7 +1100,7 @@ default AbstractOffsetDateTimeAssert assumeThat(final OffsetDateTime offsetDa * @return the created assertion object. * @since 3.12.0 */ - default ProxyableObjectAssert assumeThatObject(T actual) { + default ObjectAssert assumeThatObject(T actual) { return assumeThat(actual); } @@ -1112,7 +1112,7 @@ default ProxyableObjectAssert assumeThatObject(T actual) { * @return the created assumption for assertion object. * @since 3.9.0 */ - default ProxyablePredicateAssert assumeThat(final Predicate predicate) { + default PredicateAssert assumeThat(final Predicate predicate) { return Assumptions.assumeThat(predicate); } @@ -1156,7 +1156,7 @@ default DoublePredicateAssert assumeThat(final DoublePredicate doublePredicate) * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractUrlAssert assumeThat(final URL url) { + default UrlAssert assumeThat(final URL url) { return Assumptions.assumeThat(url); } @@ -1167,7 +1167,7 @@ default AbstractUrlAssert assumeThat(final URL url) { * @return the created assumption for assertion object. * @since 2.9.0 / 3.9.0 */ - default AbstractUriAssert assumeThat(final URI uri) { + default UriAssert assumeThat(final URI uri) { return Assumptions.assumeThat(uri); } @@ -1179,7 +1179,7 @@ default AbstractUriAssert assumeThat(final URI uri) { * @return the created assumption for assertion object. * @since 3.14.0 */ - default AbstractSpliteratorAssert assumeThat(final Spliterator spliterator) { + default SpliteratorAssert assumeThat(final Spliterator spliterator) { return Assumptions.assumeThat(spliterator); } } diff --git a/src/main/java/org/assertj/core/api/recursive/comparison/ComparisonDifference.java b/src/main/java/org/assertj/core/api/recursive/comparison/ComparisonDifference.java index 4d54dcc692b..1bfb4eb9701 100644 --- a/src/main/java/org/assertj/core/api/recursive/comparison/ComparisonDifference.java +++ b/src/main/java/org/assertj/core/api/recursive/comparison/ComparisonDifference.java @@ -38,9 +38,9 @@ public class ComparisonDifference implements Comparable { private static final String FIELD = "field/property '%s'"; private static final String TOP_LEVEL_OBJECTS = "Top level actual and expected objects"; private static final String TOP_LEVEL_ELEMENTS = "Top level actual and expected objects element at index %s"; - private static final String TEMPLATE = "%s differ:%n" + - "- actual value : %s%n" + - "- expected value : %s%s"; + static final String TEMPLATE = "%s differ:%n" + + "- actual value : %s%n" + + "- expected value: %s%s"; final List decomposedPath; final String concatenatedPath; @@ -105,8 +105,8 @@ public String multiLineDescription(Representation representation) { additionalInfo); } - // retuns a user friendly path that can differ from DualValue field location - private String fieldPathDescription() { + // returns a user friendly path description + protected String fieldPathDescription() { if (concatenatedPath.isEmpty()) return TOP_LEVEL_OBJECTS; if (concatenatedPath.matches(TOP_LEVEL_ELEMENT_PATTERN)) return format(TOP_LEVEL_ELEMENTS, extractIndex(concatenatedPath)); return format(FIELD, concatenatedPath); @@ -150,7 +150,11 @@ public int hashCode() { @Override public int compareTo(final ComparisonDifference other) { // we don't use '.' to join path before comparing them as it would make a.b < aa - return join("", decomposedPath).compareTo(join("", other.decomposedPath)); + return concat(decomposedPath).compareTo(concat(other.decomposedPath)); + } + + private static String concat(List decomposedPath) { + return join("", decomposedPath); } } diff --git a/src/main/java/org/assertj/core/api/recursive/comparison/ComparisonKeyDifference.java b/src/main/java/org/assertj/core/api/recursive/comparison/ComparisonKeyDifference.java new file mode 100644 index 00000000000..0e7b54457db --- /dev/null +++ b/src/main/java/org/assertj/core/api/recursive/comparison/ComparisonKeyDifference.java @@ -0,0 +1,53 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api.recursive.comparison; + +import static java.lang.String.format; + +import org.assertj.core.internal.UnambiguousRepresentation; +import org.assertj.core.presentation.Representation; + +public class ComparisonKeyDifference extends ComparisonDifference { + + static final String TEMPLATE_FOR_KEY_DIFFERENCE = "map key difference:%n" + + "- actual key : %s%n" + + "- expected key: %s"; + + final Object actualKey; + final Object expectedKey; + + public ComparisonKeyDifference(DualValue dualValue, Object actualKey, Object expectedKey) { + super(dualValue); + this.actualKey = actualKey; + this.expectedKey = expectedKey; + } + + @Override + public String toString() { + return format("ComparisonDifference [path=%s, actualKey=%s, expectedKey=%s]", concatenatedPath, actualKey, expectedKey); + } + + @Override + public String multiLineDescription(Representation representation) { + UnambiguousRepresentation unambiguousRepresentation = new UnambiguousRepresentation(representation, actual, expected); + UnambiguousRepresentation unambiguousKeyRepresentation = new UnambiguousRepresentation(representation, actualKey, + expectedKey); + return format(TEMPLATE + "%n" + TEMPLATE_FOR_KEY_DIFFERENCE, + fieldPathDescription(), + unambiguousRepresentation.getActual(), + unambiguousRepresentation.getExpected(), + "", + unambiguousKeyRepresentation.getActual(), + unambiguousKeyRepresentation.getExpected()); + } +} diff --git a/src/main/java/org/assertj/core/api/recursive/comparison/DualValue.java b/src/main/java/org/assertj/core/api/recursive/comparison/DualValue.java index 130e6a8fefe..1e72ad2cc2f 100644 --- a/src/main/java/org/assertj/core/api/recursive/comparison/DualValue.java +++ b/src/main/java/org/assertj/core/api/recursive/comparison/DualValue.java @@ -215,11 +215,13 @@ public boolean hasPotentialCyclingValues() { private static boolean isPotentialCyclingValue(Object object) { if (object == null) return false; - // java.lang are base types that can't cycle to themselves of other types - // we could check more type, but that's a good start + // java.lang are base types that can't cycle to themselves or other types + // we could check more types, but that's a good start String canonicalName = object.getClass().getCanonicalName(); // canonicalName is null for anonymous and local classes, return true as they can cycle back to other objects. if (canonicalName == null) return true; + // enums can refer back to other object but since they are constants it is very unlikely that they generate cycles. + if (object.getClass().isEnum()) return false; return !canonicalName.startsWith("java.lang"); } diff --git a/src/main/java/org/assertj/core/api/recursive/comparison/FieldLocation.java b/src/main/java/org/assertj/core/api/recursive/comparison/FieldLocation.java index f8173ecb5e5..0f58afda5d5 100644 --- a/src/main/java/org/assertj/core/api/recursive/comparison/FieldLocation.java +++ b/src/main/java/org/assertj/core/api/recursive/comparison/FieldLocation.java @@ -14,6 +14,7 @@ import static java.util.Collections.emptyList; import static java.util.Collections.unmodifiableList; +import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.joining; import java.util.ArrayList; @@ -31,7 +32,7 @@ public final class FieldLocation implements Comparable { private final List decomposedPath; // TODO is it useful? public FieldLocation(List path) { - decomposedPath = unmodifiableList(Objects.requireNonNull(path, "path cannot be null")); + decomposedPath = unmodifiableList(requireNonNull(path, "path cannot be null")); pathToUseInRules = pathToUseInRules(decomposedPath); } @@ -39,6 +40,10 @@ boolean matches(String fieldPath) { return pathToUseInRules.equals(fieldPath); } + boolean startsWith(String fieldPath) { + return pathToUseInRules.startsWith(fieldPath); + } + public List getDecomposedPath() { return decomposedPath; } diff --git a/src/main/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonConfiguration.java b/src/main/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonConfiguration.java index 0bef599fa01..7e8320ba392 100644 --- a/src/main/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonConfiguration.java +++ b/src/main/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonConfiguration.java @@ -21,16 +21,17 @@ import static org.assertj.core.internal.TypeComparators.defaultTypeComparators; import static org.assertj.core.util.Lists.list; import static org.assertj.core.util.Sets.newLinkedHashSet; -import static org.assertj.core.util.Strings.join; import static org.assertj.core.util.introspection.PropertyOrFieldSupport.COMPARISON; import java.util.ArrayList; +import java.util.Collection; import java.util.Comparator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map.Entry; import java.util.Set; import java.util.function.BiPredicate; +import java.util.function.Predicate; import java.util.regex.Pattern; import java.util.stream.Stream; @@ -38,10 +39,13 @@ import org.assertj.core.internal.Objects; import org.assertj.core.internal.TypeComparators; import org.assertj.core.presentation.Representation; +import org.assertj.core.util.Strings; import org.assertj.core.util.VisibleForTesting; public class RecursiveComparisonConfiguration { + private static final String DEFAULT_DELIMITER = ", "; + private static final boolean DEFAULT_IGNORE_ALL_OVERRIDDEN_EQUALS = true; public static final String INDENT_LEVEL_2 = " -"; private boolean strictTypeChecking = false; @@ -53,11 +57,14 @@ public class RecursiveComparisonConfiguration { private List ignoredFieldsRegexes = new ArrayList<>(); private Set> ignoredTypes = new LinkedHashSet<>(); + // fields to compare (no other field will be) + private Set comparedFields = new LinkedHashSet<>(); + // overridden equals method to ignore section private List> ignoredOverriddenEqualsForTypes = new ArrayList<>(); private List ignoredOverriddenEqualsForFields = new ArrayList<>(); private List ignoredOverriddenEqualsForFieldsMatchingRegexes = new ArrayList<>(); - private boolean ignoreAllOverriddenEquals = true; + private boolean ignoreAllOverriddenEquals = DEFAULT_IGNORE_ALL_OVERRIDDEN_EQUALS; // ignore order in collections section private boolean ignoreCollectionOrder = false; @@ -74,6 +81,7 @@ private RecursiveComparisonConfiguration(Builder builder) { this.ignoreAllActualEmptyOptionalFields = builder.ignoreAllActualEmptyOptionalFields; this.ignoreAllExpectedNullFields = builder.ignoreAllExpectedNullFields; this.ignoredFields = newLinkedHashSet(builder.ignoredFields); + this.comparedFields = newLinkedHashSet(builder.comparedFields); ignoreFieldsMatchingRegexes(builder.ignoredFieldsMatchingRegexes); ignoreFieldsOfTypes(builder.ignoredTypes); ignoreOverriddenEqualsForTypes(builder.ignoredOverriddenEqualsForTypes); @@ -175,9 +183,9 @@ public void setIgnoreAllExpectedNullFields(boolean ignoreAllExpectedNullFields) } /** - * Adds the given fields to the list of the object under test fields to ignore in the recursive comparison. + * Adds the given fields to the set of fields from the object under test to ignore in the recursive comparison. *

    - * The field are ignored by name, not by value. + * The fields are ignored by name, not by value. *

    * See {@link RecursiveComparisonAssert#ignoringFields(String...) RecursiveComparisonAssert#ignoringFields(String...)} for examples. * @@ -188,6 +196,23 @@ public void ignoreFields(String... fieldsToIgnore) { ignoredFields.addAll(fieldLocations); } + /** + * Adds the given fields and their subfields to the set of fields from the object under test to compare (no other fields will be compared). + *

    + * The fields are specified by name, not by value, you can specify {@code person.name} but not {@code "Jack"} as {@code "Jack"} is not a field value. + *

    + * Specifying a field will make all its subfields to be compared, for example specifying {@code person} will lead to compare {@code person.name}, {@code person.address} ... + * on the other hand if you specify {@code person.name}, {@code person} won't be compared but {@code person.name} will be. + *

    + * See {@link RecursiveComparisonAssert#comparingOnlyFields(String...) RecursiveComparisonAssert#comparingOnlyFields(String...)} for examples. + * + * @param fieldNamesToCompare the fields of the object under test to compare in the comparison. + */ + public void compareOnlyFields(String... fieldNamesToCompare) { + List fieldLocations = list(fieldNamesToCompare); + comparedFields.addAll(fieldLocations); + } + /** * Allows to ignore in the recursive comparison the object under test fields matching the given regexes. The given regexes are added to the already registered ones. *

    @@ -196,13 +221,14 @@ public void ignoreFields(String... fieldsToIgnore) { * @param regexes regexes used to ignore fields in the comparison. */ public void ignoreFieldsMatchingRegexes(String... regexes) { - ignoredFieldsRegexes.addAll(Stream.of(regexes) - .map(Pattern::compile) - .collect(toList())); + List patterns = Stream.of(regexes) + .map(Pattern::compile) + .collect(toList()); + ignoredFieldsRegexes.addAll(patterns); } /** - * Adds the given types to the list of the object under test fields types to ignore in the recursive comparison. + * Adds the given types to the list fields from the object under test types to ignore in the recursive comparison. * The fields are ignored if their types exactly match one of the ignored types, if a field is a subtype of an ignored type it won't be ignored. *

    * Note that if some object under test fields are null, they are not ignored by this method as their type can't be evaluated. @@ -229,18 +255,27 @@ private static Class asWrapperIfPrimitiveType(Class type) { } /** - * Returns the list of the object under test fields to ignore in the recursive comparison. + * Returns the set of fields from the object under test to ignore in the recursive comparison. * - * @return the list of the object under test fields to ignore in the recursive comparison. + * @return the set of fields from the object under test to ignore in the recursive comparison. */ public Set getIgnoredFields() { return ignoredFields; } /** - * Returns the set of the object under test fields types to ignore in the recursive comparison. + * Returns the set of fields to compare from the object under test (no other fields will be compared). * - * @return the set of the object under test fields types to ignore in the recursive comparison. + * @return the set of fields from the object under test to compare. + */ + public Set getComparedFields() { + return comparedFields; + } + + /** + * Returns the set of fields from the object under test types to ignore in the recursive comparison. + * + * @return the set of fields from the object under test types to ignore in the recursive comparison. */ public Set> getIgnoredTypes() { return ignoredTypes; @@ -317,7 +352,7 @@ public void ignoreCollectionOrder(boolean ignoreCollectionOrder) { } /** - * Adds the given fields to the list of the object under test fields to ignore collection order in the recursive comparison. + * Adds the given fields to the list fields from the object under test to ignore collection order in the recursive comparison. *

    * See {@link RecursiveComparisonAssert#ignoringCollectionOrderInFields(String...) RecursiveComparisonAssert#ignoringCollectionOrderInFields(String...)} for examples. * @@ -329,9 +364,9 @@ public void ignoreCollectionOrderInFields(String... fieldsToIgnoreCollectionOrde } /** - * Returns the list of the object under test fields to ignore collection order in the recursive comparison. + * Returns the list fields from the object under test to ignore collection order in the recursive comparison. * - * @return the list of the object under test fields to ignore collection order in the recursive comparison. + * @return the list fields from the object under test to ignore collection order in the recursive comparison. */ public Set getIgnoredCollectionOrderInFields() { return ignoredCollectionOrderInFields; @@ -492,7 +527,7 @@ public int hashCode() { ignoredCollectionOrderInFields, ignoredCollectionOrderInFieldsMatchingRegexes, ignoredFields, ignoredFieldsRegexes, ignoredOverriddenEqualsForFields, ignoredOverriddenEqualsForTypes, ignoredOverriddenEqualsForFieldsMatchingRegexes, ignoredTypes, strictTypeChecking, - typeComparators); + typeComparators, comparedFields); } @Override @@ -509,6 +544,7 @@ public boolean equals(Object obj) { && ignoreCollectionOrder == other.ignoreCollectionOrder && java.util.Objects.equals(ignoredCollectionOrderInFields, other.ignoredCollectionOrderInFields) && java.util.Objects.equals(ignoredFields, other.ignoredFields) + && java.util.Objects.equals(comparedFields, other.comparedFields) && java.util.Objects.equals(ignoredFieldsRegexes, other.ignoredFieldsRegexes) && java.util.Objects.equals(ignoredOverriddenEqualsForFields, other.ignoredOverriddenEqualsForFields) && java.util.Objects.equals(ignoredOverriddenEqualsForTypes, other.ignoredOverriddenEqualsForTypes) @@ -525,6 +561,7 @@ public String multiLineDescription(Representation representation) { describeIgnoreAllActualNullFields(description); describeIgnoreAllActualEmptyOptionalFields(description); describeIgnoreAllExpectedNullFields(description); + describeComparedFields(description); describeIgnoredFields(description); describeIgnoredFieldsRegexes(description); describeIgnoredFieldsForTypes(description); @@ -540,11 +577,26 @@ public String multiLineDescription(Representation representation) { boolean shouldIgnore(DualValue dualValue) { FieldLocation fieldLocation = dualValue.fieldLocation; - return matchesAnIgnoredField(fieldLocation) + return !shouldBeCompared(fieldLocation) + || matchesAnIgnoredField(fieldLocation) || matchesAnIgnoredFieldRegex(fieldLocation) || shouldIgnoreFieldBasedOnFieldValue(dualValue); } + private boolean shouldBeCompared(FieldLocation fieldLocation) { + // empty comparedFields <=> no restriction on compared fields <=> must be compared + if (comparedFields.isEmpty()) return true; + return comparedFields.stream().anyMatch(matchesComparedField(fieldLocation)); + } + + private static Predicate matchesComparedField(FieldLocation field) { + // a field f must be compared if any compared fields is f itself (obviously), a parent of f or a child of f. + // Examples: + // - "name.first" must be compared if "name" is a compared field (alongwith any other "name" subfields as "name.last") + // - "name" must be compared if "name.first" is a compared field otherwise "name" is ignored and "name.first" never evaluated + return fieldToCompare -> field.startsWith(fieldToCompare) || fieldToCompare.startsWith(field.getPathToUseInRules()); + } + Set getNonIgnoredActualFieldNames(DualValue dualValue) { Set actualFieldsNames = Objects.getFieldsNames(dualValue.actual.getClass()); // we are doing the same as shouldIgnore(DualValue dualValue) but in two steps for performance reasons: @@ -631,6 +683,11 @@ private void describeIgnoredFields(StringBuilder description) { description.append(format("- the following fields were ignored in the comparison: %s%n", describeIgnoredFields())); } + private void describeComparedFields(StringBuilder description) { + if (!comparedFields.isEmpty()) + description.append(format("- the comparison was performed on the following fields: %s%n", describeComparedFields())); + } + private void describeIgnoredFieldsForTypes(StringBuilder description) { if (!ignoredTypes.isEmpty()) description.append(format("- the following types were ignored in the comparison: %s%n", describeIgnoredTypes())); @@ -678,11 +735,11 @@ private String describeIgnoredOverriddenEqualsForTypes(Representation representa List fieldsDescription = ignoredOverriddenEqualsForTypes.stream() .map(representation::toStringOf) .collect(toList()); - return join(fieldsDescription).with(", "); + return join(fieldsDescription); } private String describeIgnoredOverriddenEqualsForFields() { - return join(ignoredOverriddenEqualsForFields).with(", "); + return join(ignoredOverriddenEqualsForFields); } private void describeIgnoreCollectionOrder(StringBuilder description) { @@ -756,25 +813,33 @@ private boolean matchesAnIgnoredCollectionOrderInFieldRegex(FieldLocation fieldL } private String describeIgnoredFields() { - return join(ignoredFields).with(", "); + return join(ignoredFields); + } + + private String describeComparedFields() { + return join(comparedFields); } private String describeIgnoredTypes() { List typesDescription = ignoredTypes.stream() .map(Class::getName) .collect(toList()); - return join(typesDescription).with(", "); + return join(typesDescription); + } + + private static String join(Collection typesDescription) { + return Strings.join(typesDescription).with(DEFAULT_DELIMITER); } private String describeIgnoredCollectionOrderInFields() { - return join(ignoredCollectionOrderInFields).with(", "); + return join(ignoredCollectionOrderInFields); } private String describeRegexes(List regexes) { List fieldsDescription = regexes.stream() .map(Pattern::pattern) .collect(toList()); - return join(fieldsDescription).with(", "); + return join(fieldsDescription); } private boolean isConfiguredToIgnoreSomeButNotAllOverriddenEqualsMethods() { @@ -845,16 +910,17 @@ public static final class Builder { private boolean ignoreAllActualEmptyOptionalFields; private boolean ignoreAllExpectedNullFields; private String[] ignoredFields = {}; + private String[] comparedFields = {}; private String[] ignoredFieldsMatchingRegexes = {}; private Class[] ignoredTypes = {}; private Class[] ignoredOverriddenEqualsForTypes = {}; private String[] ignoredOverriddenEqualsForFields = {}; private String[] ignoredOverriddenEqualsForFieldsMatchingRegexes = {}; - private boolean ignoreAllOverriddenEquals; + private boolean ignoreAllOverriddenEquals = DEFAULT_IGNORE_ALL_OVERRIDDEN_EQUALS; private boolean ignoreCollectionOrder; private String[] ignoredCollectionOrderInFields = {}; private String[] ignoredCollectionOrderInFieldsMatchingRegexes = {}; - private TypeComparators typeComparators = new TypeComparators(); + private TypeComparators typeComparators = defaultTypeComparators(); private FieldComparators fieldComparators = new FieldComparators(); private Builder() {} @@ -913,7 +979,7 @@ public Builder withIgnoreAllExpectedNullFields(boolean ignoreAllExpectedNullFiel } /** - * Adds the given fields to the list of the object under test fields to ignore in the recursive comparison. Nested fields can be specified like this: home.address.street. + * Adds the given fields to the set of fields from the object under test to ignore in the recursive comparison. Nested fields can be specified like this: home.address.street. *

    * See {@link RecursiveComparisonAssert#ignoringFields(String...) RecursiveComparisonAssert#ignoringFields(String...)} for examples. * @@ -925,6 +991,21 @@ public Builder withIgnoredFields(String... fieldsToIgnore) { return this; } + /** + * Adds the given fields to the set of fields from the object under test to compare in the recursive comparison. + *

    + * Nested fields can be specified like this: home.address.street. + *

    + * See {@link RecursiveComparisonAssert#comparingOnlyFields(String...)} for examples. + * + * @param fieldsToCompare the fields of the object under test to compare. + * @return this builder. + */ + public Builder withComparedFields(String... fieldsToCompare) { + this.comparedFields = fieldsToCompare; + return this; + } + /** * Allows to ignore in the recursive comparison the object under test fields matching the given regexes. The given regexes are added to the already registered ones. *

    @@ -939,7 +1020,7 @@ public Builder withIgnoredFieldsMatchingRegexes(String... regexes) { } /** - * Adds the given types to the list of the object under test fields types to ignore in the recursive comparison. + * Adds the given types to the list fields from the object under test types to ignore in the recursive comparison. * The fields are ignored if their types exactly match one of the ignored types, if a field is a subtype of an ignored type it won't be ignored. *

    * Note that if some object under test fields are null, they are not ignored by this method as their type can't be evaluated. @@ -1020,7 +1101,7 @@ public Builder withIgnoreCollectionOrder(boolean ignoreCollectionOrder) { } /** - * Adds the given fields to the list of the object under test fields to ignore collection order in the recursive comparison. + * Adds the given fields to the list fields from the object under test to ignore collection order in the recursive comparison. *

    * See {@link RecursiveComparisonAssert#ignoringCollectionOrderInFields(String...) RecursiveComparisonAssert#ignoringCollectionOrderInFields(String...)} for examples. * diff --git a/src/main/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonDifferenceCalculator.java b/src/main/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonDifferenceCalculator.java index f482919067d..f21d07c9508 100644 --- a/src/main/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonDifferenceCalculator.java +++ b/src/main/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonDifferenceCalculator.java @@ -86,6 +86,10 @@ void addDifference(DualValue dualValue, String description, Object... args) { differences.add(new ComparisonDifference(dualValue, format(description, args))); } + void addKeyDifference(DualValue parentDualValue, Object actualKey, Object expectedKey) { + differences.add(new ComparisonKeyDifference(parentDualValue, actualKey, expectedKey)); + } + public List getDifferences() { Collections.sort(differences); return differences; @@ -136,9 +140,9 @@ private void initDualValuesToCompare(Object actual, Object expected, FieldLocati } else { dualValuesToCompare.addFirst(dualValue); } - // We need to remove already visited fields pair to avoid infinite recursion in case - // parent -> set{child} with child having a reference back to parent - // it occurs to unordered collection where we compare all possible combination of the collection elements recursively + // We need to remove already visited fields pair to avoid infinite recursion in case parent -> set{child} with child having + // a reference back to its parent but only for complex types can have cycle, this is not the case for primitive or enums. + // It occurs for unordered collection where we compare all possible combination of the collection elements recursively. // -- // remove visited values one by one, DualValue.equals correctly compare respective actual and expected fields by reference visitedDualValues.forEach(visitedDualValue -> dualValuesToCompare.stream() @@ -460,12 +464,17 @@ private static void compareSortedMap(DualValue dualValue, ComparisonState // - expected entries not found in actual. } Iterator> expectedMapEntries = expectedMap.entrySet().iterator(); - FieldLocation fieldLocation = dualValue.fieldLocation; for (Map.Entry actualEntry : actualMap.entrySet()) { Map.Entry expectedEntry = expectedMapEntries.next(); - // Must split the Key and Value so that Map.Entry's equals() method is not used. - comparisonState.registerForComparison(new DualValue(fieldLocation, actualEntry.getKey(), expectedEntry.getKey())); - comparisonState.registerForComparison(new DualValue(fieldLocation, actualEntry.getValue(), expectedEntry.getValue())); + // check keys are matched before comparing values as keys represents a field + if (!java.util.Objects.equals(actualEntry.getKey(), expectedEntry.getKey())) { + // report a missing key/field. + comparisonState.addKeyDifference(dualValue, actualEntry.getKey(), expectedEntry.getKey()); + } else { + // as the key/field match we can simply compare field/key values + FieldLocation keyFieldLocation = keyFieldLocation(dualValue.fieldLocation, actualEntry.getKey()); + comparisonState.registerForComparison(new DualValue(keyFieldLocation, actualEntry.getValue(), expectedEntry.getValue())); + } } } @@ -506,13 +515,16 @@ private static void compareUnorderedMap(DualValue dualValue, ComparisonState com for (Map.Entry actualEntry : actualMap.entrySet()) { int deepHashCode = actualDeepHashCodesByKey.get(actualEntry.getKey()); Map.Entry expectedEntry = expectedEntriesByDeepHashCode.get(deepHashCode); - // Must split the Key and Value so that Map.Entry's equals() method is not used. - FieldLocation fieldLocation = dualValue.fieldLocation; - comparisonState.registerForComparison(new DualValue(fieldLocation, actualEntry.getKey(), expectedEntry.getKey())); - comparisonState.registerForComparison(new DualValue(fieldLocation, actualEntry.getValue(), expectedEntry.getValue())); + // since we have found an entry in expected with the actual entry key, we just need to compare entry values. + FieldLocation keyFieldLocation = keyFieldLocation(dualValue.fieldLocation, actualEntry.getKey()); + comparisonState.registerForComparison(new DualValue(keyFieldLocation, actualEntry.getValue(), expectedEntry.getValue())); } } + private static FieldLocation keyFieldLocation(FieldLocation parentFieldLocation, Object key) { + return key == null ? parentFieldLocation : parentFieldLocation.field(key.toString()); + } + private static void compareOptional(DualValue dualValue, ComparisonState comparisonState) { if (!dualValue.isActualFieldAnOptional()) { comparisonState.addDifference(dualValue, differentTypeErrorMessage(dualValue, "an Optional")); diff --git a/src/main/java/org/assertj/core/condition/Join.java b/src/main/java/org/assertj/core/condition/Join.java index 095a111bd0d..7a666df17ac 100644 --- a/src/main/java/org/assertj/core/condition/Join.java +++ b/src/main/java/org/assertj/core/condition/Join.java @@ -36,6 +36,9 @@ */ public abstract class Join extends Condition { + protected static final String SUFFIX_DELIMITER = "]"; + protected static final String PREFIX_DELIMITER = ":["; + @VisibleForTesting Collection> conditions; @@ -79,10 +82,12 @@ private static T checkNotNullConditions(T conditions) { * method used to calculate the the subclass join description */ private void calculateDescription() { - List descriptions = conditions.stream() - .map(Condition::description) - .collect(toList()); - describedAs(new JoinDescription(descriptionPrefix() + ":[", "]", descriptions)); + List conditionsDescriptions = conditions.stream() + .map(Condition::description) + .collect(toList()); + String prefix = descriptionPrefix() + PREFIX_DELIMITER; + String suffix = SUFFIX_DELIMITER; + describedAs(new JoinDescription(prefix, suffix, conditionsDescriptions)); } @Override @@ -91,6 +96,16 @@ public Description description() { return super.description(); } + @Override + public Description conditionDescriptionWithStatus(T actual) { + List descriptionsWithStatus = conditions.stream() + .map(condition -> condition.conditionDescriptionWithStatus(actual)) + .collect(toList()); + String prefix = status(actual).label + " " + descriptionPrefix() + PREFIX_DELIMITER; + String suffix = SUFFIX_DELIMITER; + return new JoinDescription(prefix, suffix, descriptionsWithStatus); + } + private static T notNull(T condition) { return requireNonNull(condition, "The given conditions should not have null entries"); } @@ -99,7 +114,7 @@ private static T notNull(T condition) { * Returns the conditions to join. * @return the conditions to join. */ - protected final Collection> conditions() { + public final Collection> conditions() { return unmodifiableCollection(conditions); } } diff --git a/src/main/java/org/assertj/core/condition/MappedCondition.java b/src/main/java/org/assertj/core/condition/MappedCondition.java new file mode 100644 index 00000000000..597526f69c3 --- /dev/null +++ b/src/main/java/org/assertj/core/condition/MappedCondition.java @@ -0,0 +1,143 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.condition; + +import static java.lang.String.format; +import static java.util.Objects.requireNonNull; + +import java.util.function.Function; + +import org.assertj.core.annotations.Beta; +import org.assertj.core.api.Condition; + +/** + * Container {@link Condition} that maps the object under test and then check the resulting mapped value against its nested {@link Condition}. + *

    + * Example: + *

     Condition<String> hasLineSeparator = new Condition<>(t -> t.contains(System.lineSeparator()), "has lineSeparator");
    + *
    + * Condition<Optional<String>> optionalWithLineSeparator = MappedCondition.mappedCondition(Optional::get, hasLineSeparator, "optional value has lineSeparator");
    + *
    + * // assertion succeeds
    + * assertThat(Optional.of("a" + System.lineSeparator())).is(optionalWithLineSeparator);
    + * // returns true
    + * optionalWithLineSeparator.matches(Optional.of("a" + System.lineSeparator()));
    + *
    + * // assertion fails
    + * assertThat(Optional.of("a")).is(optionalWithLineSeparator);
    + * // returns false
    + * optionalWithLineSeparator.matches(Optional.of("a"));
    + * + * @param the type of object this condition accepts. + * @param the type of object the nested condition accepts. + * + * @author Stefan Bischof + */ +@Beta +public class MappedCondition extends Condition { + + private Condition condition; + private Function mapping; + private String mappingDescription; + + /** + * Creates a new {@link MappedCondition}. + *

    + * Example: + *

     Condition<String> hasLineSeparator = new Condition<>(t -> t.contains(System.lineSeparator()), "has lineSeparator");
    +   *
    +   * Condition<Optional<String>> optionalWithLineSeparator = MappedCondition.mappedCondition(Optional::get, hasLineSeparator, "optional value has lineSeparator");
    +   *
    +   * // assertion succeeds
    +   * assertThat(Optional.of("a" + System.lineSeparator())).is(optionalWithLineSeparator);
    +   * // returns true
    +   * optionalWithLineSeparator.matches(Optional.of("a" + System.lineSeparator()));
    +   *
    +   * // assertion fails
    +   * assertThat(Optional.of("a")).is(optionalWithLineSeparator);
    +   * // returns false
    +   * optionalWithLineSeparator.matches(Optional.of("a"));
    + *

    + * Note that the mappingDescription argument follows {@link String#format(String, Object...)} syntax. + * + * @param the type of object the given condition accept. + * @param the type of object the nested condition accept. + * @param mapping the Function that maps the value to test to the a value for the nested condition. + * @param condition the nested condition to evaluate. + * @param mappingDescription describes the mapping, follows {@link String#format(String, Object...)} syntax. + * @param args for describing the mapping as in {@link String#format(String, Object...)} syntax. + * @return the created {@code MappedCondition}. + * @throws NullPointerException if the given condition is {@code null}. + * @throws NullPointerException if the given mapping is {@code null}. + */ + public static MappedCondition mappedCondition(Function mapping, Condition condition, + String mappingDescription, Object... args) { + requireNonNull(mappingDescription, "The given mappingDescription should not be null"); + return new MappedCondition<>(mapping, condition, format(mappingDescription, args)); + } + + /** + * Creates a new {@link MappedCondition} + * + * @param the type of object the given condition accept. + * @param the type of object the nested condition accept. + * @param mapping the Function that maps the value to test to the a value for the nested condition. + * @param condition the nested condition to evaluate. + * @return the created {@code MappedCondition}. + * @throws NullPointerException if the given condition is {@code null}. + * @throws NullPointerException if the given mapping is {@code null}. + */ + public static MappedCondition mappedCondition(Function mapping, Condition condition) { + return mappedCondition(mapping, condition, ""); + } + + private MappedCondition(Function mapping, Condition condition, String mappingDescription) { + requireNonNull(condition, "The given condition should not be null"); + requireNonNull(mapping, "The given mapping function should not be null"); + this.mapping = mapping; + this.mappingDescription = mappingDescription; + this.condition = condition; + } + + /** + * Maps the value with the given function and verifies that it satisfies the nested {@link Condition}. + * + * @param value the value to map + * @return {@code true} if the given mapped value satisfies the nested condition; {@code false} otherwise. + */ + @Override + public boolean matches(FROM value) { + TO mappedObject = mapping.apply(value); + String desc = buildMappingDescription(value, mappedObject); + describedAs(desc); + return condition.matches(mappedObject); + } + + /** + * Build the mapped condition description when applied with the FROM and TO values. + * + * @param from the value to map + * @param to the mapped value + * @return the mapped condition description . + */ + protected String buildMappingDescription(FROM from, TO to) { + StringBuilder sb = new StringBuilder("mapped"); + if (!mappingDescription.isEmpty()) sb.append(format("%n using: %s", mappingDescription)); + sb.append(format("%n from: <%s> %s%n", from.getClass().getSimpleName(), from)); + sb.append(format(" to: <%s> %s%n", to.getClass().getSimpleName(), from, to)); + sb.append(" then checked:"); + sb.append(format("%n %-10s", condition)); + return sb.toString(); + } + +} diff --git a/src/main/java/org/assertj/core/condition/VerboseCondition.java b/src/main/java/org/assertj/core/condition/VerboseCondition.java new file mode 100644 index 00000000000..e64135523ed --- /dev/null +++ b/src/main/java/org/assertj/core/condition/VerboseCondition.java @@ -0,0 +1,133 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.condition; + +import static java.lang.String.format; +import static java.util.Objects.requireNonNull; + +import java.util.function.Function; +import java.util.function.Predicate; + +import org.assertj.core.annotations.Beta; +import org.assertj.core.api.AbstractAssert; +import org.assertj.core.api.Condition; + +/** + * {@link Condition} that shows the value under test when the condition fails thanks to the specified {@code objectUnderTestDescriptor} function. + * + *

    + * When defining the {@code objectUnderTestDescriptor} function, you should take in consideration whether the condition is going to be used + * with {@link AbstractAssert#is(Condition) is(Condition)} or {@link AbstractAssert#has(Condition) has(Condition)} since the start of the error message is different between the two. + *

    + * Let's see how it works with an example that works well with {@link AbstractAssert#is(Condition) is(Condition)}: + *

     Condition<String> shorterThan4 = VerboseCondition.verboseCondition(actual -> actual.length() < 4,
    +                                                                   // predicate description  
    +                                                                   "shorter than 4",
    +                                                                   // value under test description transformation function
    +                                                                   s -> String.format(" but length was %s", s.length(), s));
    + * + * If we execute: + *
     assertThat("foooo").is(shorterThan4);
    + * it fails with the following assertion error: + *
     Expecting actual:
    + *   "foooo"
    + * to be shorter than 4 but length was 5
    + *

    + * Note that the beginning of the error message looks nice with {@link AbstractAssert#is(Condition) is(Condition)}, but not so much with {@link AbstractAssert#has(Condition) has(Condition)}: + *

     Expecting actual:
    + *   "foooo"
    + * to have shorter than 4 but length was 5
    + *

    + * The {@code objectUnderTestDescriptor} must not be null, if you don't need one this probably means you can simply use {@link Condition#Condition(Predicate, String, Object...)} instead of a {@code VerboseCondition}. + * + * @param the type of object the given condition accept. + * + * @author Stefan Bischof + */ +@Beta +public final class VerboseCondition extends Condition { + + private Function objectUnderTestDescriptor; + + // needed to avoid an incorrect description when matches is run multiple times. + private String description; + + /** + * Creates a new {@link VerboseCondition} to have better control over the condition description when the condition fails thanks + * to the {@code objectUnderTestDescriptor} function parameter. + *

    + * When defining the {@code objectUnderTestDescriptor} function, you should take in consideration whether the condition is going to be used + * with {@link AbstractAssert#is(Condition) is(Condition)} or {@link AbstractAssert#has(Condition) has(Condition)} since the start of the error message is different between the two. + *

    + * Let's see how it works with an example that works well with {@link AbstractAssert#is(Condition) is(Condition)}: + *

     Condition<String> shorterThan4 = VerboseCondition.verboseCondition(actual -> actual.length() < 4,
    +                                                                    // predicate description  
    +                                                                    "shorter than 4",
    +                                                                    // value under test description transformation function
    +                                                                    s -> String.format(" but length was %s", s.length(), s));
    + * + * If we execute: + *
     assertThat("foooo").is(shorterThan4);
    + * it fails with the following assertion error: + *
     Expecting actual:
    +   *   "foooo"
    +   * to be shorter than 4 but length was 5
    + *

    + * Note that the beginning of the error message looks nice with {@link AbstractAssert#is(Condition) is(Condition)}, but not so much with {@link AbstractAssert#has(Condition) has(Condition)}: + *

     Expecting actual:
    +   *   "foooo"
    +   * to have shorter than 4 but length was 5
    + *

    + * The {@code objectUnderTestDescriptor} must not be null, if you don't need one this probably means you can simply use {@link Condition#Condition(Predicate, String, Object...)} instead of a {@code VerboseCondition}. + * + * @param the type of object the given condition accept. + * @param predicate the Predicate that tests the value to test. + * @param description describes the Condition verbal. + * @param objectUnderTestDescriptor Function used to describe the value to test when the actual value does not match the predicate. must not be null. + * @return the created {@code VerboseCondition}. + * @throws NullPointerException if the predicate is {@code null}. + * @throws NullPointerException if the objectUnderTestDescriptor is {@code null}. + */ + public static VerboseCondition verboseCondition(Predicate predicate, String description, + Function objectUnderTestDescriptor) { + return new VerboseCondition<>(predicate, description, objectUnderTestDescriptor); + } + + private VerboseCondition(Predicate predicate, String description, Function objectUnderTestDescriptor) { + super(predicate, description); + this.description = description; + this.objectUnderTestDescriptor = requireNonNull(objectUnderTestDescriptor, + "The objectUnderTest descriptor function must not be null, if you don't need one, consider using the basic Condition(Predicate predicate, String description, Object... args) constructor"); + } + + @Override + public boolean matches(T objectUnderTest) { + boolean matches = super.matches(objectUnderTest); + describedAs(buildVerboseDescription(objectUnderTest, matches)); + return matches; + } + + /** + * Build the verbose condition description when applied with the actual values and the match result. + * + * @param objectUnderTest the object to test + * @param matches the result of the match operation + * @return the verbose condition description. + */ + protected String buildVerboseDescription(T objectUnderTest, boolean matches) { + StringBuilder sb = new StringBuilder(format("%s", description)); + if (!matches) sb.append(objectUnderTestDescriptor.apply(objectUnderTest)); + return sb.toString(); + } + +} diff --git a/src/main/java/org/assertj/core/configuration/Configuration.java b/src/main/java/org/assertj/core/configuration/Configuration.java index 40b7273258c..b81e0e44db8 100644 --- a/src/main/java/org/assertj/core/configuration/Configuration.java +++ b/src/main/java/org/assertj/core/configuration/Configuration.java @@ -23,6 +23,7 @@ import java.util.function.Consumer; import java.util.stream.Stream; +import org.assertj.core.api.AbstractDateAssert; import org.assertj.core.api.Assertions; import org.assertj.core.description.Description; import org.assertj.core.presentation.Representation; @@ -337,6 +338,9 @@ public void apply() { Assertions.setDescriptionConsumer(descriptionConsumer()); Assertions.setPrintAssertionsDescription(printAssertionsDescription()); Assertions.setMaxStackTraceElementsDisplayed(maxStackTraceElementsDisplayed()); + // reset the default date formats otherwise a custom config would register them and when another config is applied it would + // add to the previous config date formats + AbstractDateAssert.useDefaultDateFormatsOnly(); additionalDateFormats().forEach(Assertions::registerCustomDateFormat); } diff --git a/src/main/java/org/assertj/core/data/Offset.java b/src/main/java/org/assertj/core/data/Offset.java index 61f85c13338..b3cb8346c67 100644 --- a/src/main/java/org/assertj/core/data/Offset.java +++ b/src/main/java/org/assertj/core/data/Offset.java @@ -12,6 +12,8 @@ */ package org.assertj.core.data; +import static java.lang.String.format; +import static java.util.Objects.hash; import static java.util.Objects.requireNonNull; import static org.assertj.core.util.Preconditions.checkArgument; @@ -29,7 +31,7 @@ public final class Offset { public final T value; /** - * When |actual-expected|=offset and strict is true the assertThat(actual).isCloseTo(expected, offset); assertion will fail. + * When |actual-expected|=offset and strict is true the assertThat(actual).isCloseTo(expected, offset); assertion will fail. */ public final boolean strict; @@ -94,12 +96,12 @@ public boolean equals(Object obj) { @Override public int hashCode() { - return Objects.hash(value, strict); + return hash(value, strict); } @Override public String toString() { - return String.format("%s[value=%s]", getClass().getSimpleName(), value); + return format("%s%s[value=%s]", strict ? "strict " : "", getClass().getSimpleName(), value); } } diff --git a/src/main/java/org/assertj/core/data/TemporalUnitOffset.java b/src/main/java/org/assertj/core/data/TemporalUnitOffset.java index 6a96ea3792b..234a63554f1 100644 --- a/src/main/java/org/assertj/core/data/TemporalUnitOffset.java +++ b/src/main/java/org/assertj/core/data/TemporalUnitOffset.java @@ -20,6 +20,7 @@ import java.time.Duration; import java.time.temporal.Temporal; import java.time.temporal.TemporalUnit; +import java.util.Objects; /** * Base class for {@link TemporalOffset} on basis of {@link TemporalUnit}. @@ -86,4 +87,18 @@ public TemporalUnit getUnit() { return unit; } + @Override + public int hashCode() { + return Objects.hash(value); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; + TemporalUnitOffset other = (TemporalUnitOffset) obj; + return value == other.value; + } + } diff --git a/src/main/java/org/assertj/core/error/ClassModifierShouldBe.java b/src/main/java/org/assertj/core/error/ClassModifierShouldBe.java index 5617f5a6e17..1123fb2c1f5 100644 --- a/src/main/java/org/assertj/core/error/ClassModifierShouldBe.java +++ b/src/main/java/org/assertj/core/error/ClassModifierShouldBe.java @@ -29,7 +29,7 @@ public class ClassModifierShouldBe extends BasicErrorMessageFactory { private static final String PACKAGE_PRIVATE = "package-private"; private ClassModifierShouldBe(Class actual, boolean positive, String modifier) { - super("%nExpecting:%n %s%n" + (positive ? "to" : "not to") + " be a %s class but was %s.", + super("%nExpecting actual:%n %s%n" + (positive ? "to" : "not to") + " be a %s class but was %s.", actual, modifier, modifiers(actual)); } diff --git a/src/main/java/org/assertj/core/error/ConditionAndGroupGenericParameterTypeShouldBeTheSame.java b/src/main/java/org/assertj/core/error/ConditionAndGroupGenericParameterTypeShouldBeTheSame.java index f7188d057a4..ee2c9453464 100644 --- a/src/main/java/org/assertj/core/error/ConditionAndGroupGenericParameterTypeShouldBeTheSame.java +++ b/src/main/java/org/assertj/core/error/ConditionAndGroupGenericParameterTypeShouldBeTheSame.java @@ -24,7 +24,7 @@ public class ConditionAndGroupGenericParameterTypeShouldBeTheSame extends BasicErrorMessageFactory { public ConditionAndGroupGenericParameterTypeShouldBeTheSame(Object actual, Condition condition) { - super("%nExpecting: %s to have the same generic type as condition %s", actual, condition); + super("%nExpecting actual: %s to have the same generic type as condition %s", actual, condition); } /** diff --git a/src/main/java/org/assertj/core/error/GroupTypeDescription.java b/src/main/java/org/assertj/core/error/GroupTypeDescription.java index 11625441f9e..d27273ea494 100644 --- a/src/main/java/org/assertj/core/error/GroupTypeDescription.java +++ b/src/main/java/org/assertj/core/error/GroupTypeDescription.java @@ -42,12 +42,21 @@ public String getGroupTypeName() { * @return the created GroupTypeDescription object */ public static GroupTypeDescription getGroupTypeDescription(Object actual) { + return getGroupTypeDescription(actual.getClass()); + } + + /** + * Creates a new {@link GroupTypeDescription} for a group of elements. + * + * @param clazz the class for the group of elements. + * @return the created GroupTypeDescription object + */ + public static GroupTypeDescription getGroupTypeDescription(Class clazz) { - Class clazz = actual.getClass(); if (Thread.currentThread().getStackTrace()[SPLITERATORS_CLASS_STACK_TRACE_NUM].getClassName().contains("Spliterators")) return new GroupTypeDescription("spliterator characteristics", "characteristics"); - if (actual instanceof Map) return new GroupTypeDescription("map", "map entries"); + if (Map.class.isAssignableFrom(clazz)) return new GroupTypeDescription("map", "map entries"); if (clazz.isArray()) return new GroupTypeDescription(clazz.getSimpleName(), clazz.getComponentType().getSimpleName().toLowerCase() + "(s)"); diff --git a/src/main/java/org/assertj/core/error/OptionalDoubleShouldHaveValueCloseToOffset.java b/src/main/java/org/assertj/core/error/OptionalDoubleShouldHaveValueCloseToOffset.java index b21530ed88a..ed9c9c3e84c 100644 --- a/src/main/java/org/assertj/core/error/OptionalDoubleShouldHaveValueCloseToOffset.java +++ b/src/main/java/org/assertj/core/error/OptionalDoubleShouldHaveValueCloseToOffset.java @@ -26,7 +26,7 @@ public class OptionalDoubleShouldHaveValueCloseToOffset extends BasicErrorMessag private OptionalDoubleShouldHaveValueCloseToOffset(OptionalDouble actual, double expected, Offset offset, double difference) { - super("%nExpecting:%n %s%nto be close to:%n %s%n" + + super("%nExpecting actual:%n %s%nto be close to:%n %s%n" + "by less than %s but difference was %s.%n" + "(a difference of exactly %s being considered valid)", actual, expected, offset.value, difference, offset.value); diff --git a/src/main/java/org/assertj/core/error/OptionalDoubleShouldHaveValueCloseToPercentage.java b/src/main/java/org/assertj/core/error/OptionalDoubleShouldHaveValueCloseToPercentage.java index a6cb32aa933..490a1e3cc58 100644 --- a/src/main/java/org/assertj/core/error/OptionalDoubleShouldHaveValueCloseToPercentage.java +++ b/src/main/java/org/assertj/core/error/OptionalDoubleShouldHaveValueCloseToPercentage.java @@ -33,7 +33,7 @@ private OptionalDoubleShouldHaveValueCloseToPercentage(double expected) { private OptionalDoubleShouldHaveValueCloseToPercentage(OptionalDouble actual, double expected, Percentage percentage, double expectedPercentage) { - super("%nExpecting:%n" + + super("%nExpecting actual:%n" + " %s%n" + "to be close to:%n" + " %s%n" + diff --git a/src/main/java/org/assertj/core/error/OptionalShouldContain.java b/src/main/java/org/assertj/core/error/OptionalShouldContain.java index a31d0213bcc..71f64c5273c 100644 --- a/src/main/java/org/assertj/core/error/OptionalShouldContain.java +++ b/src/main/java/org/assertj/core/error/OptionalShouldContain.java @@ -28,8 +28,8 @@ */ public class OptionalShouldContain extends BasicErrorMessageFactory { - private static final String EXPECTING_TO_CONTAIN = "%nExpecting:%n %s%nto contain:%n %s%nbut did not."; - private static final String EXPECTING_TO_CONTAIN_SAME = "%nExpecting:%n %s%nto contain the instance (i.e. compared with ==):%n %s%nbut did not."; + private static final String EXPECTING_TO_CONTAIN = "%nExpecting actual:%n %s%nto contain:%n %s%nbut did not."; + private static final String EXPECTING_TO_CONTAIN_SAME = "%nExpecting actual:%n %s%nto contain the instance (i.e. compared with ==):%n %s%nbut did not."; private OptionalShouldContain(String message, Object actual, Object expected) { super(message, actual, expected); diff --git a/src/main/java/org/assertj/core/error/OptionalShouldContainInstanceOf.java b/src/main/java/org/assertj/core/error/OptionalShouldContainInstanceOf.java index c4b882a6d95..eee402e80f4 100644 --- a/src/main/java/org/assertj/core/error/OptionalShouldContainInstanceOf.java +++ b/src/main/java/org/assertj/core/error/OptionalShouldContainInstanceOf.java @@ -38,11 +38,11 @@ private OptionalShouldContainInstanceOf(String message) { public static OptionalShouldContainInstanceOf shouldContainInstanceOf(Object value, Class clazz) { Optional optional = (Optional) value; if (optional.isPresent()) { - return new OptionalShouldContainInstanceOf(format("%nExpecting:%n %s%nto contain a value that is an instance of:%n %s%nbut did contain an instance of:%n %s", + return new OptionalShouldContainInstanceOf(format("%nExpecting actual:%n %s%nto contain a value that is an instance of:%n %s%nbut did contain an instance of:%n %s", optional.getClass().getSimpleName(), clazz.getName(), optional.get().getClass().getName())); } - return new OptionalShouldContainInstanceOf(format("%nExpecting:%n %s%nto contain a value that is an instance of:%n %s%nbut was empty", + return new OptionalShouldContainInstanceOf(format("%nExpecting actual:%n %s%nto contain a value that is an instance of:%n %s%nbut was empty", optional.getClass().getSimpleName(), clazz.getName())); } } diff --git a/src/main/java/org/assertj/core/error/ShouldAccept.java b/src/main/java/org/assertj/core/error/ShouldAccept.java index 6c4abe352df..ba848782bb1 100644 --- a/src/main/java/org/assertj/core/error/ShouldAccept.java +++ b/src/main/java/org/assertj/core/error/ShouldAccept.java @@ -42,6 +42,6 @@ public static ErrorMessageFactory shouldAccept(Predicate predicat } private ShouldAccept(Object value, PredicateDescription description) { - super("%nExpecting:%n %s predicate%nto accept %s but it did not.", description, value); + super("%nExpecting actual:%n %s predicate%nto accept %s but it did not.", description, value); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBe.java b/src/main/java/org/assertj/core/error/ShouldBe.java index cb4a4d2f521..98c8dec4d7a 100644 --- a/src/main/java/org/assertj/core/error/ShouldBe.java +++ b/src/main/java/org/assertj/core/error/ShouldBe.java @@ -13,11 +13,12 @@ package org.assertj.core.error; import org.assertj.core.api.Condition; +import org.assertj.core.condition.AllOf; /** * Creates an error message indicating that an assertion that verifies that a value satisfies a {@link Condition} * failed. - * + * * @author Yvonne Wang * @author Mikhail Mazursky */ @@ -31,10 +32,21 @@ public class ShouldBe extends BasicErrorMessageFactory { * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldBe(T actual, Condition condition) { + if (condition instanceof AllOf) return new ShouldBe(actual, (AllOf) condition); return new ShouldBe(actual, condition); } private ShouldBe(Object actual, Condition condition) { - super("%nExpecting:%n %s%nto be %s", actual, condition); + super("%nExpecting actual:%n %s%nto be %s", actual, condition); + } + + private ShouldBe(T actual, AllOf allOf) { + super("%n" + + "Expecting actual:%n" + + " %s%n" + + // use concatenation to avoid the string to be double quoted later on + "to be:%n" + allOf.conditionDescriptionWithStatus(actual), + actual); } + } diff --git a/src/main/java/org/assertj/core/error/ShouldBeAbsolutePath.java b/src/main/java/org/assertj/core/error/ShouldBeAbsolutePath.java index 52094804424..d362b96b5d7 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeAbsolutePath.java +++ b/src/main/java/org/assertj/core/error/ShouldBeAbsolutePath.java @@ -28,7 +28,7 @@ public class ShouldBeAbsolutePath extends BasicErrorMessageFactory { @VisibleForTesting - public static final String SHOULD_BE_ABSOLUTE_PATH = "%nExpecting:%n %s%nto be an absolute path."; + public static final String SHOULD_BE_ABSOLUTE_PATH = "%nExpecting actual:%n %s%nto be an absolute path."; /** * Creates a new {@link ShouldBeAbsolutePath}. diff --git a/src/main/java/org/assertj/core/error/ShouldBeAbstract.java b/src/main/java/org/assertj/core/error/ShouldBeAbstract.java index 7dd6d1d910c..1fc175dfa72 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeAbstract.java +++ b/src/main/java/org/assertj/core/error/ShouldBeAbstract.java @@ -19,6 +19,6 @@ public static ErrorMessageFactory shouldBeAbstract(Class actual) { } private ShouldBeAbstract(Class actual) { - super("%nExpecting:%n %s%nto be abstract", actual); + super("%nExpecting actual:%n %s%nto be abstract", actual); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeAfter.java b/src/main/java/org/assertj/core/error/ShouldBeAfter.java index f11a83d325e..735a7e4175a 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeAfter.java +++ b/src/main/java/org/assertj/core/error/ShouldBeAfter.java @@ -60,6 +60,6 @@ public static ErrorMessageFactory shouldBeAfter(Date actual, int year) { } private ShouldBeAfter(Object actual, Object other, ComparisonStrategy comparisonStrategy) { - super("%nExpecting:%n %s%nto be strictly after:%n %s%n%s", actual, other, comparisonStrategy); + super("%nExpecting actual:%n %s%nto be strictly after:%n %s%n%s", actual, other, comparisonStrategy); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeAfterOrEqualTo.java b/src/main/java/org/assertj/core/error/ShouldBeAfterOrEqualTo.java index 0170cb88ff1..844a8ac2d8b 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeAfterOrEqualTo.java +++ b/src/main/java/org/assertj/core/error/ShouldBeAfterOrEqualTo.java @@ -47,6 +47,6 @@ public static ErrorMessageFactory shouldBeAfterOrEqualTo(Object actual, Object o } private ShouldBeAfterOrEqualTo(Object actual, Object other, ComparisonStrategy comparisonStrategy) { - super("%nExpecting:%n %s%nto be after or equal to:%n %s%n%s", actual, other, comparisonStrategy); + super("%nExpecting actual:%n %s%nto be after or equal to:%n %s%n%s", actual, other, comparisonStrategy); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeAtIndex.java b/src/main/java/org/assertj/core/error/ShouldBeAtIndex.java index 60fa7086528..b6ec3868092 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeAtIndex.java +++ b/src/main/java/org/assertj/core/error/ShouldBeAtIndex.java @@ -39,6 +39,6 @@ public static ErrorMessageFactory shouldBeAtIndex(List actual, } private ShouldBeAtIndex(List actual, Condition condition, Index index, T found) { - super("%nExpecting:%n %s%nat index %s to be:%n %s%nin:%n %s%n", found, index.value, condition, actual); + super("%nExpecting actual:%n %s%nat index %s to be:%n %s%nin:%n %s%n", found, index.value, condition, actual); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeBefore.java b/src/main/java/org/assertj/core/error/ShouldBeBefore.java index fa9b105faa3..849a2450568 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeBefore.java +++ b/src/main/java/org/assertj/core/error/ShouldBeBefore.java @@ -45,6 +45,6 @@ public static ErrorMessageFactory shouldBeBefore(Object actual, Object other) { } private ShouldBeBefore(Object actual, Object other, ComparisonStrategy comparisonStrategy) { - super("%nExpecting:%n %s%nto be strictly before:%n %s%n%s", actual, other, comparisonStrategy); + super("%nExpecting actual:%n %s%nto be strictly before:%n %s%n%s", actual, other, comparisonStrategy); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeBeforeOrEqualTo.java b/src/main/java/org/assertj/core/error/ShouldBeBeforeOrEqualTo.java index 21d647112eb..38ce29daefa 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeBeforeOrEqualTo.java +++ b/src/main/java/org/assertj/core/error/ShouldBeBeforeOrEqualTo.java @@ -47,6 +47,6 @@ public static ErrorMessageFactory shouldBeBeforeOrEqualTo(Object actual, Object } private ShouldBeBeforeOrEqualTo(Object actual, Object other, ComparisonStrategy comparisonStrategy) { - super("%nExpecting:%n %s%nto be before or equal to:%n %s%n%s", actual, other, comparisonStrategy); + super("%nExpecting actual:%n %s%nto be before or equal to:%n %s%n%s", actual, other, comparisonStrategy); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeBetween.java b/src/main/java/org/assertj/core/error/ShouldBeBetween.java index 529cdd25ba0..3488db9169c 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeBetween.java +++ b/src/main/java/org/assertj/core/error/ShouldBeBetween.java @@ -88,13 +88,13 @@ public static > ErrorMessageFactory shouldBeBetw private ShouldBeBetween(Date actual, Date start, Date end, boolean inclusiveStart, boolean inclusiveEnd, ComparisonStrategy comparisonStrategy) { - super("%nExpecting:%n %s%nto be in period:%n " + (inclusiveStart ? '[' : ']') + "%s, %s" + + super("%nExpecting actual:%n %s%nto be in period:%n " + (inclusiveStart ? '[' : ']') + "%s, %s" + (inclusiveEnd ? ']' : '[') + "%n%s", actual, start, end, comparisonStrategy); } private > ShouldBeBetween(T actual, T start, T end, boolean inclusiveStart, boolean inclusiveEnd, ComparisonStrategy comparisonStrategy) { - super("%nExpecting:%n %s%nto be between:%n " + (inclusiveStart ? '[' : ']') + super("%nExpecting actual:%n %s%nto be between:%n " + (inclusiveStart ? '[' : ']') + "%s, %s" + (inclusiveEnd ? ']' : '[') + "%n%s", actual, start, end, comparisonStrategy); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeCanonicalPath.java b/src/main/java/org/assertj/core/error/ShouldBeCanonicalPath.java index 061192f5ce8..5980aa40212 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeCanonicalPath.java +++ b/src/main/java/org/assertj/core/error/ShouldBeCanonicalPath.java @@ -22,7 +22,7 @@ */ public class ShouldBeCanonicalPath extends BasicErrorMessageFactory { @VisibleForTesting - public static final String SHOULD_BE_CANONICAL = "%nExpecting:%n %s%nto be a canonical path"; + public static final String SHOULD_BE_CANONICAL = "%nExpecting actual:%n %s%nto be a canonical path"; public static ErrorMessageFactory shouldBeCanonicalPath(final Path actual) { return new ShouldBeCanonicalPath(actual); diff --git a/src/main/java/org/assertj/core/error/ShouldBeCloseTo.java b/src/main/java/org/assertj/core/error/ShouldBeCloseTo.java index 3c28bbdd28a..f8166748cc3 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeCloseTo.java +++ b/src/main/java/org/assertj/core/error/ShouldBeCloseTo.java @@ -61,16 +61,16 @@ private ShouldBeCloseTo(Date actual, Date other, long deltaInMilliseconds, long // seems equal in the error message. // Use standard formatting to avoid calling ToString.toStringOf for long that adds a 'L' (like 100L) to // differentiate integer from long (here there is no ambiguity). - super(format("%nExpecting:%n %s%nto be close to:%n %s%nby less than %sms but difference was %sms", + super(format("%nExpecting actual:%n %s%nto be close to:%n %s%nby less than %sms but difference was %sms", formatAsDatetimeWithMs(actual), formatAsDatetimeWithMs(other), deltaInMilliseconds, difference)); } private ShouldBeCloseTo(Temporal actual, Temporal other, String differenceDescription) { - super(format("%nExpecting:%n %s%nto be close to:%n %s%n%s", actual, other, differenceDescription)); + super(format("%nExpecting actual:%n %s%nto be close to:%n %s%n%s", actual, other, differenceDescription)); } private ShouldBeCloseTo(TemporalAmount actual, TemporalAmount other, TemporalAmount offset, TemporalAmount difference) { - super(format("%nExpecting:%n %s%nto be close to:%n %s%nwithin %s but difference was %s", actual, other, offset, + super(format("%nExpecting actual:%n %s%nto be close to:%n %s%nwithin %s but difference was %s", actual, other, offset, difference)); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeEmptyDirectory.java b/src/main/java/org/assertj/core/error/ShouldBeEmptyDirectory.java index 412cdde99d0..fd5e69366f8 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeEmptyDirectory.java +++ b/src/main/java/org/assertj/core/error/ShouldBeEmptyDirectory.java @@ -21,7 +21,7 @@ public class ShouldBeEmptyDirectory extends BasicErrorMessageFactory { @VisibleForTesting - public static final String SHOULD_BE_EMPTY_DIRECTORY = "%nExpecting:%n %s%nto be an empty directory but it contained:%n %s"; + public static final String SHOULD_BE_EMPTY_DIRECTORY = "%nExpecting actual:%n %s%nto be an empty directory but it contained:%n %s"; public static ErrorMessageFactory shouldBeEmptyDirectory(final Path actual, List directoryContent) { return new ShouldBeEmptyDirectory(actual, directoryContent); diff --git a/src/main/java/org/assertj/core/error/ShouldBeEqual.java b/src/main/java/org/assertj/core/error/ShouldBeEqual.java index 4ee4e828239..fd0723563d9 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeEqual.java +++ b/src/main/java/org/assertj/core/error/ShouldBeEqual.java @@ -41,7 +41,7 @@ */ public class ShouldBeEqual implements AssertionErrorFactory { - private static final String EXPECTED_BUT_WAS_MESSAGE = "%nexpected: %s%nbut was : %s"; + private static final String EXPECTED_BUT_WAS_MESSAGE = "%nexpected: %s%n but was: %s"; private static final String EXPECTED_BUT_WAS_MESSAGE_USING_COMPARATOR = EXPECTED_BUT_WAS_MESSAGE + "%n%s"; private static final Class[] MSG_ARG_TYPES = array(String.class, String.class, String.class); private static final Class[] MSG_ARG_TYPES_FOR_ASSERTION_FAILED_ERROR = array(String.class, Object.class, diff --git a/src/main/java/org/assertj/core/error/ShouldBeEqualByComparingFieldByFieldRecursively.java b/src/main/java/org/assertj/core/error/ShouldBeEqualByComparingFieldByFieldRecursively.java index b9e7f4b88d8..6309998b372 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeEqualByComparingFieldByFieldRecursively.java +++ b/src/main/java/org/assertj/core/error/ShouldBeEqualByComparingFieldByFieldRecursively.java @@ -54,7 +54,7 @@ public static ErrorMessageFactory shouldBeEqualByComparingFieldByFieldRecursivel String differencesCount = differences.size() == 1 ? "difference:%n" : "%s differences:%n"; // @format:off return new ShouldBeEqualByComparingFieldByFieldRecursively("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " %s%n" + "to be equal to:%n" + " %s%n" + diff --git a/src/main/java/org/assertj/core/error/ShouldBeEqualIgnoringCase.java b/src/main/java/org/assertj/core/error/ShouldBeEqualIgnoringCase.java index ec3ffce4dec..9966635bb55 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeEqualIgnoringCase.java +++ b/src/main/java/org/assertj/core/error/ShouldBeEqualIgnoringCase.java @@ -31,6 +31,6 @@ public static ErrorMessageFactory shouldBeEqual(CharSequence actual, CharSequenc } private ShouldBeEqualIgnoringCase(CharSequence actual, CharSequence expected) { - super("%nexpected: %s%nbut was : %s%nignoring case considerations", expected, actual); + super("%nexpected: %s%n but was: %s%nignoring case considerations", expected, actual); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeEqualIgnoringHours.java b/src/main/java/org/assertj/core/error/ShouldBeEqualIgnoringHours.java index 31bab9fcb22..fa16c9714a9 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeEqualIgnoringHours.java +++ b/src/main/java/org/assertj/core/error/ShouldBeEqualIgnoringHours.java @@ -34,6 +34,6 @@ public static ErrorMessageFactory shouldBeEqualIgnoringHours(Object actual, Obje } private ShouldBeEqualIgnoringHours(Object actual, Object other) { - super("%nExpecting:%n %s%nto have same year, month and day as:%n %s%nbut had not.", actual, other); + super("%nExpecting actual:%n %s%nto have same year, month and day as:%n %s%nbut had not.", actual, other); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeEqualIgnoringMinutes.java b/src/main/java/org/assertj/core/error/ShouldBeEqualIgnoringMinutes.java index 0615759beb6..1ee1a60d848 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeEqualIgnoringMinutes.java +++ b/src/main/java/org/assertj/core/error/ShouldBeEqualIgnoringMinutes.java @@ -65,14 +65,14 @@ public static ErrorMessageFactory shouldBeEqualIgnoringMinutes(OffsetTime actual } private ShouldBeEqualIgnoringMinutes(Object actual, Object other) { - super("%nExpecting:%n %s%nto have same year, month, day and hour as:%n %s%nbut had not.", actual, other); + super("%nExpecting actual:%n %s%nto have same year, month, day and hour as:%n %s%nbut had not.", actual, other); } private ShouldBeEqualIgnoringMinutes(LocalTime actual, LocalTime other) { - super("%nExpecting:%n %s%nto have same hour as:%n %s%nbut had not.", actual, other); + super("%nExpecting actual:%n %s%nto have same hour as:%n %s%nbut had not.", actual, other); } private ShouldBeEqualIgnoringMinutes(OffsetTime actual, OffsetTime other) { - super("%nExpecting:%n %s%nto have same hour as:%n %s%nbut had not.", actual, other); + super("%nExpecting actual:%n %s%nto have same hour as:%n %s%nbut had not.", actual, other); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeEqualIgnoringNanos.java b/src/main/java/org/assertj/core/error/ShouldBeEqualIgnoringNanos.java index 86165d9caa3..4aa95bb8026 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeEqualIgnoringNanos.java +++ b/src/main/java/org/assertj/core/error/ShouldBeEqualIgnoringNanos.java @@ -63,15 +63,15 @@ public static ErrorMessageFactory shouldBeEqualIgnoringNanos(OffsetTime actual, } private ShouldBeEqualIgnoringNanos(Object actual, Object other) { - super("%nExpecting:%n %s%nto have same year, month, day, hour, minute and second as:%n %s%nbut had not.", + super("%nExpecting actual:%n %s%nto have same year, month, day, hour, minute and second as:%n %s%nbut had not.", actual, other); } private ShouldBeEqualIgnoringNanos(LocalTime actual, LocalTime other) { - super("%nExpecting:%n %s%nto have same hour, minute and second as:%n %s%nbut had not.", actual, other); + super("%nExpecting actual:%n %s%nto have same hour, minute and second as:%n %s%nbut had not.", actual, other); } private ShouldBeEqualIgnoringNanos(OffsetTime actual, OffsetTime other) { - super("%nExpecting:%n %s%nto have same hour, minute and second as:%n %s%nbut had not.", actual, other); + super("%nExpecting actual:%n %s%nto have same hour, minute and second as:%n %s%nbut had not.", actual, other); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeEqualIgnoringNewLines.java b/src/main/java/org/assertj/core/error/ShouldBeEqualIgnoringNewLines.java index f85ccc89039..33b023268c9 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeEqualIgnoringNewLines.java +++ b/src/main/java/org/assertj/core/error/ShouldBeEqualIgnoringNewLines.java @@ -20,7 +20,7 @@ public static ErrorMessageFactory shouldBeEqualIgnoringNewLines(CharSequence act private ShouldBeEqualIgnoringNewLines(CharSequence actual, CharSequence expected) { super("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " %s%n" + "to be equal to:%n" + " %s%n" + diff --git a/src/main/java/org/assertj/core/error/ShouldBeEqualIgnoringSeconds.java b/src/main/java/org/assertj/core/error/ShouldBeEqualIgnoringSeconds.java index 40894f5dd18..8625b929e86 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeEqualIgnoringSeconds.java +++ b/src/main/java/org/assertj/core/error/ShouldBeEqualIgnoringSeconds.java @@ -43,7 +43,7 @@ public static ErrorMessageFactory shouldBeEqualIgnoringSeconds(Object actual, Ob } private ShouldBeEqualIgnoringSeconds(Object actual, Object other) { - super("%nExpecting:%n %s%nto have same year, month, day, hour and minute as:%n %s%nbut had not.", actual, other); + super("%nExpecting actual:%n %s%nto have same year, month, day, hour and minute as:%n %s%nbut had not.", actual, other); } /** @@ -69,10 +69,10 @@ public static ErrorMessageFactory shouldBeEqualIgnoringSeconds(OffsetTime actual } private ShouldBeEqualIgnoringSeconds(LocalTime actual, LocalTime other) { - super("%nExpecting:%n %s%nto have same hour and minute as:%n %s%nbut had not.", actual, other); + super("%nExpecting actual:%n %s%nto have same hour and minute as:%n %s%nbut had not.", actual, other); } private ShouldBeEqualIgnoringSeconds(OffsetTime actual, OffsetTime other) { - super("%nExpecting:%n %s%nto have same hour and minute as:%n %s%nbut had not.", actual, other); + super("%nExpecting actual:%n %s%nto have same hour and minute as:%n %s%nbut had not.", actual, other); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeEqualIgnoringTimezone.java b/src/main/java/org/assertj/core/error/ShouldBeEqualIgnoringTimezone.java index 15bcf13d900..62bbe284095 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeEqualIgnoringTimezone.java +++ b/src/main/java/org/assertj/core/error/ShouldBeEqualIgnoringTimezone.java @@ -46,6 +46,6 @@ public static ErrorMessageFactory shouldBeEqualIgnoringTimezone(OffsetDateTime a } private ShouldBeEqualIgnoringTimezone(Object actual, Object other) { - super("%nExpecting:%n %s%nto have same time fields except timezone as:%n %s%nbut had not.", actual, other); + super("%nExpecting actual:%n %s%nto have same time fields except timezone as:%n %s%nbut had not.", actual, other); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeEqualIgnoringWhitespace.java b/src/main/java/org/assertj/core/error/ShouldBeEqualIgnoringWhitespace.java index ac82e2fc37e..09c2df6301a 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeEqualIgnoringWhitespace.java +++ b/src/main/java/org/assertj/core/error/ShouldBeEqualIgnoringWhitespace.java @@ -31,6 +31,6 @@ public static ErrorMessageFactory shouldBeEqualIgnoringWhitespace(CharSequence a } private ShouldBeEqualIgnoringWhitespace(CharSequence actual, CharSequence expected) { - super("%nExpecting:%n %s%nto be equal to:%n %s%nwhen ignoring whitespace differences", actual, expected); + super("%nExpecting actual:%n %s%nto be equal to:%n %s%nwhen ignoring whitespace differences", actual, expected); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeEqualNormalizingPunctuationAndWhitespace.java b/src/main/java/org/assertj/core/error/ShouldBeEqualNormalizingPunctuationAndWhitespace.java index e7a27dbc41d..2a00393d35f 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeEqualNormalizingPunctuationAndWhitespace.java +++ b/src/main/java/org/assertj/core/error/ShouldBeEqualNormalizingPunctuationAndWhitespace.java @@ -32,7 +32,7 @@ public static ErrorMessageFactory shouldBeEqualNormalizingPunctuationAndWhitespa private ShouldBeEqualNormalizingPunctuationAndWhitespace(CharSequence actual, CharSequence expected) { super("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " %s%n" + "to be equal to:%n" + " %s%n" + diff --git a/src/main/java/org/assertj/core/error/ShouldBeEqualNormalizingWhitespace.java b/src/main/java/org/assertj/core/error/ShouldBeEqualNormalizingWhitespace.java index 013d2a7d5bf..dd8a8242750 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeEqualNormalizingWhitespace.java +++ b/src/main/java/org/assertj/core/error/ShouldBeEqualNormalizingWhitespace.java @@ -31,6 +31,6 @@ public static ErrorMessageFactory shouldBeEqualNormalizingWhitespace(CharSequenc } private ShouldBeEqualNormalizingWhitespace(CharSequence actual, CharSequence expected) { - super("%nExpecting:%n %s%nto be equal to:%n %s%nafter whitespace differences are normalized", actual, expected); + super("%nExpecting actual:%n %s%nto be equal to:%n %s%nafter whitespace differences are normalized", actual, expected); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeEqualWithTimePrecision.java b/src/main/java/org/assertj/core/error/ShouldBeEqualWithTimePrecision.java index f0f7b03e575..b8f6b1b7ee5 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeEqualWithTimePrecision.java +++ b/src/main/java/org/assertj/core/error/ShouldBeEqualWithTimePrecision.java @@ -55,7 +55,7 @@ private static String buildErrorMessageTemplate(final TimeUnit precision) { fields = ", day, hour, minute"; lastField = "second"; } - return "%nExpecting:%n" + + return "%nExpecting actual:%n" + " %s%n" + "to have same year, month" + fields + " and " + lastField + " as:%n" + " %s%n" + diff --git a/src/main/java/org/assertj/core/error/ShouldBeEqualWithinOffset.java b/src/main/java/org/assertj/core/error/ShouldBeEqualWithinOffset.java index 0dde9bc9d7a..9ba322831d6 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeEqualWithinOffset.java +++ b/src/main/java/org/assertj/core/error/ShouldBeEqualWithinOffset.java @@ -39,7 +39,7 @@ public static ErrorMessageFactory shouldBeEqual(T actual, T e private ShouldBeEqualWithinOffset(Number actual, Number expected, Offset offset, Number difference) { super("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " %s%n" + "to be close to:%n" + " %s%n" + diff --git a/src/main/java/org/assertj/core/error/ShouldBeEqualWithinPercentage.java b/src/main/java/org/assertj/core/error/ShouldBeEqualWithinPercentage.java index 195cfbe0d24..2356d7e6f9c 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeEqualWithinPercentage.java +++ b/src/main/java/org/assertj/core/error/ShouldBeEqualWithinPercentage.java @@ -41,7 +41,7 @@ public static ErrorMessageFactory shouldBeEqualWithinPercenta private ShouldBeEqualWithinPercentage(Number actual, Number expected, Percentage percentage, double expectedPercentage) { - super("%nExpecting:%n" + + super("%nExpecting actual:%n" + " %s%n" + "to be close to:%n" + " %s%n" + diff --git a/src/main/java/org/assertj/core/error/ShouldBeExactlyInstanceOf.java b/src/main/java/org/assertj/core/error/ShouldBeExactlyInstanceOf.java index fe4ffaa5c3d..4cc6a42c16d 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeExactlyInstanceOf.java +++ b/src/main/java/org/assertj/core/error/ShouldBeExactlyInstanceOf.java @@ -34,7 +34,7 @@ public static ErrorMessageFactory shouldBeExactlyInstance(Object actual, Class type) { - super("%nExpecting:%n %s%nto be exactly an instance of:%n %s%nbut was an instance of:%n %s", actual, type, + super("%nExpecting actual:%n %s%nto be exactly an instance of:%n %s%nbut was an instance of:%n %s", actual, type, actual.getClass()); } diff --git a/src/main/java/org/assertj/core/error/ShouldBeExecutable.java b/src/main/java/org/assertj/core/error/ShouldBeExecutable.java index c25e5a22d00..8bf911f4e40 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeExecutable.java +++ b/src/main/java/org/assertj/core/error/ShouldBeExecutable.java @@ -23,7 +23,7 @@ * */ public class ShouldBeExecutable extends BasicErrorMessageFactory { - private static final String SHOULD_BE_EXECUTABLE = "%nExpecting:%n %s%nto be executable."; + private static final String SHOULD_BE_EXECUTABLE = "%nExpecting actual:%n %s%nto be executable."; private ShouldBeExecutable(File actual) { super(SHOULD_BE_EXECUTABLE, actual); diff --git a/src/main/java/org/assertj/core/error/ShouldBeFile.java b/src/main/java/org/assertj/core/error/ShouldBeFile.java index 56189a3a6cc..306e17a370f 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeFile.java +++ b/src/main/java/org/assertj/core/error/ShouldBeFile.java @@ -32,6 +32,6 @@ public static ErrorMessageFactory shouldBeFile(File actual) { } private ShouldBeFile(File actual) { - super("%nExpecting:%n %s%nto be a file", actual); + super("%nExpecting actual:%n %s%nto be a file", actual); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeGreater.java b/src/main/java/org/assertj/core/error/ShouldBeGreater.java index e30e7ccefcb..887c60370ea 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeGreater.java +++ b/src/main/java/org/assertj/core/error/ShouldBeGreater.java @@ -50,6 +50,6 @@ public static > ErrorMessageFactory shouldBeGrea } private ShouldBeGreater(Comparable actual, Comparable other, ComparisonStrategy comparisonStrategy) { - super("%nExpecting:%n %s%nto be greater than:%n %s%n%s", actual, other, comparisonStrategy); + super("%nExpecting actual:%n %s%nto be greater than:%n %s%n%s", actual, other, comparisonStrategy); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeGreaterOrEqual.java b/src/main/java/org/assertj/core/error/ShouldBeGreaterOrEqual.java index 722b90a8cfa..a2cc9ee94e9 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeGreaterOrEqual.java +++ b/src/main/java/org/assertj/core/error/ShouldBeGreaterOrEqual.java @@ -49,6 +49,6 @@ public static > ErrorMessageFactory shouldBeGrea } private ShouldBeGreaterOrEqual(Comparable actual, Comparable other, ComparisonStrategy comparisonStrategy) { - super("%nExpecting:%n %s%nto be greater than or equal to:%n %s%n%s", actual, other, comparisonStrategy); + super("%nExpecting actual:%n %s%nto be greater than or equal to:%n %s%n%s", actual, other, comparisonStrategy); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeIn.java b/src/main/java/org/assertj/core/error/ShouldBeIn.java index c7a1c73acd3..d114e1abb2c 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeIn.java +++ b/src/main/java/org/assertj/core/error/ShouldBeIn.java @@ -46,7 +46,7 @@ public static ErrorMessageFactory shouldBeIn(Object actual, Object values) { } private ShouldBeIn(Object actual, Object values, ComparisonStrategy comparisonStrategy) { - super("%nExpecting:%n %s%nto be in:%n %s%n%s", actual, values, comparisonStrategy); + super("%nExpecting actual:%n %s%nto be in:%n %s%n%s", actual, values, comparisonStrategy); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeInSameDay.java b/src/main/java/org/assertj/core/error/ShouldBeInSameDay.java index fefbc771ffd..4020a01f476 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeInSameDay.java +++ b/src/main/java/org/assertj/core/error/ShouldBeInSameDay.java @@ -33,6 +33,6 @@ public static ErrorMessageFactory shouldBeInSameDay(Date actual, Date other) { } private ShouldBeInSameDay(Date actual, Date other) { - super("%nExpecting:%n %s%nto be on same year, month and day as:%n %s", actual, other); + super("%nExpecting actual:%n %s%nto be on same year, month and day as:%n %s", actual, other); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeInSameHour.java b/src/main/java/org/assertj/core/error/ShouldBeInSameHour.java index 8f1924fbd00..5f270c64614 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeInSameHour.java +++ b/src/main/java/org/assertj/core/error/ShouldBeInSameHour.java @@ -33,6 +33,6 @@ public static ErrorMessageFactory shouldBeInSameHour(Date actual, Date other) { } private ShouldBeInSameHour(Date actual, Date other) { - super("%nExpecting:%n %s%nto have same year, month, day and hour fields values as:%n %s", actual, other); + super("%nExpecting actual:%n %s%nto have same year, month, day and hour fields values as:%n %s", actual, other); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeInSameHourWindow.java b/src/main/java/org/assertj/core/error/ShouldBeInSameHourWindow.java index 33f9f5c0def..6b1419c65c4 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeInSameHourWindow.java +++ b/src/main/java/org/assertj/core/error/ShouldBeInSameHourWindow.java @@ -36,7 +36,7 @@ public static ErrorMessageFactory shouldBeInSameHourWindow(Date actual, Date oth } private ShouldBeInSameHourWindow(Date actual, Date other) { - super("%nExpecting:%n %s%nto be close to:%n %s%nby less than one hour (strictly) but difference was: " + super("%nExpecting actual:%n %s%nto be close to:%n %s%nby less than one hour (strictly) but difference was: " + formatTimeDifference(actual, other), actual, other); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeInSameMinute.java b/src/main/java/org/assertj/core/error/ShouldBeInSameMinute.java index 622b1ce015c..3ac5d8ff92a 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeInSameMinute.java +++ b/src/main/java/org/assertj/core/error/ShouldBeInSameMinute.java @@ -33,6 +33,6 @@ public static ErrorMessageFactory shouldBeInSameMinute(Date actual, Date other) } private ShouldBeInSameMinute(Date actual, Date other) { - super("%nExpecting:%n %s%nto have same year, month, day, hour and minute fields values as:%n %s", actual, other); + super("%nExpecting actual:%n %s%nto have same year, month, day, hour and minute fields values as:%n %s", actual, other); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeInSameMinuteWindow.java b/src/main/java/org/assertj/core/error/ShouldBeInSameMinuteWindow.java index e2c6d7e1647..ced72f1a0b6 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeInSameMinuteWindow.java +++ b/src/main/java/org/assertj/core/error/ShouldBeInSameMinuteWindow.java @@ -36,7 +36,7 @@ public static ErrorMessageFactory shouldBeInSameMinuteWindow(Date actual, Date o } private ShouldBeInSameMinuteWindow(Date actual, Date other) { - super("%nExpecting:%n %s%nto be close to:%n %s%nby less than one minute (strictly) but difference was: " + super("%nExpecting actual:%n %s%nto be close to:%n %s%nby less than one minute (strictly) but difference was: " + formatTimeDifference(actual, other), actual, other); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeInSameMonth.java b/src/main/java/org/assertj/core/error/ShouldBeInSameMonth.java index 448a4412bdf..a261d5b2766 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeInSameMonth.java +++ b/src/main/java/org/assertj/core/error/ShouldBeInSameMonth.java @@ -33,6 +33,6 @@ public static ErrorMessageFactory shouldBeInSameMonth(Date actual, Date other) { } private ShouldBeInSameMonth(Date actual, Date other) { - super("%nExpecting:%n %s%nto be on same year and month as:%n %s", actual, other); + super("%nExpecting actual:%n %s%nto be on same year and month as:%n %s", actual, other); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeInSameSecond.java b/src/main/java/org/assertj/core/error/ShouldBeInSameSecond.java index 2aefa51ebf9..de03e0c24b4 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeInSameSecond.java +++ b/src/main/java/org/assertj/core/error/ShouldBeInSameSecond.java @@ -34,6 +34,6 @@ public static ErrorMessageFactory shouldBeInSameSecond(Date actual, Date other) } private ShouldBeInSameSecond(Date actual, Date other) { - super("%nExpecting:%n %s%nto have same year, month, day, hour, minute and second fields values as:%n %s", actual, other); + super("%nExpecting actual:%n %s%nto have same year, month, day, hour, minute and second fields values as:%n %s", actual, other); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeInSameSecondWindow.java b/src/main/java/org/assertj/core/error/ShouldBeInSameSecondWindow.java index c0543cd043a..f206a016970 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeInSameSecondWindow.java +++ b/src/main/java/org/assertj/core/error/ShouldBeInSameSecondWindow.java @@ -29,7 +29,7 @@ public static ErrorMessageFactory shouldBeInSameSecondWindow(Date actual, Date o } private ShouldBeInSameSecondWindow(Date actual, Date other) { - super("%nExpecting:%n %s%nto be close to:%n %s%nby less than one second (strictly) but difference was: " + super("%nExpecting actual:%n %s%nto be close to:%n %s%nby less than one second (strictly) but difference was: " + formatTimeDifference(actual, other), actual, other); } diff --git a/src/main/java/org/assertj/core/error/ShouldBeInSameYear.java b/src/main/java/org/assertj/core/error/ShouldBeInSameYear.java index 3ee1b5a0d44..2ee90b09c6f 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeInSameYear.java +++ b/src/main/java/org/assertj/core/error/ShouldBeInSameYear.java @@ -32,6 +32,6 @@ public static ErrorMessageFactory shouldBeInSameYear(Date actual, Date other) { } private ShouldBeInSameYear(Date actual, Date other) { - super("%nExpecting:%n %s%nto be on same year as:%n %s", actual, other); + super("%nExpecting actual:%n %s%nto be on same year as:%n %s", actual, other); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeInTheFuture.java b/src/main/java/org/assertj/core/error/ShouldBeInTheFuture.java index 41193ce5448..c8e64786e85 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeInTheFuture.java +++ b/src/main/java/org/assertj/core/error/ShouldBeInTheFuture.java @@ -44,6 +44,6 @@ public static ErrorMessageFactory shouldBeInTheFuture(Date actual) { } private ShouldBeInTheFuture(Date actual, ComparisonStrategy comparisonStrategy) { - super("%nExpecting:%n %s%nto be in the future %s but was not.", actual, comparisonStrategy); + super("%nExpecting actual:%n %s%nto be in the future %s but was not.", actual, comparisonStrategy); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeInThePast.java b/src/main/java/org/assertj/core/error/ShouldBeInThePast.java index fa74ec89c56..595f598345b 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeInThePast.java +++ b/src/main/java/org/assertj/core/error/ShouldBeInThePast.java @@ -44,6 +44,6 @@ public static ErrorMessageFactory shouldBeInThePast(Date actual) { } private ShouldBeInThePast(Date actual, ComparisonStrategy comparisonStrategy) { - super("%nExpecting:%n %s%nto be in the past %s but was not.", actual, comparisonStrategy); + super("%nExpecting actual:%n %s%nto be in the past %s but was not.", actual, comparisonStrategy); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeInstance.java b/src/main/java/org/assertj/core/error/ShouldBeInstance.java index a07d6a98095..73e1e382cf8 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeInstance.java +++ b/src/main/java/org/assertj/core/error/ShouldBeInstance.java @@ -45,7 +45,7 @@ public static ErrorMessageFactory shouldBeInstanceButWasNull(String objectDescri private ShouldBeInstance(Object object, Class type) { super("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " %s%n" + "to be an instance of:%n" + " %s%n" + diff --git a/src/main/java/org/assertj/core/error/ShouldBeInstanceOfAny.java b/src/main/java/org/assertj/core/error/ShouldBeInstanceOfAny.java index 7eaf1fb0318..eeb6d4a9f8f 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeInstanceOfAny.java +++ b/src/main/java/org/assertj/core/error/ShouldBeInstanceOfAny.java @@ -34,7 +34,7 @@ public static ErrorMessageFactory shouldBeInstanceOfAny(Object actual, Class[ } private ShouldBeInstanceOfAny(Object actual, Class[] types) { - super("%nExpecting:%n %s%nto be an instance of any of:%n %s%nbut was instance of:%n %s", actual, types, + super("%nExpecting actual:%n %s%nto be an instance of any of:%n %s%nbut was instance of:%n %s", actual, types, actual.getClass()); } diff --git a/src/main/java/org/assertj/core/error/ShouldBeLess.java b/src/main/java/org/assertj/core/error/ShouldBeLess.java index 313d49d5a72..9f2028a4323 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeLess.java +++ b/src/main/java/org/assertj/core/error/ShouldBeLess.java @@ -48,6 +48,6 @@ public static > ErrorMessageFactory shouldBeLess } private ShouldBeLess(Comparable actual, Comparable other, ComparisonStrategy comparisonStrategy) { - super("%nExpecting:%n %s%nto be less than:%n %s %s", actual, other, comparisonStrategy); + super("%nExpecting actual:%n %s%nto be less than:%n %s %s", actual, other, comparisonStrategy); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeLessOrEqual.java b/src/main/java/org/assertj/core/error/ShouldBeLessOrEqual.java index cbd5abc3b57..3d32fd5dadf 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeLessOrEqual.java +++ b/src/main/java/org/assertj/core/error/ShouldBeLessOrEqual.java @@ -47,6 +47,6 @@ public static > ErrorMessageFactory shouldBeLess } private ShouldBeLessOrEqual(Comparable actual, Comparable other, ComparisonStrategy comparisonStrategy) { - super("%nExpecting:%n %s%nto be less than or equal to:%n %s %s", actual, other, comparisonStrategy); + super("%nExpecting actual:%n %s%nto be less than or equal to:%n %s %s", actual, other, comparisonStrategy); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeOfClassIn.java b/src/main/java/org/assertj/core/error/ShouldBeOfClassIn.java index 1f848e75324..5c5b0770325 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeOfClassIn.java +++ b/src/main/java/org/assertj/core/error/ShouldBeOfClassIn.java @@ -30,6 +30,6 @@ public static ErrorMessageFactory shouldBeOfClassIn(Object actual, Object types) } private ShouldBeOfClassIn(Object actual, Object types) { - super("%nExpecting:%n %s%nto be of one these types:%n %s%nbut was:%n %s", actual, types, actual.getClass()); + super("%nExpecting actual:%n %s%nto be of one these types:%n %s%nbut was:%n %s", actual, types, actual.getClass()); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeReadable.java b/src/main/java/org/assertj/core/error/ShouldBeReadable.java index 6d0751788e3..f08f94729c0 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeReadable.java +++ b/src/main/java/org/assertj/core/error/ShouldBeReadable.java @@ -23,7 +23,7 @@ * */ public class ShouldBeReadable extends BasicErrorMessageFactory { - static final String SHOULD_BE_READABLE = "%nExpecting:%n %s%nto be readable."; + static final String SHOULD_BE_READABLE = "%nExpecting actual:%n %s%nto be readable."; private ShouldBeReadable(File actual) { super(SHOULD_BE_READABLE, actual); diff --git a/src/main/java/org/assertj/core/error/ShouldBeRelativePath.java b/src/main/java/org/assertj/core/error/ShouldBeRelativePath.java index e707b720e64..4d732d24751 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeRelativePath.java +++ b/src/main/java/org/assertj/core/error/ShouldBeRelativePath.java @@ -24,7 +24,7 @@ public class ShouldBeRelativePath extends BasicErrorMessageFactory { @VisibleForTesting - public static final String SHOULD_BE_RELATIVE_PATH = "%nExpecting:%n %s%nto be a relative path."; + public static final String SHOULD_BE_RELATIVE_PATH = "%nExpecting actual:%n %s%nto be a relative path."; /** * Creates a new {@link ShouldBeRelativePath}. diff --git a/src/main/java/org/assertj/core/error/ShouldBeSame.java b/src/main/java/org/assertj/core/error/ShouldBeSame.java index 8a6993e1faa..dfdbc828f7f 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeSame.java +++ b/src/main/java/org/assertj/core/error/ShouldBeSame.java @@ -30,6 +30,6 @@ public static ErrorMessageFactory shouldBeSame(Object actual, Object expected) { } private ShouldBeSame(Object actual, Object expected) { - super("%nExpecting:%n %s%nand actual:%n %s%nto refer to the same object", expected, actual); + super("%nExpecting actual:%n %s%nand actual:%n %s%nto refer to the same object", expected, actual); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeSubstring.java b/src/main/java/org/assertj/core/error/ShouldBeSubstring.java index 7d4df1d866e..ae56d61b913 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeSubstring.java +++ b/src/main/java/org/assertj/core/error/ShouldBeSubstring.java @@ -29,6 +29,6 @@ public static ErrorMessageFactory shouldBeSubstring(CharSequence actual, CharSeq } private ShouldBeSubstring(CharSequence actual, CharSequence expected, ComparisonStrategy comparisonStrategy) { - super("%nExpecting:%n %s%nto be a substring of:%n %s%n%s", actual, expected, comparisonStrategy); + super("%nExpecting actual:%n %s%nto be a substring of:%n %s%n%s", actual, expected, comparisonStrategy); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeToday.java b/src/main/java/org/assertj/core/error/ShouldBeToday.java index 843a7cc04c2..7abb095fcc1 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeToday.java +++ b/src/main/java/org/assertj/core/error/ShouldBeToday.java @@ -55,10 +55,10 @@ public static ErrorMessageFactory shouldBeToday(Date actual) { } private ShouldBeToday(Date actual, ComparisonStrategy comparisonStrategy) { - super("%nExpecting:%n %s%nto be today %s but was not.", actual, comparisonStrategy); + super("%nExpecting actual:%n %s%nto be today %s but was not.", actual, comparisonStrategy); } private ShouldBeToday(LocalDate actual) { - super("%nExpecting:%n %s%nto be today but was not.", actual); + super("%nExpecting actual:%n %s%nto be today but was not.", actual); } } diff --git a/src/main/java/org/assertj/core/error/ShouldBeWritable.java b/src/main/java/org/assertj/core/error/ShouldBeWritable.java index a39974bb75d..911a27359b4 100644 --- a/src/main/java/org/assertj/core/error/ShouldBeWritable.java +++ b/src/main/java/org/assertj/core/error/ShouldBeWritable.java @@ -23,7 +23,7 @@ * */ public class ShouldBeWritable extends BasicErrorMessageFactory { - static final String SHOULD_BE_WRITABLE = "%nExpecting:%n %s%nto be writable."; + static final String SHOULD_BE_WRITABLE = "%nExpecting actual:%n %s%nto be writable."; private ShouldBeWritable(File actual) { super(SHOULD_BE_WRITABLE, actual); diff --git a/src/main/java/org/assertj/core/error/ShouldContain.java b/src/main/java/org/assertj/core/error/ShouldContain.java index 591fdb3a128..1335a660302 100644 --- a/src/main/java/org/assertj/core/error/ShouldContain.java +++ b/src/main/java/org/assertj/core/error/ShouldContain.java @@ -41,7 +41,21 @@ public class ShouldContain extends BasicErrorMessageFactory { */ public static ErrorMessageFactory shouldContain(Object actual, Object expected, Object notFound, ComparisonStrategy comparisonStrategy) { - GroupTypeDescription groupTypeDescription = getGroupTypeDescription(actual); + return shouldContain(actual.getClass(), actual, expected, notFound, comparisonStrategy); + } + + /** + * Creates a new {@link ShouldContain}. + * @param clazz the actual value class in the failed assertion. + * @param actual the actual value in the failed assertion. + * @param expected values expected to be in {@code actual}. + * @param notFound the values in {@code expected} not found in {@code actual}. + * @param comparisonStrategy the {@link ComparisonStrategy} used to evaluate assertion. + * @return the created {@code ErrorMessageFactory}. + */ + public static ErrorMessageFactory shouldContain(Class clazz, Object actual, Object expected, Object notFound, + ComparisonStrategy comparisonStrategy) { + GroupTypeDescription groupTypeDescription = getGroupTypeDescription(clazz); return new ShouldContain(actual, expected, notFound, comparisonStrategy, groupTypeDescription); } diff --git a/src/main/java/org/assertj/core/error/ShouldContainAnyOf.java b/src/main/java/org/assertj/core/error/ShouldContainAnyOf.java index 8e6dbef924e..c7ba91dced6 100644 --- a/src/main/java/org/assertj/core/error/ShouldContainAnyOf.java +++ b/src/main/java/org/assertj/core/error/ShouldContainAnyOf.java @@ -27,7 +27,7 @@ public static ErrorMessageFactory shouldContainAnyOf(Object actual, Object expec } private ShouldContainAnyOf(Object actual, Object expected, ComparisonStrategy comparisonStrategy) { - super("%nExpecting:%n" + + super("%nExpecting actual:%n" + " %s%n" + "to contain at least one of the following elements:%n" + " %s%n" + diff --git a/src/main/java/org/assertj/core/error/ShouldContainAtIndex.java b/src/main/java/org/assertj/core/error/ShouldContainAtIndex.java index 08c8ccee1f4..5675e301b37 100644 --- a/src/main/java/org/assertj/core/error/ShouldContainAtIndex.java +++ b/src/main/java/org/assertj/core/error/ShouldContainAtIndex.java @@ -52,6 +52,6 @@ public static ErrorMessageFactory shouldContainAtIndex(Object actual, Object exp } private ShouldContainAtIndex(Object actual, Object expected, Index index, Object found, ComparisonStrategy comparisonStrategy) { - super("%nExpecting:%n %s%nat index %s but found:%n %s%nin:%n %s%n%s", expected, index.value, found, actual, comparisonStrategy); + super("%nExpecting actual:%n %s%nat index %s but found:%n %s%nin:%n %s%n%s", expected, index.value, found, actual, comparisonStrategy); } } diff --git a/src/main/java/org/assertj/core/error/ShouldContainCharSequence.java b/src/main/java/org/assertj/core/error/ShouldContainCharSequence.java index 901eb1a02a3..1d4f989b4cc 100644 --- a/src/main/java/org/assertj/core/error/ShouldContainCharSequence.java +++ b/src/main/java/org/assertj/core/error/ShouldContainCharSequence.java @@ -38,7 +38,7 @@ public class ShouldContainCharSequence extends BasicErrorMessageFactory { * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldContain(CharSequence actual, CharSequence sequence) { - return new ShouldContainCharSequence("%nExpecting:%n %s%nto contain:%n %s %s", actual, sequence, + return new ShouldContainCharSequence("%nExpecting actual:%n %s%nto contain:%n %s %s", actual, sequence, StandardComparisonStrategy.instance()); } @@ -81,7 +81,7 @@ public static ErrorMessageFactory shouldContain(Throwable actual, CharSequence[] */ public static ErrorMessageFactory shouldContain(CharSequence actual, CharSequence sequence, ComparisonStrategy comparisonStrategy) { - return new ShouldContainCharSequence("%nExpecting:%n %s%nto contain:%n %s %s", actual, sequence, comparisonStrategy); + return new ShouldContainCharSequence("%nExpecting actual:%n %s%nto contain:%n %s %s", actual, sequence, comparisonStrategy); } /** @@ -96,7 +96,7 @@ public static ErrorMessageFactory shouldContain(CharSequence actual, CharSequenc public static ErrorMessageFactory shouldContain(CharSequence actual, CharSequence[] strings, Set notFound, ComparisonStrategy comparisonStrategy) { - return new ShouldContainCharSequence("%nExpecting:%n %s%nto contain:%n %s%nbut could not find:%n %s%n %s", actual, + return new ShouldContainCharSequence("%nExpecting actual:%n %s%nto contain:%n %s%nbut could not find:%n %s%n %s", actual, strings, notFound, comparisonStrategy); } @@ -121,10 +121,51 @@ public static ErrorMessageFactory shouldContain(CharSequence actual, CharSequenc * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldContainIgnoringCase(CharSequence actual, CharSequence sequence) { - return new ShouldContainCharSequence("%nExpecting:%n %s%nto contain:%n %s%n (ignoring case)", actual, sequence, + return new ShouldContainCharSequence("%nExpecting actual:%n %s%nto contain:%n %s%n (ignoring case)", actual, sequence, StandardComparisonStrategy.instance()); } + /** + * Creates a new {@link ShouldContainCharSequence}. + * + * @param actual the actual value in the failed assertion. + * @param sequence the sequence of values expected to be in {@code actual}. + * @param comparisonStrategy the {@link ComparisonStrategy} used to evaluate assertion. + * @return the created {@code ErrorMessageFactory}. + */ + public static ErrorMessageFactory shouldContainIgnoringWhitespaces(CharSequence actual, CharSequence sequence, + ComparisonStrategy comparisonStrategy) { + return new ShouldContainCharSequence("%n" + + "Expecting actual:%n" + + " %s%n" + + "to contain (ignoring whitespaces):%n" + + " %s %s", + actual, sequence, comparisonStrategy); + } + + /** + * Creates a new {@link ShouldContainCharSequence}. + * + * @param actual the actual value in the failed assertion. + * @param strings the sequence of values expected to be in {@code actual}. + * @param notFound the values not found. + * @param comparisonStrategy the {@link ComparisonStrategy} used to evaluate assertion. + * @return the created {@code ErrorMessageFactory}. + */ + public static ErrorMessageFactory shouldContainIgnoringWhitespaces(CharSequence actual, CharSequence[] strings, + Set notFound, + ComparisonStrategy comparisonStrategy) { + return new ShouldContainCharSequence("%n" + + "Expecting actual:%n" + + " %s%n" + + "to contain (ignoring whitespaces):%n" + + " %s%n" + + "but could not find:%n" + + " %s%n" + + " %s", + actual, strings, notFound, comparisonStrategy); + } + private ShouldContainCharSequence(String format, CharSequence actual, CharSequence sequence, ComparisonStrategy comparisonStrategy) { super(format, actual, sequence, comparisonStrategy); diff --git a/src/main/java/org/assertj/core/error/ShouldContainCharSequenceOnlyOnce.java b/src/main/java/org/assertj/core/error/ShouldContainCharSequenceOnlyOnce.java index a24fc07b62e..cc10e4d610f 100644 --- a/src/main/java/org/assertj/core/error/ShouldContainCharSequenceOnlyOnce.java +++ b/src/main/java/org/assertj/core/error/ShouldContainCharSequenceOnlyOnce.java @@ -52,13 +52,13 @@ public static ErrorMessageFactory shouldContainOnlyOnce(CharSequence actual, Cha } private ShouldContainCharSequenceOnlyOnce(CharSequence actual, CharSequence expected, int occurrences, ComparisonStrategy comparisonStrategy) { - super("%nExpecting:%n %s%nto appear only once in:%n %s%nbut it appeared %s times %s", expected, actual, + super("%nExpecting actual:%n %s%nto appear only once in:%n %s%nbut it appeared %s times %s", expected, actual, occurrences, comparisonStrategy); } private ShouldContainCharSequenceOnlyOnce(CharSequence actual, CharSequence expected, ComparisonStrategy comparisonStrategy) { - super("%nExpecting:%n %s%nto appear only once in:%n %s%nbut it did not appear %s", expected, actual, + super("%nExpecting actual:%n %s%nto appear only once in:%n %s%nbut it did not appear %s", expected, actual, comparisonStrategy); } } diff --git a/src/main/java/org/assertj/core/error/ShouldContainEntry.java b/src/main/java/org/assertj/core/error/ShouldContainEntry.java index 1e0065b414a..ff7023fea45 100644 --- a/src/main/java/org/assertj/core/error/ShouldContainEntry.java +++ b/src/main/java/org/assertj/core/error/ShouldContainEntry.java @@ -51,7 +51,7 @@ public static ErrorMessageFactory shouldContainEntry(Map actual, Co private ShouldContainEntry(Map actual, Condition entryCondition) { super("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " %s%n" + "to contain an entry satisfying:%n" + " %s", @@ -61,7 +61,7 @@ private ShouldContainEntry(Map actual, Condition entryCondition) private ShouldContainEntry(Map actual, Condition keyCondition, Condition valueCondition) { super("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " %s%n" + "to contain an entry satisfying both key and value conditions:%n" + "- key condition:%n" + diff --git a/src/main/java/org/assertj/core/error/ShouldContainExactly.java b/src/main/java/org/assertj/core/error/ShouldContainExactly.java index 70ddab5af36..a521cc712d9 100644 --- a/src/main/java/org/assertj/core/error/ShouldContainExactly.java +++ b/src/main/java/org/assertj/core/error/ShouldContainExactly.java @@ -66,7 +66,7 @@ public static ErrorMessageFactory shouldContainExactly(Object actual, Iterable notFound, Iterable notExpected, ComparisonStrategy comparisonStrategy) { super("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " %s%n" + "to contain exactly in any order:%n" + " %s%n" + @@ -66,7 +66,7 @@ private ShouldContainExactlyInAnyOrder(Object actual, Object expected, Iterable< ComparisonStrategy comparisonStrategy) { // @format:off super("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " %s%n" + "to contain exactly in any order:%n" + " %s%n" + (errorType == NOT_FOUND_ONLY ? diff --git a/src/main/java/org/assertj/core/error/ShouldContainKey.java b/src/main/java/org/assertj/core/error/ShouldContainKey.java index dd9fd5bc49c..88df97e3132 100644 --- a/src/main/java/org/assertj/core/error/ShouldContainKey.java +++ b/src/main/java/org/assertj/core/error/ShouldContainKey.java @@ -32,7 +32,7 @@ public static ErrorMessageFactory shouldContainKey(Object actual, Condition k private ShouldContainKey(Object actual, Condition keyCondition) { super("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " %s%n" + "to contain a key satisfying:%n" + " %s", diff --git a/src/main/java/org/assertj/core/error/ShouldContainKeys.java b/src/main/java/org/assertj/core/error/ShouldContainKeys.java index 03258336d7d..0776aafb9b5 100644 --- a/src/main/java/org/assertj/core/error/ShouldContainKeys.java +++ b/src/main/java/org/assertj/core/error/ShouldContainKeys.java @@ -36,10 +36,10 @@ public static ErrorMessageFactory shouldContainKeys(Object actual, Set ke } private ShouldContainKeys(Object actual, Set key) { - super("%nExpecting:%n %s%nto contain keys:%n %s", actual, key); + super("%nExpecting actual:%n %s%nto contain keys:%n %s", actual, key); } private ShouldContainKeys(Object actual, K key) { - super("%nExpecting:%n %s%nto contain key:%n %s", actual, key); + super("%nExpecting actual:%n %s%nto contain key:%n %s", actual, key); } } diff --git a/src/main/java/org/assertj/core/error/ShouldContainNull.java b/src/main/java/org/assertj/core/error/ShouldContainNull.java index 8c6095275bd..a1126c10a8c 100644 --- a/src/main/java/org/assertj/core/error/ShouldContainNull.java +++ b/src/main/java/org/assertj/core/error/ShouldContainNull.java @@ -30,6 +30,6 @@ public static ErrorMessageFactory shouldContainNull(Object actual) { } private ShouldContainNull(Object actual) { - super("%nExpecting:%n %s%nto contain a null element", actual); + super("%nExpecting actual:%n %s%nto contain a null element", actual); } } diff --git a/src/main/java/org/assertj/core/error/ShouldContainOnlyDigits.java b/src/main/java/org/assertj/core/error/ShouldContainOnlyDigits.java index 1a95a24cfdd..f96353faac0 100644 --- a/src/main/java/org/assertj/core/error/ShouldContainOnlyDigits.java +++ b/src/main/java/org/assertj/core/error/ShouldContainOnlyDigits.java @@ -40,11 +40,11 @@ public static ErrorMessageFactory shouldContainOnlyDigits(CharSequence actual) { } private ShouldContainOnlyDigits(CharSequence actual, char character, int index) { - super("%nExpecting:%n %s%nto contain only digits%nbut found non-digit character %s at index <%s>", + super("%nExpecting actual:%n %s%nto contain only digits%nbut found non-digit character %s at index <%s>", actual, character, index); } private ShouldContainOnlyDigits(CharSequence actual) { - super("%nExpecting:%n %s%nto contain only digits%nbut could not found any digits at all", actual); + super("%nExpecting actual:%n %s%nto contain only digits%nbut could not found any digits at all", actual); } } diff --git a/src/main/java/org/assertj/core/error/ShouldContainOnlyKeys.java b/src/main/java/org/assertj/core/error/ShouldContainOnlyKeys.java index 3cff915ecfc..376cee27310 100644 --- a/src/main/java/org/assertj/core/error/ShouldContainOnlyKeys.java +++ b/src/main/java/org/assertj/core/error/ShouldContainOnlyKeys.java @@ -59,7 +59,7 @@ public static ErrorMessageFactory shouldContainOnlyKeys(Object actual, Object ex private ShouldContainOnlyKeys(Object actual, Object expected, Object notFound, Object notExpected, ComparisonStrategy comparisonStrategy) { super("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " %s%n" + "to contain only following keys:%n" + " %s%n" + @@ -72,7 +72,7 @@ private ShouldContainOnlyKeys(Object actual, Object expected, Object notFound, O private ShouldContainOnlyKeys(Object actual, Object expected, Object notFound, ComparisonStrategy comparisonStrategy) { super("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " %s%n" + "to contain only following keys:%n" + " %s%n" + diff --git a/src/main/java/org/assertj/core/error/ShouldContainOnlyNulls.java b/src/main/java/org/assertj/core/error/ShouldContainOnlyNulls.java index 819a4500076..91c39001b19 100644 --- a/src/main/java/org/assertj/core/error/ShouldContainOnlyNulls.java +++ b/src/main/java/org/assertj/core/error/ShouldContainOnlyNulls.java @@ -38,7 +38,7 @@ public static ErrorMessageFactory shouldContainOnlyNulls(Object actual, Iterable private ShouldContainOnlyNulls(Object actual, ErrorType errorType, Iterable notExpected) { super("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " %s%n" + "to contain only null elements but " + describe(errorType), actual, notExpected); diff --git a/src/main/java/org/assertj/core/error/ShouldContainPattern.java b/src/main/java/org/assertj/core/error/ShouldContainPattern.java index 223e2466bd0..aff8a4220e5 100644 --- a/src/main/java/org/assertj/core/error/ShouldContainPattern.java +++ b/src/main/java/org/assertj/core/error/ShouldContainPattern.java @@ -30,6 +30,6 @@ public static ErrorMessageFactory shouldContainPattern(CharSequence actual, Char } private ShouldContainPattern(CharSequence actual, CharSequence pattern) { - super("%nExpecting:%n %s%nto contain pattern:%n %s", actual, pattern); + super("%nExpecting actual:%n %s%nto contain pattern:%n %s", actual, pattern); } } diff --git a/src/main/java/org/assertj/core/error/ShouldContainSequence.java b/src/main/java/org/assertj/core/error/ShouldContainSequence.java index 3dabf1447b9..e51376fc33f 100644 --- a/src/main/java/org/assertj/core/error/ShouldContainSequence.java +++ b/src/main/java/org/assertj/core/error/ShouldContainSequence.java @@ -47,7 +47,7 @@ public static ErrorMessageFactory shouldContainSequence(Object actual, Object se } private ShouldContainSequence(Object actual, Object sequence, ComparisonStrategy comparisonStrategy) { - super("%nExpecting:%n" + + super("%nExpecting actual:%n" + " %s%n" + "to contain sequence:%n" + " %s%n%s", actual, sequence, comparisonStrategy); diff --git a/src/main/java/org/assertj/core/error/ShouldContainSequenceOfCharSequence.java b/src/main/java/org/assertj/core/error/ShouldContainSequenceOfCharSequence.java index db3564463cd..1e118080101 100644 --- a/src/main/java/org/assertj/core/error/ShouldContainSequenceOfCharSequence.java +++ b/src/main/java/org/assertj/core/error/ShouldContainSequenceOfCharSequence.java @@ -25,7 +25,7 @@ public class ShouldContainSequenceOfCharSequence extends BasicErrorMessageFactory { private ShouldContainSequenceOfCharSequence(CharSequence actual, CharSequence[] sequence, ComparisonStrategy comparisonStrategy) { - super("%nExpecting:%n %s%nto contain sequence:%n %s%n%s", actual, sequence, comparisonStrategy); + super("%nExpecting actual:%n %s%nto contain sequence:%n %s%n%s", actual, sequence, comparisonStrategy); } /** diff --git a/src/main/java/org/assertj/core/error/ShouldContainSubsequence.java b/src/main/java/org/assertj/core/error/ShouldContainSubsequence.java index 15f691e3f5b..8c647af41c5 100644 --- a/src/main/java/org/assertj/core/error/ShouldContainSubsequence.java +++ b/src/main/java/org/assertj/core/error/ShouldContainSubsequence.java @@ -48,6 +48,6 @@ public static ErrorMessageFactory shouldContainSubsequence(Object actual, Object } private ShouldContainSubsequence(Object actual, Object subsequence, ComparisonStrategy comparisonStrategy) { - super("%nExpecting:%n %s%nto contain subsequence:%n %s%n%s", actual, subsequence, comparisonStrategy); + super("%nExpecting actual:%n %s%nto contain subsequence:%n %s%n%s", actual, subsequence, comparisonStrategy); } } diff --git a/src/main/java/org/assertj/core/error/ShouldContainSubsequenceOfCharSequence.java b/src/main/java/org/assertj/core/error/ShouldContainSubsequenceOfCharSequence.java index f557988756c..593b7c142e8 100644 --- a/src/main/java/org/assertj/core/error/ShouldContainSubsequenceOfCharSequence.java +++ b/src/main/java/org/assertj/core/error/ShouldContainSubsequenceOfCharSequence.java @@ -49,7 +49,7 @@ public static ErrorMessageFactory shouldContainSubsequence(CharSequence actual, public static ErrorMessageFactory shouldContainSubsequence(CharSequence actual, CharSequence[] strings, int badOrderIndex, ComparisonStrategy comparisonStrategy) { - return new ShouldContainSubsequenceOfCharSequence("%nExpecting:%n" + + return new ShouldContainSubsequenceOfCharSequence("%nExpecting actual:%n" + " %s%n" + "to contain the following CharSequences in this order:%n" + " %s%n" + diff --git a/src/main/java/org/assertj/core/error/ShouldContainValue.java b/src/main/java/org/assertj/core/error/ShouldContainValue.java index a1ea0647289..c01e378f416 100644 --- a/src/main/java/org/assertj/core/error/ShouldContainValue.java +++ b/src/main/java/org/assertj/core/error/ShouldContainValue.java @@ -43,10 +43,10 @@ public static ErrorMessageFactory shouldContainValue(Object actual, Condition } private ShouldContainValue(Object actual, Object value) { - super("%nExpecting:%n %s%nto contain value:%n %s", actual, value); + super("%nExpecting actual:%n %s%nto contain value:%n %s", actual, value); } private ShouldContainValue(Object actual, Condition valueCondition) { - super("%nExpecting:%n %s%nto contain a value satisfying:%n %s", actual, valueCondition); + super("%nExpecting actual:%n %s%nto contain a value satisfying:%n %s", actual, valueCondition); } } diff --git a/src/main/java/org/assertj/core/error/ShouldContainValues.java b/src/main/java/org/assertj/core/error/ShouldContainValues.java index 149fa786e32..c676c889f51 100644 --- a/src/main/java/org/assertj/core/error/ShouldContainValues.java +++ b/src/main/java/org/assertj/core/error/ShouldContainValues.java @@ -37,6 +37,6 @@ public static ErrorMessageFactory shouldContainValues(Object actual, Set } private ShouldContainValues(Object actual, Set values) { - super("%nExpecting:%n %s%nto contain values:%n %s", actual, values); + super("%nExpecting actual:%n %s%nto contain values:%n %s", actual, values); } } diff --git a/src/main/java/org/assertj/core/error/ShouldContainsOnlyOnce.java b/src/main/java/org/assertj/core/error/ShouldContainsOnlyOnce.java index 405cfdc7560..d8c02e234e3 100644 --- a/src/main/java/org/assertj/core/error/ShouldContainsOnlyOnce.java +++ b/src/main/java/org/assertj/core/error/ShouldContainsOnlyOnce.java @@ -63,21 +63,21 @@ public static ErrorMessageFactory shouldContainsOnlyOnce(Object actual, Object e private ShouldContainsOnlyOnce(Object actual, Object expected, Set notFound, Set notOnlyOnce, ComparisonStrategy comparisonStrategy) { - super("%nExpecting:%n %s%nto contain only once:%n %s%n" + super("%nExpecting actual:%n %s%nto contain only once:%n %s%n" + "but some elements were not found:%n %s%n" + "and others were found more than once:%n %s%n%s", actual, expected, notFound, notOnlyOnce, comparisonStrategy); } private ShouldContainsOnlyOnce(Object actual, Object expected, Set notFound, ComparisonStrategy comparisonStrategy) { - super("%nExpecting:%n %s%nto contain only once:%n %s%nbut some elements were not found:%n %s%n%s", + super("%nExpecting actual:%n %s%nto contain only once:%n %s%nbut some elements were not found:%n %s%n%s", actual, expected, notFound, comparisonStrategy); } // change the order of parameters to avoid confusion with previous constructor private ShouldContainsOnlyOnce(Set notOnlyOnce, Object actual, Object expected, ComparisonStrategy comparisonStrategy) { - super("%nExpecting:%n %s%nto contain only once:%n %s%nbut some elements were found more than once:%n %s%n%s", + super("%nExpecting actual:%n %s%nto contain only once:%n %s%nbut some elements were found more than once:%n %s%n%s", actual, expected, notOnlyOnce, comparisonStrategy); } diff --git a/src/main/java/org/assertj/core/error/ShouldEndWith.java b/src/main/java/org/assertj/core/error/ShouldEndWith.java index 34ebf7567b9..bd759b68832 100644 --- a/src/main/java/org/assertj/core/error/ShouldEndWith.java +++ b/src/main/java/org/assertj/core/error/ShouldEndWith.java @@ -45,6 +45,6 @@ public static ErrorMessageFactory shouldEndWith(Object actual, Object expected) } private ShouldEndWith(Object actual, Object expected, ComparisonStrategy comparisonStrategy) { - super("%nExpecting:%n %s%nto end with:%n %s%n%s", actual, expected, comparisonStrategy); + super("%nExpecting actual:%n %s%nto end with:%n %s%n%s", actual, expected, comparisonStrategy); } } diff --git a/src/main/java/org/assertj/core/error/ShouldHave.java b/src/main/java/org/assertj/core/error/ShouldHave.java index 1e9235efae8..64a26243d6c 100644 --- a/src/main/java/org/assertj/core/error/ShouldHave.java +++ b/src/main/java/org/assertj/core/error/ShouldHave.java @@ -13,11 +13,12 @@ package org.assertj.core.error; import org.assertj.core.api.Condition; +import org.assertj.core.condition.AllOf; /** * Creates an error message indicating that an assertion that verifies that a value satisfies a {@link Condition} * failed. - * + * * @author Yvonne Wang * @author Mikhail Mazursky */ @@ -31,10 +32,20 @@ public class ShouldHave extends BasicErrorMessageFactory { * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldHave(T actual, Condition condition) { + if (condition instanceof AllOf) return new ShouldHave(actual, (AllOf) condition); return new ShouldHave(actual, condition); } private ShouldHave(Object actual, Condition condition) { - super("%nExpecting:%n %s%nto have:%n %s", actual, condition); + super("%nExpecting actual:%n %s%nto have %s", actual, condition); + } + + private ShouldHave(T actual, AllOf allOf) { + super("%n" + + "Expecting actual:%n" + + " %s%n" + + // use concatenation to avoid the string to be double quoted later on + "to have:%n" + allOf.conditionDescriptionWithStatus(actual), + actual); } } diff --git a/src/main/java/org/assertj/core/error/ShouldHaveAtIndex.java b/src/main/java/org/assertj/core/error/ShouldHaveAtIndex.java index 8451364aff3..bbbb1540e07 100644 --- a/src/main/java/org/assertj/core/error/ShouldHaveAtIndex.java +++ b/src/main/java/org/assertj/core/error/ShouldHaveAtIndex.java @@ -40,6 +40,6 @@ public static ErrorMessageFactory shouldHaveAtIndex(List actual } private ShouldHaveAtIndex(List actual, Condition condition, Index index, T found) { - super("%nExpecting:%n %s%nat index %s to have:%n %s%nin:%n %s%n", found, index.value, condition, actual); + super("%nExpecting actual:%n %s%nat index %s to have:%n %s%nin:%n %s%n", found, index.value, condition, actual); } } diff --git a/src/main/java/org/assertj/core/error/ShouldHaveAtLeastOneElementOfType.java b/src/main/java/org/assertj/core/error/ShouldHaveAtLeastOneElementOfType.java index 4adadf2e06b..a88bb162c5c 100644 --- a/src/main/java/org/assertj/core/error/ShouldHaveAtLeastOneElementOfType.java +++ b/src/main/java/org/assertj/core/error/ShouldHaveAtLeastOneElementOfType.java @@ -29,6 +29,6 @@ public static ShouldHaveAtLeastOneElementOfType shouldHaveAtLeastOneElementOfTyp } private ShouldHaveAtLeastOneElementOfType(Object actual, Class expectedType) { - super("%nExpecting:%n %s%nto have at least one element of type:%n %s%nbut had none.", actual, expectedType); + super("%nExpecting actual:%n %s%nto have at least one element of type:%n %s%nbut had none.", actual, expectedType); } } diff --git a/src/main/java/org/assertj/core/error/ShouldHaveDateField.java b/src/main/java/org/assertj/core/error/ShouldHaveDateField.java index 6ed6db5d1c9..d74bc5a3c66 100644 --- a/src/main/java/org/assertj/core/error/ShouldHaveDateField.java +++ b/src/main/java/org/assertj/core/error/ShouldHaveDateField.java @@ -34,6 +34,6 @@ public static ErrorMessageFactory shouldHaveDateField(Date actual, String fieldD } private ShouldHaveDateField(Date actual, String fieldDescription, int fieldValue) { - super("%nExpecting:%n %s%nto be on %s %s", actual, fieldDescription, fieldValue); + super("%nExpecting actual:%n %s%nto be on %s %s", actual, fieldDescription, fieldValue); } } diff --git a/src/main/java/org/assertj/core/error/ShouldHaveExactlyTypes.java b/src/main/java/org/assertj/core/error/ShouldHaveExactlyTypes.java new file mode 100644 index 00000000000..d8d7923f616 --- /dev/null +++ b/src/main/java/org/assertj/core/error/ShouldHaveExactlyTypes.java @@ -0,0 +1,74 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.error; + +import static org.assertj.core.util.IterableUtil.isNullOrEmpty; + +public class ShouldHaveExactlyTypes extends BasicErrorMessageFactory { + + public static ErrorMessageFactory shouldHaveTypes(Object actual, Iterable> expectedTypes, + Iterable> expectedTypesNotFoundInActual, + Iterable> actualTypesNotExpected) { + if (!isNullOrEmpty(actualTypesNotExpected) && !isNullOrEmpty(expectedTypesNotFoundInActual)) { + return new ShouldHaveExactlyTypes(actual, expectedTypes, expectedTypesNotFoundInActual, actualTypesNotExpected); + } + // empty actualTypesNotExpected means expectedTypesNotFoundInActual is not empty + boolean expectedTypesNotFoundInActualOnly = isNullOrEmpty(actualTypesNotExpected); + Iterable> diff = expectedTypesNotFoundInActualOnly ? expectedTypesNotFoundInActual : actualTypesNotExpected; + return new ShouldHaveExactlyTypes(actual, expectedTypes, diff, expectedTypesNotFoundInActualOnly); + } + + public static ErrorMessageFactory elementsTypesDifferAtIndex(Object actualElement, Class expectedElement, + int indexOfDifference) { + return new ShouldHaveExactlyTypes(actualElement, expectedElement, indexOfDifference); + } + + private ShouldHaveExactlyTypes(Object actual, Iterable> expected, Iterable> expectedTypesNotFoundInActual, + Iterable> actualTypesNotExpected) { + super("%n" + + "Expecting actual elements:%n" + + " %s%n" + + "to have the following types (in this order):%n" + + " %s%n" + + "but there were no actual elements with these types:%n" + + " %s%n" + + "and these actual elements types were not expected:%n" + + " %s", + actual, expected, expectedTypesNotFoundInActual, actualTypesNotExpected); + } + + private ShouldHaveExactlyTypes(Object actual, Iterable> expected, Iterable> diff, + boolean expectedTypesNotFoundInActualOnly) { + // @format:off + super("%n" + + "Expecting actual elements:%n" + + " %s%n" + + "to have the following types (in this order):%n" + + " %s%n" + + (expectedTypesNotFoundInActualOnly + ? "but there were no actual elements with these types" + : "but these actual elements types were not expected") + ":%n" + + " %s", + actual, expected, diff); + // @format:on + } + + private ShouldHaveExactlyTypes(Object actualElement, Class expectedType, int indexOfDifference) { + super("%n" + + "actual element at index %s does not have the expected type, element was:%s%n" + + "actual element type: %s%n" + + "expected type : %s", + indexOfDifference, actualElement, actualElement.getClass(), expectedType); + } + +} diff --git a/src/main/java/org/assertj/core/error/ShouldHaveOnlyElementsOfType.java b/src/main/java/org/assertj/core/error/ShouldHaveOnlyElementsOfType.java index 23905411e6c..8d603d4827b 100644 --- a/src/main/java/org/assertj/core/error/ShouldHaveOnlyElementsOfType.java +++ b/src/main/java/org/assertj/core/error/ShouldHaveOnlyElementsOfType.java @@ -30,6 +30,6 @@ public static ShouldHaveOnlyElementsOfType shouldHaveOnlyElementsOfType(Object a } private ShouldHaveOnlyElementsOfType(Object actual, Class expectedType, Class unexpectedType) { - super("%nExpecting:%n %s%nto only have elements of type:%n %s%nbut found:%n %s", actual, expectedType, unexpectedType); + super("%nExpecting actual:%n %s%nto only have elements of type:%n %s%nbut found:%n %s", actual, expectedType, unexpectedType); } } diff --git a/src/main/java/org/assertj/core/error/ShouldHaveSameHourAs.java b/src/main/java/org/assertj/core/error/ShouldHaveSameHourAs.java index 07e2f275eb3..a481a65014f 100644 --- a/src/main/java/org/assertj/core/error/ShouldHaveSameHourAs.java +++ b/src/main/java/org/assertj/core/error/ShouldHaveSameHourAs.java @@ -35,6 +35,6 @@ public static ErrorMessageFactory shouldHaveSameHourAs(Temporal actual, Temporal } private ShouldHaveSameHourAs(Temporal actual, Temporal other) { - super("%nExpecting:%n %s%nto have same hour as:%n %s%nbut had not.", actual, other); + super("%nExpecting actual:%n %s%nto have same hour as:%n %s%nbut had not.", actual, other); } } diff --git a/src/main/java/org/assertj/core/error/ShouldHaveSuppressedException.java b/src/main/java/org/assertj/core/error/ShouldHaveSuppressedException.java index 68ef9e0d1e3..299807ef08f 100644 --- a/src/main/java/org/assertj/core/error/ShouldHaveSuppressedException.java +++ b/src/main/java/org/assertj/core/error/ShouldHaveSuppressedException.java @@ -30,7 +30,7 @@ public static ErrorMessageFactory shouldHaveSuppressedException(Throwable actual private ShouldHaveSuppressedException(Throwable actual, Throwable expectedSuppressedException) { super("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " %s%n" + "to have a suppressed exception with the following type and message:%n" + " %s / %s%n" + diff --git a/src/main/java/org/assertj/core/error/ShouldMatch.java b/src/main/java/org/assertj/core/error/ShouldMatch.java index 17f9007efd4..994ff2071fd 100644 --- a/src/main/java/org/assertj/core/error/ShouldMatch.java +++ b/src/main/java/org/assertj/core/error/ShouldMatch.java @@ -32,7 +32,7 @@ public class ShouldMatch extends BasicErrorMessageFactory { " assertThat(player).matches(p -> p.isRookie(), \"is rookie\");%n" + "will give an error message looking like:%n" + "%n" + - "Expecting:%n" + + "Expecting actual:%n" + " player%n" + "to match 'is rookie' predicate"); // @format:on @@ -53,6 +53,6 @@ public static ErrorMessageFactory shouldMatch(T actual, Predicate } private ShouldMatch(Object actual, PredicateDescription description) { - super("%nExpecting:%n %s%nto match %s predicate." + (description.isDefault() ? ADVICE : ""), actual, description); + super("%nExpecting actual:%n %s%nto match %s predicate." + (description.isDefault() ? ADVICE : ""), actual, description); } } diff --git a/src/main/java/org/assertj/core/error/ShouldMatchPattern.java b/src/main/java/org/assertj/core/error/ShouldMatchPattern.java index 17965114a17..6a37a853def 100644 --- a/src/main/java/org/assertj/core/error/ShouldMatchPattern.java +++ b/src/main/java/org/assertj/core/error/ShouldMatchPattern.java @@ -31,6 +31,6 @@ public static ErrorMessageFactory shouldMatch(CharSequence actual, CharSequence } private ShouldMatchPattern(CharSequence actual, CharSequence pattern) { - super("%nExpecting:%n %s%nto match pattern:%n %s", actual, pattern); + super("%nExpecting actual:%n %s%nto match pattern:%n %s", actual, pattern); } } diff --git a/src/main/java/org/assertj/core/error/ShouldNotAccept.java b/src/main/java/org/assertj/core/error/ShouldNotAccept.java index 23ecfa17201..5ced25ea7d4 100644 --- a/src/main/java/org/assertj/core/error/ShouldNotAccept.java +++ b/src/main/java/org/assertj/core/error/ShouldNotAccept.java @@ -42,6 +42,6 @@ public static ErrorMessageFactory shouldNotAccept(Predicate predi } private ShouldNotAccept(Object value, PredicateDescription description) { - super("%nExpecting:%n %s predicate%nnot to accept %s but it did.", description, value); + super("%nExpecting actual:%n %s predicate%nnot to accept %s but it did.", description, value); } } diff --git a/src/main/java/org/assertj/core/error/ShouldNotBe.java b/src/main/java/org/assertj/core/error/ShouldNotBe.java index 9f3dd7988e5..daf2531220e 100644 --- a/src/main/java/org/assertj/core/error/ShouldNotBe.java +++ b/src/main/java/org/assertj/core/error/ShouldNotBe.java @@ -35,6 +35,6 @@ public static ErrorMessageFactory shouldNotBe(T actual, Condition } private ShouldNotBe(Object actual, Condition condition) { - super("%nExpecting:%n %s%nnot to be %s", actual, condition); + super("%nExpecting actual:%n %s%nnot to be %s", actual, condition); } } diff --git a/src/main/java/org/assertj/core/error/ShouldNotBeBetween.java b/src/main/java/org/assertj/core/error/ShouldNotBeBetween.java index b885518b9a5..609d719e4cb 100644 --- a/src/main/java/org/assertj/core/error/ShouldNotBeBetween.java +++ b/src/main/java/org/assertj/core/error/ShouldNotBeBetween.java @@ -56,7 +56,7 @@ public static ErrorMessageFactory shouldNotBeBetween(Date actual, Date start, Da private ShouldNotBeBetween(Date actual, Date start, Date end, boolean inclusiveStart, boolean inclusiveEnd, ComparisonStrategy comparisonStrategy) { - super("%nExpecting:%n %s%nnot to be in period:%n "+(inclusiveStart ? '[' : ']') + + super("%nExpecting actual:%n %s%nnot to be in period:%n "+(inclusiveStart ? '[' : ']') + "%s, %s%s" + (inclusiveEnd ? ']' : '['), actual, start, end, comparisonStrategy); } } diff --git a/src/main/java/org/assertj/core/error/ShouldNotBeEqual.java b/src/main/java/org/assertj/core/error/ShouldNotBeEqual.java index 5bce4a65f61..98b7e1e0676 100644 --- a/src/main/java/org/assertj/core/error/ShouldNotBeEqual.java +++ b/src/main/java/org/assertj/core/error/ShouldNotBeEqual.java @@ -44,7 +44,7 @@ public static ErrorMessageFactory shouldNotBeEqual(Object actual, Object other) } private ShouldNotBeEqual(Object actual, Object other, ComparisonStrategy comparisonStrategy) { - super("%nExpecting:%n %s%nnot to be equal to:%n %s%n%s", actual, other, comparisonStrategy); + super("%nExpecting actual:%n %s%nnot to be equal to:%n %s%n%s", actual, other, comparisonStrategy); } } diff --git a/src/main/java/org/assertj/core/error/ShouldNotBeEqualComparingFieldByFieldRecursively.java b/src/main/java/org/assertj/core/error/ShouldNotBeEqualComparingFieldByFieldRecursively.java index df619e9a450..a60922ddd3a 100644 --- a/src/main/java/org/assertj/core/error/ShouldNotBeEqualComparingFieldByFieldRecursively.java +++ b/src/main/java/org/assertj/core/error/ShouldNotBeEqualComparingFieldByFieldRecursively.java @@ -22,7 +22,7 @@ public static ErrorMessageFactory shouldNotBeEqualComparingFieldByFieldRecursive Representation representation) { String recursiveComparisonConfigurationDescription = recursiveComparisonConfiguration.multiLineDescription(representation); return new ShouldNotBeEqualComparingFieldByFieldRecursively("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " %s%n" + "not to be equal to:%n" + " %s%n" + diff --git a/src/main/java/org/assertj/core/error/ShouldNotBeEqualIgnoringCase.java b/src/main/java/org/assertj/core/error/ShouldNotBeEqualIgnoringCase.java index 792b6351357..973908544f0 100644 --- a/src/main/java/org/assertj/core/error/ShouldNotBeEqualIgnoringCase.java +++ b/src/main/java/org/assertj/core/error/ShouldNotBeEqualIgnoringCase.java @@ -33,6 +33,6 @@ public static ErrorMessageFactory shouldNotBeEqualIgnoringCase(CharSequence actu } private ShouldNotBeEqualIgnoringCase(CharSequence actual, CharSequence expected) { - super("%nExpecting:%n %s%nnot to be equal to:%n %s%nignoring case considerations", actual, expected); + super("%nExpecting actual:%n %s%nnot to be equal to:%n %s%nignoring case considerations", actual, expected); } } diff --git a/src/main/java/org/assertj/core/error/ShouldNotBeEqualIgnoringWhitespace.java b/src/main/java/org/assertj/core/error/ShouldNotBeEqualIgnoringWhitespace.java index 1b14ab97eec..1ac583bb425 100644 --- a/src/main/java/org/assertj/core/error/ShouldNotBeEqualIgnoringWhitespace.java +++ b/src/main/java/org/assertj/core/error/ShouldNotBeEqualIgnoringWhitespace.java @@ -31,6 +31,6 @@ public static ErrorMessageFactory shouldNotBeEqualIgnoringWhitespace(CharSequenc } private ShouldNotBeEqualIgnoringWhitespace(CharSequence actual, CharSequence expected) { - super("%nExpecting:%n %s%nnot to be equal to:%n %s%nignoring whitespace differences", actual, expected); + super("%nExpecting actual:%n %s%nnot to be equal to:%n %s%nignoring whitespace differences", actual, expected); } } diff --git a/src/main/java/org/assertj/core/error/ShouldNotBeEqualNormalizingWhitespace.java b/src/main/java/org/assertj/core/error/ShouldNotBeEqualNormalizingWhitespace.java index ddf9bd03285..f32eda25047 100644 --- a/src/main/java/org/assertj/core/error/ShouldNotBeEqualNormalizingWhitespace.java +++ b/src/main/java/org/assertj/core/error/ShouldNotBeEqualNormalizingWhitespace.java @@ -31,6 +31,6 @@ public static ErrorMessageFactory shouldNotBeEqualNormalizingWhitespace(CharSequ } private ShouldNotBeEqualNormalizingWhitespace(CharSequence actual, CharSequence expected) { - super("%nExpecting:%n %s%nnot to be equal to:%n %s%nafter whitespace differences are normalized", actual, expected); + super("%nExpecting actual:%n %s%nnot to be equal to:%n %s%nafter whitespace differences are normalized", actual, expected); } } diff --git a/src/main/java/org/assertj/core/error/ShouldNotBeEqualWithinOffset.java b/src/main/java/org/assertj/core/error/ShouldNotBeEqualWithinOffset.java index 4694766bc95..02475668410 100644 --- a/src/main/java/org/assertj/core/error/ShouldNotBeEqualWithinOffset.java +++ b/src/main/java/org/assertj/core/error/ShouldNotBeEqualWithinOffset.java @@ -36,7 +36,7 @@ public static ErrorMessageFactory shouldNotBeEqual(T actual, private ShouldNotBeEqualWithinOffset(Number actual, Number expected, Offset offset, Number difference) { - super("%nExpecting:%n" + + super("%nExpecting actual:%n" + " %s%n" + "not to be close to:%n" + " %s%n" + diff --git a/src/main/java/org/assertj/core/error/ShouldNotBeEqualWithinPercentage.java b/src/main/java/org/assertj/core/error/ShouldNotBeEqualWithinPercentage.java index 6720d28a7ef..3b96ab61232 100644 --- a/src/main/java/org/assertj/core/error/ShouldNotBeEqualWithinPercentage.java +++ b/src/main/java/org/assertj/core/error/ShouldNotBeEqualWithinPercentage.java @@ -40,7 +40,7 @@ public static ErrorMessageFactory shouldNotBeEqualWithinPerce } private ShouldNotBeEqualWithinPercentage(Number actual, Number expected, Percentage percentage, double expectedPercentage) { - super("%nExpecting:%n" + + super("%nExpecting actual:%n" + " %s%n" + "not to be close to:%n" + " %s%n" + diff --git a/src/main/java/org/assertj/core/error/ShouldNotBeFinite.java b/src/main/java/org/assertj/core/error/ShouldNotBeFinite.java new file mode 100644 index 00000000000..4b58f6e6450 --- /dev/null +++ b/src/main/java/org/assertj/core/error/ShouldNotBeFinite.java @@ -0,0 +1,24 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.error; + +public class ShouldNotBeFinite extends BasicErrorMessageFactory { + + public static ErrorMessageFactory shouldNotBeFinite(Number actual) { + return new ShouldNotBeFinite(actual); + } + + private ShouldNotBeFinite(Number actual) { + super("%nExpecting %s not to be finite", actual); + } +} diff --git a/src/main/java/org/assertj/core/error/ShouldNotBeIn.java b/src/main/java/org/assertj/core/error/ShouldNotBeIn.java index 16f6ad36f13..ba8ed29e787 100644 --- a/src/main/java/org/assertj/core/error/ShouldNotBeIn.java +++ b/src/main/java/org/assertj/core/error/ShouldNotBeIn.java @@ -45,7 +45,7 @@ public static ErrorMessageFactory shouldNotBeIn(Object actual, Object values) { } private ShouldNotBeIn(Object actual, Object values, ComparisonStrategy comparisonStrategy) { - super("%nExpecting:%n %s%nnot to be in:%n %s%n%s", actual, values, comparisonStrategy); + super("%nExpecting actual:%n %s%nnot to be in:%n %s%n%s", actual, values, comparisonStrategy); } } diff --git a/src/main/java/org/assertj/core/error/ShouldNotBeInfinite.java b/src/main/java/org/assertj/core/error/ShouldNotBeInfinite.java new file mode 100644 index 00000000000..61cc66623e9 --- /dev/null +++ b/src/main/java/org/assertj/core/error/ShouldNotBeInfinite.java @@ -0,0 +1,24 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.error; + +public class ShouldNotBeInfinite extends BasicErrorMessageFactory { + + public static ErrorMessageFactory shouldNotBeInfinite(Number actual) { + return new ShouldNotBeInfinite(actual); + } + + private ShouldNotBeInfinite(Number actual) { + super("%nExpecting %s not to be infinite", actual); + } +} diff --git a/src/main/java/org/assertj/core/error/ShouldNotBeInstance.java b/src/main/java/org/assertj/core/error/ShouldNotBeInstance.java index 910f073e26d..fe3af25d201 100644 --- a/src/main/java/org/assertj/core/error/ShouldNotBeInstance.java +++ b/src/main/java/org/assertj/core/error/ShouldNotBeInstance.java @@ -33,10 +33,10 @@ public static ErrorMessageFactory shouldNotBeInstance(Object actual, Class ty } private ShouldNotBeInstance(Object actual, Class type) { - super("%nExpecting:%n %s%nnot to be an instance of: %s", actual, type); + super("%nExpecting actual:%n %s%nnot to be an instance of: %s", actual, type); } private ShouldNotBeInstance(Throwable throwable, Class type) { - super("%nExpecting:%n %s%nnot to be an instance of: %s", getStackTrace(throwable), type); + super("%nExpecting actual:%n %s%nnot to be an instance of: %s", getStackTrace(throwable), type); } } diff --git a/src/main/java/org/assertj/core/error/ShouldNotBeInstanceOfAny.java b/src/main/java/org/assertj/core/error/ShouldNotBeInstanceOfAny.java index ff244bb2a89..5298e006a04 100644 --- a/src/main/java/org/assertj/core/error/ShouldNotBeInstanceOfAny.java +++ b/src/main/java/org/assertj/core/error/ShouldNotBeInstanceOfAny.java @@ -34,10 +34,10 @@ public static ErrorMessageFactory shouldNotBeInstanceOfAny(Object actual, Class< } private ShouldNotBeInstanceOfAny(Object actual, Class[] types) { - super("%nExpecting:%n %s%nnot to be an instance of any of these types:%n %s", actual, types); + super("%nExpecting actual:%n %s%nnot to be an instance of any of these types:%n %s", actual, types); } private ShouldNotBeInstanceOfAny(Throwable throwable, Class[] types) { - super("%nExpecting:%n %s%nnot to be an instance of any of these types:%n %s", getStackTrace(throwable), types); + super("%nExpecting actual:%n %s%nnot to be an instance of any of these types:%n %s", getStackTrace(throwable), types); } } diff --git a/src/main/java/org/assertj/core/error/ShouldNotBeOfClassIn.java b/src/main/java/org/assertj/core/error/ShouldNotBeOfClassIn.java index 0b1dfa111d3..722af2144a9 100644 --- a/src/main/java/org/assertj/core/error/ShouldNotBeOfClassIn.java +++ b/src/main/java/org/assertj/core/error/ShouldNotBeOfClassIn.java @@ -30,6 +30,6 @@ public static ErrorMessageFactory shouldNotBeOfClassIn(Object actual, Object typ } private ShouldNotBeOfClassIn(Object actual, Object types) { - super("%nExpecting:%n %s%nnot to be of any type in:%n %s%nbut was of type: %s", actual, types, actual.getClass()); + super("%nExpecting actual:%n %s%nnot to be of any type in:%n %s%nbut was of type: %s", actual, types, actual.getClass()); } } diff --git a/src/main/java/org/assertj/core/error/ShouldNotContainAtIndex.java b/src/main/java/org/assertj/core/error/ShouldNotContainAtIndex.java index 6ada6d3ecd6..56abe0f7c6d 100644 --- a/src/main/java/org/assertj/core/error/ShouldNotContainAtIndex.java +++ b/src/main/java/org/assertj/core/error/ShouldNotContainAtIndex.java @@ -50,6 +50,6 @@ public static ErrorMessageFactory shouldNotContainAtIndex(Object actual, Object } private ShouldNotContainAtIndex(Object actual, Object expected, Index index, ComparisonStrategy comparisonStrategy) { - super("%nExpecting:%n %s%nnot to contain:%n %s%nat index %s%n%s", actual, expected, index.value, comparisonStrategy); + super("%nExpecting actual:%n %s%nnot to contain:%n %s%nat index %s%n%s", actual, expected, index.value, comparisonStrategy); } } diff --git a/src/main/java/org/assertj/core/error/ShouldNotContainCharSequence.java b/src/main/java/org/assertj/core/error/ShouldNotContainCharSequence.java index e560092529b..8cf299ab672 100644 --- a/src/main/java/org/assertj/core/error/ShouldNotContainCharSequence.java +++ b/src/main/java/org/assertj/core/error/ShouldNotContainCharSequence.java @@ -48,7 +48,7 @@ private ShouldNotContainCharSequence(String format, CharSequence actual, CharSeq public static ErrorMessageFactory shouldNotContain(CharSequence actual, CharSequence sequence, ComparisonStrategy comparisonStrategy) { return new ShouldNotContainCharSequence("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " %s%n" + "not to contain:%n" + " %s%n" + @@ -72,7 +72,7 @@ public static ErrorMessageFactory shouldNotContain(CharSequence actual, CharSequ Set found, ComparisonStrategy comparisonStrategy) { return new ShouldNotContainCharSequence("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " %s%n" + "not to contain:%n" + " %s%n" + @@ -91,7 +91,7 @@ public static ErrorMessageFactory shouldNotContain(CharSequence actual, CharSequ */ public static ErrorMessageFactory shouldNotContainIgnoringCase(CharSequence actual, CharSequence sequence) { return new ShouldNotContainCharSequence("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " %s%n" + "not to contain (ignoring case):%n" + " %s%n" + @@ -102,7 +102,7 @@ public static ErrorMessageFactory shouldNotContainIgnoringCase(CharSequence actu public static ErrorMessageFactory shouldNotContainIgnoringCase(CharSequence actual, CharSequence[] sequences, Set foundSequences) { return new ShouldNotContainCharSequence("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " %s%n" + "not to contain (ignoring case):%n" + " %s%n" + diff --git a/src/main/java/org/assertj/core/error/ShouldNotContainKey.java b/src/main/java/org/assertj/core/error/ShouldNotContainKey.java index 36898ac2ad8..1127956aa1d 100644 --- a/src/main/java/org/assertj/core/error/ShouldNotContainKey.java +++ b/src/main/java/org/assertj/core/error/ShouldNotContainKey.java @@ -30,6 +30,6 @@ public static ErrorMessageFactory shouldNotContainKey(Object actual, Object key) } private ShouldNotContainKey(Object actual, Object key) { - super("%nExpecting:%n %s%nnot to contain key:%n %s", actual, key); + super("%nExpecting actual:%n %s%nnot to contain key:%n %s", actual, key); } } diff --git a/src/main/java/org/assertj/core/error/ShouldNotContainKeys.java b/src/main/java/org/assertj/core/error/ShouldNotContainKeys.java index 82511f3b146..213e91ecdb9 100644 --- a/src/main/java/org/assertj/core/error/ShouldNotContainKeys.java +++ b/src/main/java/org/assertj/core/error/ShouldNotContainKeys.java @@ -37,6 +37,6 @@ public static ErrorMessageFactory shouldNotContainKeys(Object actual, Set } private ShouldNotContainKeys(Object actual, Set key) { - super("%nExpecting:%n %s%nnot to contain keys:%n %s", actual, key); + super("%nExpecting actual:%n %s%nnot to contain keys:%n %s", actual, key); } } diff --git a/src/main/java/org/assertj/core/error/ShouldNotContainNull.java b/src/main/java/org/assertj/core/error/ShouldNotContainNull.java index 2d8f625ada1..b3bb63d5dc3 100644 --- a/src/main/java/org/assertj/core/error/ShouldNotContainNull.java +++ b/src/main/java/org/assertj/core/error/ShouldNotContainNull.java @@ -30,6 +30,6 @@ public static ErrorMessageFactory shouldNotContainNull(Object actual) { } private ShouldNotContainNull(Object actual) { - super("%nExpecting:%n %s%nnot to contain null elements", actual); + super("%nExpecting actual:%n %s%nnot to contain null elements", actual); } } diff --git a/src/main/java/org/assertj/core/error/ShouldNotContainPattern.java b/src/main/java/org/assertj/core/error/ShouldNotContainPattern.java index aba99157152..6e0d3ee05d3 100644 --- a/src/main/java/org/assertj/core/error/ShouldNotContainPattern.java +++ b/src/main/java/org/assertj/core/error/ShouldNotContainPattern.java @@ -30,7 +30,7 @@ public static ErrorMessageFactory shouldNotContainPattern(CharSequence actual, C private ShouldNotContainPattern(CharSequence actual, CharSequence pattern) { super("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " %s%n" + "not to contain pattern:%n" + " %s", diff --git a/src/main/java/org/assertj/core/error/ShouldNotContainSequence.java b/src/main/java/org/assertj/core/error/ShouldNotContainSequence.java index 62eea71ff7a..9baf24fb1ef 100644 --- a/src/main/java/org/assertj/core/error/ShouldNotContainSequence.java +++ b/src/main/java/org/assertj/core/error/ShouldNotContainSequence.java @@ -47,7 +47,7 @@ public static ErrorMessageFactory shouldNotContainSequence(Object actual, Object } private ShouldNotContainSequence(Object actual, Object sequence, int index, ComparisonStrategy comparisonStrategy) { - super("%nExpecting:%n %s%nto not contain sequence:%n %s%nbut was found at index %s%n%s", actual, sequence, index, comparisonStrategy); + super("%nExpecting actual:%n %s%nto not contain sequence:%n %s%nbut was found at index %s%n%s", actual, sequence, index, comparisonStrategy); } } diff --git a/src/main/java/org/assertj/core/error/ShouldNotContainSubsequence.java b/src/main/java/org/assertj/core/error/ShouldNotContainSubsequence.java index ada6208b7c0..24fbfb523de 100644 --- a/src/main/java/org/assertj/core/error/ShouldNotContainSubsequence.java +++ b/src/main/java/org/assertj/core/error/ShouldNotContainSubsequence.java @@ -51,7 +51,7 @@ public static ErrorMessageFactory shouldNotContainSubsequence(Object actual, Obj private ShouldNotContainSubsequence(Object actual, Object subsequence, ComparisonStrategy comparisonStrategy, int index) { - super("%nExpecting:%n %s%nto not contain subsequence:%n %s%nbut was found starting at index %s%n%s", + super("%nExpecting actual:%n %s%nto not contain subsequence:%n %s%nbut was found starting at index %s%n%s", actual, subsequence, index, comparisonStrategy); } } diff --git a/src/main/java/org/assertj/core/error/ShouldNotContainValue.java b/src/main/java/org/assertj/core/error/ShouldNotContainValue.java index 8f7d5ac83ab..48931672ffb 100644 --- a/src/main/java/org/assertj/core/error/ShouldNotContainValue.java +++ b/src/main/java/org/assertj/core/error/ShouldNotContainValue.java @@ -30,6 +30,6 @@ public static ErrorMessageFactory shouldNotContainValue(Object actual, Object va } private ShouldNotContainValue(Object actual, Object value) { - super("%nExpecting:%n %s%nnot to contain value:%n %s", actual, value); + super("%nExpecting actual:%n %s%nnot to contain value:%n %s", actual, value); } } diff --git a/src/main/java/org/assertj/core/error/ShouldNotEndWith.java b/src/main/java/org/assertj/core/error/ShouldNotEndWith.java index 7864723ad4a..e884abe4252 100644 --- a/src/main/java/org/assertj/core/error/ShouldNotEndWith.java +++ b/src/main/java/org/assertj/core/error/ShouldNotEndWith.java @@ -48,6 +48,6 @@ public static ErrorMessageFactory shouldNotEndWith(Object actual, Object expecte } private ShouldNotEndWith(Object actual, Object expected, ComparisonStrategy comparisonStrategy) { - super("%nExpecting:%n %s%nnot to end with:%n %s%n%s", actual, expected, comparisonStrategy); + super("%nExpecting actual:%n %s%nnot to end with:%n %s%n%s", actual, expected, comparisonStrategy); } } diff --git a/src/main/java/org/assertj/core/error/ShouldNotHave.java b/src/main/java/org/assertj/core/error/ShouldNotHave.java index 2adb9e0785b..bda49127da5 100644 --- a/src/main/java/org/assertj/core/error/ShouldNotHave.java +++ b/src/main/java/org/assertj/core/error/ShouldNotHave.java @@ -35,6 +35,6 @@ public static ErrorMessageFactory shouldNotHave(T actual, Condition condition) { - super("%nExpecting:%n %s%nnot to have:%n %s", actual, condition); + super("%nExpecting actual:%n %s%nnot to have %s", actual, condition); } } diff --git a/src/main/java/org/assertj/core/error/ShouldNotHaveAnyElementsOfTypes.java b/src/main/java/org/assertj/core/error/ShouldNotHaveAnyElementsOfTypes.java index 5ae8068816b..2931f8b96fc 100644 --- a/src/main/java/org/assertj/core/error/ShouldNotHaveAnyElementsOfTypes.java +++ b/src/main/java/org/assertj/core/error/ShouldNotHaveAnyElementsOfTypes.java @@ -20,7 +20,7 @@ public class ShouldNotHaveAnyElementsOfTypes extends BasicErrorMessageFactory { private ShouldNotHaveAnyElementsOfTypes(Object actual, Class[] unexpectedTypes, Map, List> nonMatchingElementsByType) { super("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " %s%n" + "to not have any elements of the following types:%n" + " %s%n" + diff --git a/src/main/java/org/assertj/core/error/ShouldNotHaveSameClass.java b/src/main/java/org/assertj/core/error/ShouldNotHaveSameClass.java index d9668d385a7..2690068e5ca 100644 --- a/src/main/java/org/assertj/core/error/ShouldNotHaveSameClass.java +++ b/src/main/java/org/assertj/core/error/ShouldNotHaveSameClass.java @@ -30,6 +30,6 @@ public static ErrorMessageFactory shouldNotHaveSameClass(Object actual, Object o } private ShouldNotHaveSameClass(Object actual, Object other) { - super("%nExpecting:%n %s%nnot to have the same class as:%n %s (%s)", actual, other, actual.getClass()); + super("%nExpecting actual:%n %s%nnot to have the same class as:%n %s (%s)", actual, other, actual.getClass()); } } diff --git a/src/main/java/org/assertj/core/error/ShouldNotMatch.java b/src/main/java/org/assertj/core/error/ShouldNotMatch.java index 97ed64e5c5c..3f2af6ef421 100644 --- a/src/main/java/org/assertj/core/error/ShouldNotMatch.java +++ b/src/main/java/org/assertj/core/error/ShouldNotMatch.java @@ -32,7 +32,7 @@ public class ShouldNotMatch extends BasicErrorMessageFactory { " assertThat(player).doesNotMatch(p -> p.isRookie(), \"is not rookie\");%n" + "will give an error message looking like:%n" + "%n" + - "Expecting:%n" + + "Expecting actual:%n" + " player%n" + "not to match 'is not rookie' predicate"); // @format:on @@ -53,6 +53,6 @@ public static ErrorMessageFactory shouldNotMatch(T actual, Predicate[] types, Iterable nonMatchingElements) { super("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " %s%n" + "to only have instances of:%n" + " %s%n" + diff --git a/src/main/java/org/assertj/core/error/ShouldSatisfy.java b/src/main/java/org/assertj/core/error/ShouldSatisfy.java index 46b3d3db58f..47071eb44fd 100644 --- a/src/main/java/org/assertj/core/error/ShouldSatisfy.java +++ b/src/main/java/org/assertj/core/error/ShouldSatisfy.java @@ -24,9 +24,9 @@ public class ShouldSatisfy extends BasicErrorMessageFactory { @VisibleForTesting - public static final String CONDITION_SHOULD_BE_SATISFIED = "%nExpecting:%n %s%nto satisfy:%n %s"; + public static final String CONDITION_SHOULD_BE_SATISFIED = "%nExpecting actual:%n %s%nto satisfy:%n %s"; @VisibleForTesting - public static final String CONSUMERS_SHOULD_BE_SATISFIED_IN_ANY_ORDER = "%nExpecting:%n %s%nto satisfy all the consumers in any order."; + public static final String CONSUMERS_SHOULD_BE_SATISFIED_IN_ANY_ORDER = "%nExpecting actual:%n %s%nto satisfy all the consumers in any order."; @VisibleForTesting public static final String CONSUMERS_SHOULD_NOT_BE_NULL = "The Consumer... expressing the assertions consumers must not be null"; diff --git a/src/main/java/org/assertj/core/error/ShouldStartWith.java b/src/main/java/org/assertj/core/error/ShouldStartWith.java index 22707bc487d..51b08ba753b 100644 --- a/src/main/java/org/assertj/core/error/ShouldStartWith.java +++ b/src/main/java/org/assertj/core/error/ShouldStartWith.java @@ -45,7 +45,7 @@ public static ErrorMessageFactory shouldStartWith(Object actual, Object expected } private ShouldStartWith(Object actual, Object expected, ComparisonStrategy comparisonStrategy) { - super("%nExpecting:%n %s%nto start with:%n %s%n%s", actual, expected, comparisonStrategy); + super("%nExpecting actual:%n %s%nto start with:%n %s%n%s", actual, expected, comparisonStrategy); } } diff --git a/src/main/java/org/assertj/core/error/uri/ShouldHaveAnchor.java b/src/main/java/org/assertj/core/error/uri/ShouldHaveAnchor.java index ea509d32f34..a29ba795dbf 100644 --- a/src/main/java/org/assertj/core/error/uri/ShouldHaveAnchor.java +++ b/src/main/java/org/assertj/core/error/uri/ShouldHaveAnchor.java @@ -20,7 +20,7 @@ public class ShouldHaveAnchor extends BasicErrorMessageFactory { private static final String SHOULD_HAVE_ANCHOR = "%nExpecting anchor of%n <%s>%nto be:%n <%s>%nbut was:%n <%s>"; - private static final String SHOULD_NOT_HAVE_ANCHOR = "%nExpecting:%n <%s>%nnot to have an anchor but had:%n <%s>"; + private static final String SHOULD_NOT_HAVE_ANCHOR = "%nExpecting actual:%n <%s>%nnot to have an anchor but had:%n <%s>"; public static ErrorMessageFactory shouldHaveAnchor(URL actual, String expectedAnchor) { return expectedAnchor == null ? new ShouldHaveAnchor(actual) : new ShouldHaveAnchor(actual, expectedAnchor); diff --git a/src/main/java/org/assertj/core/error/uri/ShouldHaveParameter.java b/src/main/java/org/assertj/core/error/uri/ShouldHaveParameter.java index 2bb266b799a..6fea16ece3c 100644 --- a/src/main/java/org/assertj/core/error/uri/ShouldHaveParameter.java +++ b/src/main/java/org/assertj/core/error/uri/ShouldHaveParameter.java @@ -20,25 +20,25 @@ public class ShouldHaveParameter extends BasicErrorMessageFactory { - private static final String SHOULD_HAVE_PARAMETER_BUT_WAS_MISSING = "%nExpecting:%n <%s>%nto have parameter:%n <%s>%nbut was missing"; - private static final String SHOULD_HAVE_PARAMETER_WITHOUT_VALUE_BUT_PARAMETER_WAS_MISSING = "%nExpecting:%n <%s>%nto have parameter:%n <%s>%nwith no value, but parameter was missing"; - private static final String SHOULD_HAVE_PARAMETER_WITH_VALUE_BUT_PARAMETER_WAS_MISSING = "%nExpecting:%n <%s>%nto have parameter:%n <%s>%nwith value:%n <%s>%nbut parameter was missing"; + private static final String SHOULD_HAVE_PARAMETER_BUT_WAS_MISSING = "%nExpecting actual:%n <%s>%nto have parameter:%n <%s>%nbut was missing"; + private static final String SHOULD_HAVE_PARAMETER_WITHOUT_VALUE_BUT_PARAMETER_WAS_MISSING = "%nExpecting actual:%n <%s>%nto have parameter:%n <%s>%nwith no value, but parameter was missing"; + private static final String SHOULD_HAVE_PARAMETER_WITH_VALUE_BUT_PARAMETER_WAS_MISSING = "%nExpecting actual:%n <%s>%nto have parameter:%n <%s>%nwith value:%n <%s>%nbut parameter was missing"; - private static final String SHOULD_HAVE_PARAMETER_WITHOUT_VALUE_BUT_HAD_VALUE = "%nExpecting:%n <%s>%nto have parameter:%n <%s>%nwith no value, but parameter had value:%n <%s>"; - private static final String SHOULD_HAVE_PARAMETER_WITHOUT_VALUE_BUT_HAD_VALUES = "%nExpecting:%n <%s>%nto have parameter:%n <%s>%nwith no value, but parameter had values:%n <%s>"; - private static final String SHOULD_HAVE_PARAMETER_WITH_VALUE_BUT_HAD_NO_VALUE = "%nExpecting:%n <%s>%nto have parameter:%n <%s>%nwith value:%n <%s>%nbut parameter had no value"; + private static final String SHOULD_HAVE_PARAMETER_WITHOUT_VALUE_BUT_HAD_VALUE = "%nExpecting actual:%n <%s>%nto have parameter:%n <%s>%nwith no value, but parameter had value:%n <%s>"; + private static final String SHOULD_HAVE_PARAMETER_WITHOUT_VALUE_BUT_HAD_VALUES = "%nExpecting actual:%n <%s>%nto have parameter:%n <%s>%nwith no value, but parameter had values:%n <%s>"; + private static final String SHOULD_HAVE_PARAMETER_WITH_VALUE_BUT_HAD_NO_VALUE = "%nExpecting actual:%n <%s>%nto have parameter:%n <%s>%nwith value:%n <%s>%nbut parameter had no value"; - private static final String SHOULD_HAVE_PARAMETER_VALUE_BUT_HAD_WRONG_VALUE = "%nExpecting:%n <%s>%nto have parameter:%n <%s>%nwith value:%n <%s>%nbut had value:%n <%s>"; - private static final String SHOULD_HAVE_PARAMETER_VALUE_BUT_HAD_WRONG_VALUES = "%nExpecting:%n <%s>%nto have parameter:%n <%s>%nwith value:%n <%s>%nbut had values:%n <%s>"; + private static final String SHOULD_HAVE_PARAMETER_VALUE_BUT_HAD_WRONG_VALUE = "%nExpecting actual:%n <%s>%nto have parameter:%n <%s>%nwith value:%n <%s>%nbut had value:%n <%s>"; + private static final String SHOULD_HAVE_PARAMETER_VALUE_BUT_HAD_WRONG_VALUES = "%nExpecting actual:%n <%s>%nto have parameter:%n <%s>%nwith value:%n <%s>%nbut had values:%n <%s>"; - private static final String SHOULD_HAVE_NO_PARAMETER_BUT_HAD_ONE_WITHOUT_VALUE = "%nExpecting:%n <%s>%nnot to have parameter:%n <%s>%nbut parameter was present with no value"; - private static final String SHOULD_HAVE_NO_PARAMETER_BUT_HAD_ONE_VALUE = "%nExpecting:%n <%s>%nnot to have parameter:%n <%s>%nbut parameter was present with value:%n <%s>"; - private static final String SHOULD_HAVE_NO_PARAMETER_BUT_HAD_MULTIPLE_VALUES = "%nExpecting:%n <%s>%nnot to have parameter:%n <%s>%nbut parameter was present with values:%n <%s>"; + private static final String SHOULD_HAVE_NO_PARAMETER_BUT_HAD_ONE_WITHOUT_VALUE = "%nExpecting actual:%n <%s>%nnot to have parameter:%n <%s>%nbut parameter was present with no value"; + private static final String SHOULD_HAVE_NO_PARAMETER_BUT_HAD_ONE_VALUE = "%nExpecting actual:%n <%s>%nnot to have parameter:%n <%s>%nbut parameter was present with value:%n <%s>"; + private static final String SHOULD_HAVE_NO_PARAMETER_BUT_HAD_MULTIPLE_VALUES = "%nExpecting actual:%n <%s>%nnot to have parameter:%n <%s>%nbut parameter was present with values:%n <%s>"; - private static final String SHOULD_HAVE_NO_PARAMETER_WITHOUT_VALUE_BUT_FOUND_ONE = "%nExpecting:%n <%s>%nnot to have parameter:%n <%s>%nwith no value, but did"; - private static final String SHOULD_HAVE_NO_PARAMETER_WITH_GIVEN_VALUE_BUT_FOUND_ONE = "%nExpecting:%n <%s>%nnot to have parameter:%n <%s>%nwith value:%n <%s>%nbut did"; + private static final String SHOULD_HAVE_NO_PARAMETER_WITHOUT_VALUE_BUT_FOUND_ONE = "%nExpecting actual:%n <%s>%nnot to have parameter:%n <%s>%nwith no value, but did"; + private static final String SHOULD_HAVE_NO_PARAMETER_WITH_GIVEN_VALUE_BUT_FOUND_ONE = "%nExpecting actual:%n <%s>%nnot to have parameter:%n <%s>%nwith value:%n <%s>%nbut did"; - private static final String SHOULD_HAVE_NO_PARAMETERS = "%nExpecting:%n <%s>%nnot to have any parameters but found:%n <%s>"; + private static final String SHOULD_HAVE_NO_PARAMETERS = "%nExpecting actual:%n <%s>%nnot to have any parameters but found:%n <%s>"; public static ErrorMessageFactory shouldHaveParameter(Object actual, String name) { return new ShouldHaveParameter(SHOULD_HAVE_PARAMETER_BUT_WAS_MISSING, actual, name); diff --git a/src/main/java/org/assertj/core/error/uri/ShouldHavePath.java b/src/main/java/org/assertj/core/error/uri/ShouldHavePath.java index 98244f60da5..ba40d505e04 100644 --- a/src/main/java/org/assertj/core/error/uri/ShouldHavePath.java +++ b/src/main/java/org/assertj/core/error/uri/ShouldHavePath.java @@ -22,7 +22,7 @@ public class ShouldHavePath extends BasicErrorMessageFactory { - private static final String SHOULD_NOT_HAVE_PATH = "%nExpecting:%n <%s>%nnot to have a path but had:%n <%s>"; + private static final String SHOULD_NOT_HAVE_PATH = "%nExpecting actual:%n <%s>%nnot to have a path but had:%n <%s>"; private static final String SHOULD_HAVE_PATH = "%nExpecting path of%n <%s>%nto be:%n <%s>%nbut was:%n <%s>"; public static ErrorMessageFactory shouldHavePath(URI actual, String expectedPath) { diff --git a/src/main/java/org/assertj/core/error/uri/ShouldHavePort.java b/src/main/java/org/assertj/core/error/uri/ShouldHavePort.java index 8880fcbdb34..9a8c7d04ee8 100644 --- a/src/main/java/org/assertj/core/error/uri/ShouldHavePort.java +++ b/src/main/java/org/assertj/core/error/uri/ShouldHavePort.java @@ -21,7 +21,7 @@ public class ShouldHavePort extends BasicErrorMessageFactory { private static final int NO_PORT = -1; - private static final String SHOULD_HAVE_NO_PORT = "%nExpecting:%n <%s>%nnot to have a port but had:%n <%s>"; + private static final String SHOULD_HAVE_NO_PORT = "%nExpecting actual:%n <%s>%nnot to have a port but had:%n <%s>"; private static final String SHOULD_HAVE_PORT = "%nExpecting port of%n <%s>%nto be:%n <%s>%nbut was:%n <%s>"; public static ErrorMessageFactory shouldHavePort(URI actual, int expectedPort) { diff --git a/src/main/java/org/assertj/core/error/uri/ShouldHaveQuery.java b/src/main/java/org/assertj/core/error/uri/ShouldHaveQuery.java index e84390729b6..096b019e98e 100644 --- a/src/main/java/org/assertj/core/error/uri/ShouldHaveQuery.java +++ b/src/main/java/org/assertj/core/error/uri/ShouldHaveQuery.java @@ -21,7 +21,7 @@ public class ShouldHaveQuery extends BasicErrorMessageFactory { private static final String SHOULD_HAVE_QUERY = "%nExpecting query of%n <%s>%nto be:%n <%s>%nbut was:%n <%s>"; - private static final String SHOULD_NOT_HAVE_QUERY = "%nExpecting:%n <%s>%nnot to have a query but had:%n <%s>"; + private static final String SHOULD_NOT_HAVE_QUERY = "%nExpecting actual:%n <%s>%nnot to have a query but had:%n <%s>"; public static ErrorMessageFactory shouldHaveQuery(URI actual, String expectedQuery) { return expectedQuery == null ? new ShouldHaveQuery(actual) : new ShouldHaveQuery(actual, expectedQuery); diff --git a/src/main/java/org/assertj/core/error/uri/ShouldHaveUserInfo.java b/src/main/java/org/assertj/core/error/uri/ShouldHaveUserInfo.java index a5642bcbba5..c9d20d74e3a 100644 --- a/src/main/java/org/assertj/core/error/uri/ShouldHaveUserInfo.java +++ b/src/main/java/org/assertj/core/error/uri/ShouldHaveUserInfo.java @@ -20,7 +20,7 @@ public class ShouldHaveUserInfo extends BasicErrorMessageFactory { - private static final String SHOULD_HAVE_NO_USER_INFO = "%nExpecting:%n <%s>%nnot to have user info but had:%n <%s>"; + private static final String SHOULD_HAVE_NO_USER_INFO = "%nExpecting actual:%n <%s>%nnot to have user info but had:%n <%s>"; private static final String SHOULD_HAVE_USER_INFO = "%nExpecting user info of%n <%s>%nto be:%n <%s>%nbut was:%n <%s>"; public static ErrorMessageFactory shouldHaveUserInfo(URI actual, String expectedUserInfo) { diff --git a/src/main/java/org/assertj/core/internal/AtomicReferenceArrayElementComparisonStrategy.java b/src/main/java/org/assertj/core/internal/AtomicReferenceArrayElementComparisonStrategy.java index dfd850a9726..179631bcf27 100644 --- a/src/main/java/org/assertj/core/internal/AtomicReferenceArrayElementComparisonStrategy.java +++ b/src/main/java/org/assertj/core/internal/AtomicReferenceArrayElementComparisonStrategy.java @@ -20,7 +20,7 @@ public class AtomicReferenceArrayElementComparisonStrategy extends StandardComparisonStrategy { - private Comparator elementComparator; + private final Comparator elementComparator; public AtomicReferenceArrayElementComparisonStrategy(Comparator elementComparator) { this.elementComparator = elementComparator; diff --git a/src/main/java/org/assertj/core/internal/Classes.java b/src/main/java/org/assertj/core/internal/Classes.java index dcd4247b135..d8f6c20d469 100644 --- a/src/main/java/org/assertj/core/internal/Classes.java +++ b/src/main/java/org/assertj/core/internal/Classes.java @@ -250,7 +250,7 @@ public void assertIsNotFinal(AssertionInfo info, Class actual) { * @throws AssertionError if the actual {@code Class} doesn't contains all of these annotations. */ public void assertContainsAnnotations(AssertionInfo info, Class actual, - @SuppressWarnings("unchecked") Class... annotations) { + Class[] annotations) { assertNotNull(info, actual); Set> expected = newLinkedHashSet(annotations); Set> missing = new LinkedHashSet<>(); @@ -274,7 +274,7 @@ public void assertContainsAnnotations(AssertionInfo info, Class actual, */ public void assertHasSuperclass(AssertionInfo info, Class actual, Class superclass) { assertNotNull(info, actual); - requireNonNull(superclass, shouldNotBeNull("superclass").create()); + requireNonNull(superclass, shouldNotBeNull("superclass")::create); Class actualSuperclass = actual.getSuperclass(); if (actualSuperclass == null || !actualSuperclass.equals(superclass)) { throw failures.failure(info, shouldHaveSuperclass(actual, superclass)); @@ -595,7 +595,7 @@ private static void classParameterIsNotNull(Class clazz) { */ public void assertHasPackage(AssertionInfo info, Class actual, String packageName) { assertNotNull(info, actual); - requireNonNull(packageName, shouldNotBeNull("packageName").create()); + requireNonNull(packageName, shouldNotBeNull("packageName")::create); Package actualPackage = actual.getPackage(); if (actualPackage == null || !actualPackage.getName().equals(packageName)) { @@ -615,7 +615,7 @@ public void assertHasPackage(AssertionInfo info, Class actual, String package */ public void assertHasPackage(AssertionInfo info, Class actual, Package aPackage) { assertNotNull(info, actual); - requireNonNull(aPackage, shouldNotBeNull("aPackage").create()); + requireNonNull(aPackage, shouldNotBeNull("aPackage")::create); Package actualPackage = actual.getPackage(); if (!aPackage.equals(actualPackage)) { diff --git a/src/main/java/org/assertj/core/internal/Doubles.java b/src/main/java/org/assertj/core/internal/Doubles.java index 6aa8ceeb1fd..cfb1d8d0f83 100644 --- a/src/main/java/org/assertj/core/internal/Doubles.java +++ b/src/main/java/org/assertj/core/internal/Doubles.java @@ -62,7 +62,7 @@ protected Double NaN() { @Override protected Double absDiff(Double actual, Double other) { - return abs(other.doubleValue() - actual.doubleValue()); + return abs(other - actual); } @Override @@ -70,8 +70,18 @@ protected boolean isFinite(Double value) { return Double.isFinite(value); } + @Override + protected boolean isNotFinite(Double value) { + return !Double.isFinite(value); + } + @Override protected boolean isInfinite(Double value) { return Double.isInfinite(value); } + + @Override + protected boolean isNotInfinite(Double value) { + return !Double.isInfinite(value); + } } diff --git a/src/main/java/org/assertj/core/internal/ErrorMessages.java b/src/main/java/org/assertj/core/internal/ErrorMessages.java index 5dc99e2aa28..16294c0f151 100644 --- a/src/main/java/org/assertj/core/internal/ErrorMessages.java +++ b/src/main/java/org/assertj/core/internal/ErrorMessages.java @@ -55,6 +55,10 @@ public static String entriesToLookForIsNull() { return "The array of entries to look for should not be null"; } + public static String mapOfEntriesToLookForIsNull() { + return "The map of entries to look for should not be null"; + } + public static String entryToLookForIsNull() { return "Entries to look for should not be null"; } diff --git a/src/main/java/org/assertj/core/internal/FieldByFieldComparator.java b/src/main/java/org/assertj/core/internal/FieldByFieldComparator.java index 0c75c3e7f2c..365c2f9fafc 100644 --- a/src/main/java/org/assertj/core/internal/FieldByFieldComparator.java +++ b/src/main/java/org/assertj/core/internal/FieldByFieldComparator.java @@ -24,13 +24,23 @@ import java.util.Map.Entry; import java.util.TreeMap; +import org.assertj.core.api.AbstractIterableAssert; +import org.assertj.core.api.AbstractObjectAssert; import org.assertj.core.api.Assertions; +import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration; import org.assertj.core.util.introspection.IntrospectionError; /** + * Deprecated javadoc + *

    * Compares objects field/property by field/property including private fields unless * {@link Assertions#setAllowComparingPrivateFields(boolean)} has been called with false. + * @deprecated + * This comparator is deprecated because it performs a shallow field by field comparison, i.e. elements are compared + * field by field but the fields are compared with equals, use {@link AbstractIterableAssert#usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration)} + * or {@link AbstractObjectAssert#usingRecursiveComparison()} instead to perform a true recursive comparison. */ +@Deprecated public class FieldByFieldComparator implements Comparator { protected final Map> comparatorsByPropertyOrField; diff --git a/src/main/java/org/assertj/core/internal/Floats.java b/src/main/java/org/assertj/core/internal/Floats.java index b2cd61bb47a..bc47ce07228 100644 --- a/src/main/java/org/assertj/core/internal/Floats.java +++ b/src/main/java/org/assertj/core/internal/Floats.java @@ -63,7 +63,7 @@ protected Float NaN() { @Override protected Float absDiff(Float actual, Float other) { - return abs(other.floatValue() - actual.floatValue()); + return abs(other - actual); } @Override @@ -71,8 +71,18 @@ protected boolean isFinite(Float value) { return Float.isFinite(value); } + @Override + protected boolean isNotFinite(Float value) { + return !Float.isFinite(value); + } + @Override protected boolean isInfinite(Float value) { return Float.isInfinite(value); } + + @Override + protected boolean isNotInfinite(Float value) { + return !Float.isInfinite(value); + } } diff --git a/src/main/java/org/assertj/core/internal/IgnoringFieldsComparator.java b/src/main/java/org/assertj/core/internal/IgnoringFieldsComparator.java index 05e3c72d242..c3589324e6d 100644 --- a/src/main/java/org/assertj/core/internal/IgnoringFieldsComparator.java +++ b/src/main/java/org/assertj/core/internal/IgnoringFieldsComparator.java @@ -19,9 +19,19 @@ import java.util.HashMap; import java.util.Map; +import org.assertj.core.api.AbstractIterableAssert; +import org.assertj.core.api.AbstractObjectAssert; +import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration; import org.assertj.core.util.VisibleForTesting; import org.assertj.core.util.introspection.IntrospectionError; +/** + * @deprecated + * This comparator is deprecated because it performs a shallow field by field comparison, i.e. elements are compared + * field by field but the fields are compared with equals, use {@link AbstractIterableAssert#usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration)} + * or {@link AbstractObjectAssert#usingRecursiveComparison()} instead to perform a true recursive comparison. + */ +@Deprecated public class IgnoringFieldsComparator extends FieldByFieldComparator { private final String[] fields; diff --git a/src/main/java/org/assertj/core/internal/IterableDiff.java b/src/main/java/org/assertj/core/internal/IterableDiff.java index 5254c605c08..c7ece65b8f3 100644 --- a/src/main/java/org/assertj/core/internal/IterableDiff.java +++ b/src/main/java/org/assertj/core/internal/IterableDiff.java @@ -19,23 +19,30 @@ import java.util.List; // immutable -class IterableDiff { +/** + * @param the type of element to compare. + */ +class IterableDiff { private final ComparisonStrategy comparisonStrategy; - List unexpected; - List missing; + List unexpected; + List missing; - IterableDiff(Iterable actual, Iterable expected, ComparisonStrategy comparisonStrategy) { + IterableDiff(Iterable actual, Iterable expected, ComparisonStrategy comparisonStrategy) { this.comparisonStrategy = comparisonStrategy; // return the elements in actual that are not in expected: actual - expected - this.unexpected = subtract(actual, expected); + this.unexpected = unexpectedActualElements(actual, expected); // return the elements in expected that are not in actual: expected - actual - this.missing = subtract(expected, actual); + this.missing = missingActualElements(actual, expected); + } + + static IterableDiff diff(Iterable actual, Iterable expected, ComparisonStrategy comparisonStrategy) { + return new IterableDiff<>(actual, expected, comparisonStrategy); } - static IterableDiff diff(Iterable actual, Iterable expected, ComparisonStrategy comparisonStrategy) { - return new IterableDiff(actual, expected, comparisonStrategy); + static IterableDiff diff(Iterable actual, Iterable expected) { + return diff(actual, expected, StandardComparisonStrategy.instance()); } boolean differencesFound() { @@ -45,31 +52,54 @@ boolean differencesFound() { /** * Returns the list of elements in the first iterable that are not in the second, i.e. first - second * - * @param the element type - * @param first the list we want to subtract from - * @param second the list to subtract + * @param actual the list we want to subtract from + * @param expected the list to subtract * @return the list of elements in the first iterable that are not in the second, i.e. first - second */ - private List subtract(Iterable first, Iterable second) { - List missingInFirst = new ArrayList<>(); + private List unexpectedActualElements(Iterable actual, Iterable expected) { + List missingInFirst = new ArrayList<>(); // use a copy to deal correctly with potential duplicates - List copyOfSecond = newArrayList(second); - for (Object elementInFirst : first) { - if (iterableContains(copyOfSecond, elementInFirst)) { + List copyOfExpected = newArrayList(expected); + for (T elementInActual : actual) { + if (isActualElementInExpected(elementInActual, copyOfExpected)) { // remove the element otherwise a duplicate would be found in the case if there is one in actual - iterablesRemoveFirst(copyOfSecond, elementInFirst); + iterablesRemoveFirst(copyOfExpected, elementInActual); } else { - missingInFirst.add(elementInFirst); + missingInFirst.add(elementInActual); } } return unmodifiableList(missingInFirst); } - private boolean iterableContains(Iterable actual, Object value) { - return comparisonStrategy.iterableContains(actual, value); + private boolean isActualElementInExpected(T elementInActual, List copyOfExpected) { + // the order of comparisonStrategy.areEqual is important if element comparison is not symmetrical, we must compare actual to + // expected but not expected to actual, for ex recursive comparison where: + // - actual element is PersonDto, expected a list of Person + // - Person has more fields than PersonDto => comparing PersonDto to Person is ok as it looks at PersonDto fields only, + // --- the opposite always fails as the reference fields are Person fields and PersonDto does not have all of them. + return copyOfExpected.stream().anyMatch(expectedElement -> comparisonStrategy.areEqual(elementInActual, expectedElement)); + } + + private List missingActualElements(Iterable actual, Iterable expected) { + List missingInExpected = new ArrayList<>(); + // use a copy to deal correctly with potential duplicates + List copyOfActual = newArrayList(actual); + for (T expectedElement : expected) { + if (iterableContains(copyOfActual, expectedElement)) { + // remove the element otherwise a duplicate would be found in the case if there is one in actual + iterablesRemoveFirst(copyOfActual, expectedElement); + } else { + missingInExpected.add(expectedElement); + } + } + return unmodifiableList(missingInExpected); + } + + private boolean iterableContains(Iterable actual, T expectedElement) { + return comparisonStrategy.iterableContains(actual, expectedElement); } - private void iterablesRemoveFirst(Iterable actual, Object value) { + private void iterablesRemoveFirst(Iterable actual, T value) { comparisonStrategy.iterablesRemoveFirst(actual, value); } } diff --git a/src/main/java/org/assertj/core/internal/IterableElementComparisonStrategy.java b/src/main/java/org/assertj/core/internal/IterableElementComparisonStrategy.java index 6df8a8d2787..de5e19dd2de 100644 --- a/src/main/java/org/assertj/core/internal/IterableElementComparisonStrategy.java +++ b/src/main/java/org/assertj/core/internal/IterableElementComparisonStrategy.java @@ -21,7 +21,7 @@ public class IterableElementComparisonStrategy extends StandardComparisonStrategy { - private Comparator elementComparator; + private final Comparator elementComparator; public IterableElementComparisonStrategy(Comparator elementComparator) { this.elementComparator = elementComparator; diff --git a/src/main/java/org/assertj/core/internal/Iterables.java b/src/main/java/org/assertj/core/internal/Iterables.java index 78effc97cb6..37127c61e1c 100644 --- a/src/main/java/org/assertj/core/internal/Iterables.java +++ b/src/main/java/org/assertj/core/internal/Iterables.java @@ -342,15 +342,16 @@ public void assertContains(AssertionInfo info, Iterable actual, Object[] valu final List actualAsList = newArrayList(actual); if (commonCheckThatIterableAssertionSucceeds(info, actualAsList, values)) return; // check for elements in values that are missing in actual. - assertIterableContainsGivenValues(actualAsList, values, info); + assertIterableContainsGivenValues(actual.getClass(), actualAsList, values, info); } - private void assertIterableContainsGivenValues(Iterable actual, Object[] values, AssertionInfo info) { + private void assertIterableContainsGivenValues(@SuppressWarnings("rawtypes") Class clazz, + Iterable actual, Object[] values, AssertionInfo info) { Set notFound = stream(values).filter(value -> !iterableContains(actual, value)) .collect(toCollection(LinkedHashSet::new)); if (notFound.isEmpty()) return; - throw failures.failure(info, shouldContain(actual, values, notFound, comparisonStrategy)); + throw failures.failure(info, shouldContain(clazz, actual, values, notFound, comparisonStrategy)); } private boolean iterableContains(Iterable actual, Object value) { @@ -1099,10 +1100,11 @@ public void assertHaveExactly(AssertionInfo info, Iterable actu * {@code Iterable}, in any order. */ public void assertContainsAll(AssertionInfo info, Iterable actual, Iterable other) { + final List actualAsList = newArrayList(actual); checkIterableIsNotNull(other); - assertNotNull(info, actual); + assertNotNull(info, actualAsList); Object[] values = newArrayList(other).toArray(); - assertIterableContainsGivenValues(actual, values, info); + assertIterableContainsGivenValues(actual.getClass(), actualAsList, values, info); } /** @@ -1161,7 +1163,7 @@ private static Optional failsRequirements(Consumer void assertSatisfiesExactly(AssertionInfo info, Iterable actual, - @SuppressWarnings("unchecked") Consumer... allRequirements) { + Consumer[] allRequirements) { assertNotNull(info, actual); assertHasSameSizeAs(info, actual, allRequirements); // TODO List actualAsList = newArrayList(actual); @@ -1177,9 +1179,8 @@ public void assertSatisfiesExactly(AssertionInfo info, Iterable } - @SafeVarargs - public final void assertSatisfiesExactlyInAnyOrder(AssertionInfo info, Iterable actual, - @SuppressWarnings("unchecked") Consumer... consumers) { + public void assertSatisfiesExactlyInAnyOrder(AssertionInfo info, Iterable actual, + Consumer[] consumers) { assertNotNull(info, actual); requireNonNull(consumers, "The Consumer... expressing the assertions must not be null"); for (Consumer consumer : consumers) diff --git a/src/main/java/org/assertj/core/internal/Maps.java b/src/main/java/org/assertj/core/internal/Maps.java index 9163223422c..d4ce2a939b1 100644 --- a/src/main/java/org/assertj/core/internal/Maps.java +++ b/src/main/java/org/assertj/core/internal/Maps.java @@ -12,6 +12,7 @@ */ package org.assertj.core.internal; +import static java.util.Objects.deepEquals; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toList; import static org.assertj.core.data.MapEntry.entry; @@ -22,6 +23,7 @@ import static org.assertj.core.error.ShouldBeEmpty.shouldBeEmpty; import static org.assertj.core.error.ShouldBeNullOrEmpty.shouldBeNullOrEmpty; import static org.assertj.core.error.ShouldContain.shouldContain; +import static org.assertj.core.error.ShouldContainAnyOf.shouldContainAnyOf; import static org.assertj.core.error.ShouldContainEntry.shouldContainEntry; import static org.assertj.core.error.ShouldContainExactly.elementsDifferAtIndex; import static org.assertj.core.error.ShouldContainExactly.shouldContainExactly; @@ -46,16 +48,19 @@ import static org.assertj.core.internal.CommonValidations.hasSameSizeAsCheck; import static org.assertj.core.internal.ErrorMessages.keysToLookForIsEmpty; import static org.assertj.core.internal.ErrorMessages.keysToLookForIsNull; +import static org.assertj.core.util.Arrays.array; import static org.assertj.core.util.Arrays.asList; import static org.assertj.core.util.IterableUtil.toArray; import static org.assertj.core.util.Objects.areEqual; import static org.assertj.core.util.Preconditions.checkArgument; +import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.Optional; import java.util.Set; import java.util.function.BiConsumer; @@ -63,7 +68,7 @@ import org.assertj.core.api.AssertionInfo; import org.assertj.core.api.Condition; -import org.assertj.core.error.ShouldContainAnyOf; +import org.assertj.core.data.MapEntry; import org.assertj.core.error.UnsatisfiedRequirement; import org.assertj.core.util.VisibleForTesting; @@ -78,11 +83,6 @@ public class Maps { private static final Maps INSTANCE = new Maps(); - /** - * Returns the singleton instance of this class. - * - * @return the singleton instance of this class. - */ public static Maps instance() { return INSTANCE; } @@ -111,7 +111,7 @@ public void assertAllSatisfy(AssertionInfo info, Map actual, } private static Optional failsRequirements(BiConsumer entryRequirements, - Map.Entry entry) { + Entry entry) { try { entryRequirements.accept(entry.getKey(), entry.getValue()); } catch (AssertionError ex) { @@ -126,7 +126,7 @@ public void assertAnySatisfy(AssertionInfo info, Map actual, assertNotNull(info, actual); List unsatisfiedRequirements = new ArrayList<>(); - for (Map.Entry entry : actual.entrySet()) { + for (Entry entry : actual.entrySet()) { Optional result = failsRequirements(entryRequirements, entry); if (!result.isPresent()) return; // entry satisfied the requirements unsatisfiedRequirements.add(result.get()); @@ -139,17 +139,17 @@ public void assertNoneSatisfy(AssertionInfo info, Map actual, BiCon requireNonNull(entryRequirements, "The BiConsumer expressing the assertions requirements must not be null"); assertNotNull(info, actual); - List> erroneousEntries = actual.entrySet().stream() - .map(entry -> failsRestrictions(entry, entryRequirements)) - .filter(Optional::isPresent) - .map(Optional::get) - .collect(toList()); + List> erroneousEntries = actual.entrySet().stream() + .map(entry -> failsRestrictions(entry, entryRequirements)) + .filter(Optional::isPresent) + .map(Optional::get) + .collect(toList()); if (erroneousEntries.size() > 0) throw failures.failure(info, noElementsShouldSatisfy(actual, erroneousEntries)); } - private Optional> failsRestrictions(Map.Entry entry, - BiConsumer entryRequirements) { + private Optional> failsRestrictions(Entry entry, + BiConsumer entryRequirements) { try { entryRequirements.accept(entry.getKey(), entry.getValue()); } catch (AssertionError e) { @@ -160,328 +160,135 @@ private Optional> failsRestrictions(Map.Entry entry return Optional.of(entry); } - /** - * Asserts that the given {@code Map} is {@code null} or empty. - * - * @param info contains information about the assertion. - * @param actual the given map. - * @throws AssertionError if the given {@code Map} is not {@code null} *and* contains one or more entries. - */ public void assertNullOrEmpty(AssertionInfo info, Map actual) { if (actual != null && !actual.isEmpty()) throw failures.failure(info, shouldBeNullOrEmpty(actual)); } - /** - * Asserts that the given {@code Map} is empty. - * - * @param info contains information about the assertion. - * @param actual the given {@code Map}. - * @throws AssertionError if the given {@code Map} is {@code null}. - * @throws AssertionError if the given {@code Map} is not empty. - */ public void assertEmpty(AssertionInfo info, Map actual) { assertNotNull(info, actual); if (!actual.isEmpty()) throw failures.failure(info, shouldBeEmpty(actual)); } - /** - * Asserts that the given {@code Map} is not empty. - * - * @param info contains information about the assertion. - * @param actual the given {@code Map}. - * @throws AssertionError if the given {@code Map} is {@code null}. - * @throws AssertionError if the given {@code Map} is empty. - */ public void assertNotEmpty(AssertionInfo info, Map actual) { assertNotNull(info, actual); if (actual.isEmpty()) throw failures.failure(info, shouldNotBeEmpty()); } - /** - * Asserts that the number of entries in the given {@code Map} is equal to the expected one. - * - * @param info contains information about the assertion. - * @param actual the given {@code Map}. - * @param expectedSize the expected size of {@code actual}. - * @throws AssertionError if the given {@code Map} is {@code null}. - * @throws AssertionError if the number of entries in the given {@code Map} is different than the expected one. - */ public void assertHasSize(AssertionInfo info, Map actual, int expectedSize) { assertNotNull(info, actual); checkSizes(actual, actual.size(), expectedSize, info); } - /** - * Asserts that the number of entries in the given {@code Map} is greater than the boundary. - * - * @param info contains information about the assertion. - * @param actual the given {@code Map}. - * @param boundary the given value to compare the size of {@code actual} to. - * @throws AssertionError if the given {@code Map} is {@code null}. - * @throws AssertionError if the number of entries in the given {@code Map} is greater than the boundary. - */ public void assertHasSizeGreaterThan(AssertionInfo info, Map actual, int boundary) { assertNotNull(info, actual); checkSizeGreaterThan(actual, boundary, actual.size(), info); } - /** - * Asserts that the number of entries in the given {@code Map} is greater than or equal to the boundary. - * - * @param info contains information about the assertion. - * @param actual the given {@code Map}. - * @param boundary the given value to compare the size of {@code actual} to. - * @throws AssertionError if the given {@code Map} is {@code null}. - * @throws AssertionError if the number of entries in the given {@code Map} is greater than or equal to the boundary. - */ public void assertHasSizeGreaterThanOrEqualTo(AssertionInfo info, Map actual, int boundary) { assertNotNull(info, actual); checkSizeGreaterThanOrEqualTo(actual, boundary, actual.size(), info); } - /** - * Asserts that the number of entries in the given {@code Map} is less than the boundary. - * - * @param info contains information about the assertion. - * @param actual the given {@code Map}. - * @param boundary the given value to compare the size of {@code actual} to. - * @throws AssertionError if the given {@code Map} is {@code null}. - * @throws AssertionError if the number of entries in the given {@code Map} is less than the expected one. - */ public void assertHasSizeLessThan(AssertionInfo info, Map actual, int boundary) { assertNotNull(info, actual); checkSizeLessThan(actual, boundary, actual.size(), info); } - /** - * Asserts that the number of entries in the given {@code Map} is less than or equal to the boundary. - * - * @param info contains information about the assertion. - * @param actual the given {@code Map}. - * @param boundary the given value to compare the size of {@code actual} to. - * @throws AssertionError if the given {@code Map} is {@code null}. - * @throws AssertionError if the number of entries in the given {@code Map} is less than or equal to the boundary. - */ public void assertHasSizeLessThanOrEqualTo(AssertionInfo info, Map actual, int boundary) { assertNotNull(info, actual); checkSizeLessThanOrEqualTo(actual, boundary, actual.size(), info); } - /** - * Asserts that the number of entries in the given {@code Map} is between the given lower and higher boundary (inclusive). - * - * @param info contains information about the assertion. - * @param actual the given {@code Map}. - * @param lowerBoundary the lower boundary compared to which actual size should be greater than or equal to. - * @param higherBoundary the higher boundary compared to which actual size should be less than or equal to. - * @throws AssertionError if the given array is {@code null}. - * @throws AssertionError if the number of elements in the given array is not between the boundaries. - */ public void assertHasSizeBetween(AssertionInfo info, Map actual, int lowerBoundary, int higherBoundary) { assertNotNull(info, actual); checkSizeBetween(actual, lowerBoundary, higherBoundary, actual.size(), info); } - /** - * Asserts that the number of entries in the given {@code Map} has the same size as the other {@code Iterable}. - * - * @param info contains information about the assertion. - * @param map the given {@code Map}. - * @param other the group to compare - * @throws AssertionError if the given {@code Map} is {@code null}. - * @throws AssertionError if the given {@code Iterable} is {@code null}. - * @throws AssertionError if the number of entries in the given {@code Map} does not have the same size. - */ public void assertHasSameSizeAs(AssertionInfo info, Map map, Iterable other) { assertNotNull(info, map); hasSameSizeAsCheck(info, map, other, map.size()); } - /** - * Asserts that the number of entries in the given {@code Map} has the same size as the other array. - * - * @param info contains information about the assertion. - * @param map the given {@code Map}. - * @param other the group to compare - * @throws AssertionError if the given {@code Map} is {@code null}. - * @throws AssertionError if the given array is {@code null}. - * @throws AssertionError if the number of entries in the given {@code Map} does not have the same size. - */ public void assertHasSameSizeAs(AssertionInfo info, Map map, Object other) { assertNotNull(info, map); assertIsArray(info, other); hasSameSizeAsCheck(info, map, other, map.size()); } - /** - * Asserts that the size of the given {@code Map} is equal to the size of the other {@code Map}. - * - * @param info contains information about the assertion. - * @param map the given {@code Map}. - * @param other the other {@code Map} to compare - * @throws NullPointerException if the other {@code Map} is {@code null}. - * @throws AssertionError if the given {@code Map} is {@code null}. - * @throws AssertionError if the size of the given {@code Map} is not equal to the other {@code Map} size - */ public void assertHasSameSizeAs(AssertionInfo info, Map map, Map other) { assertNotNull(info, map); hasSameSizeAsCheck(info, map, other, map.size()); } - /** - * Asserts that the given {@code Map} contains the given entries, in any order. - * - * @param key type - * @param value type - * @param info contains information about the assertion. - * @param actual the given {@code Map}. - * @param entries the entries that are expected to be in the given {@code Map}. - * @throws NullPointerException if the array of entries is {@code null}. - * @throws IllegalArgumentException if the array of entries is empty. - * @throws NullPointerException if any of the entries in the given array is {@code null}. - * @throws AssertionError if the given {@code Map} is {@code null}. - * @throws AssertionError if the given {@code Map} does not contain the given entries. - */ - public void assertContains(AssertionInfo info, Map actual, - Map.Entry[] entries) { + public void assertContains(AssertionInfo info, Map actual, Entry[] entries) { failIfNull(entries); assertNotNull(info, actual); // if both actual and values are empty, then assertion passes. if (actual.isEmpty() && entries.length == 0) return; - failIfEmptySinceActualIsNotEmpty(entries); - Set> notFound = new LinkedHashSet<>(); - for (Map.Entry entry : entries) { - if (!containsEntry(actual, entry)) notFound.add(entry); - } - if (notFound.isEmpty()) return; - throw failures.failure(info, shouldContain(actual, entries, notFound)); + failIfEntriesIsEmptyEmptySinceActualIsNotEmpty(info, actual, entries); + failIfAnyEntryNotFoundInActualMap(info, actual, entries); + } + + @SuppressWarnings("unchecked") + public void assertContainsAllEntriesOf(AssertionInfo info, Map actual, Map other) { + failIfNull(other); + assertNotNull(info, actual); + // assertion passes if other is empty since actual contains all other entries. + if (other.isEmpty()) return; + failIfAnyEntryNotFoundInActualMap(info, actual, other.entrySet().toArray(new Entry[0])); } - public void assertContainsAnyOf(AssertionInfo info, Map actual, - Map.Entry[] entries) { + public void assertContainsAnyOf(AssertionInfo info, Map actual, Entry[] entries) { failIfNull(entries); assertNotNull(info, actual); // if both actual and values are empty, then assertion passes. if (actual.isEmpty() && entries.length == 0) return; - failIfEmptySinceActualIsNotEmpty(entries); - for (Map.Entry entry : entries) { + failIfEntriesIsEmptyEmptySinceActualIsNotEmpty(info, actual, entries); + for (Entry entry : entries) { if (containsEntry(actual, entry)) return; } - throw failures.failure(info, ShouldContainAnyOf.shouldContainAnyOf(actual, entries)); - } - - /** - * Verifies that the given {@code Map} contains the value for given {@code key} that satisfy given {@code valueCondition}. - * - * @param key type - * @param value type - * @param info contains information about the assertion. - * @param actual the given {@code Map}. - * @param key he given key to check. - * @param valueCondition the given condition for check value. - * @throws NullPointerException if the given values is {@code null}. - * @throws AssertionError if the actual map is {@code null}. - * @throws AssertionError if the actual map not contains the given {@code key}. - * @throws AssertionError if the actual map contains the given key, but value not match the given {@code valueCondition}. - * @since 2.6.0 / 3.6.0 - */ - @SuppressWarnings("unchecked") - public void assertHasEntrySatisfying(AssertionInfo info, Map actual, K key, - Condition valueCondition) { - assertContainsKeys(info, actual, key); + throw failures.failure(info, shouldContainAnyOf(actual, entries)); + } + + public void assertHasEntrySatisfying(AssertionInfo info, Map actual, K key, Condition valueCondition) { + assertContainsKey(info, actual, key); conditions.assertIsNotNull(valueCondition); V value = actual.get(key); if (!valueCondition.matches(value)) throw failures.failure(info, elementsShouldBe(actual, value, valueCondition)); } - /** - * Verifies that the {@code Map} contains the value for given {@code key} that satisfy given {@code valueRequirements}. - * - * @param key type - * @param value type - * @param info contains information about the assertion. - * @param actual the given {@code Map}. - * @param key he given key to check. - * @param valueRequirements the given requirements for check value. - * @throws NullPointerException if the given values is {@code null}. - * @throws AssertionError if the actual map is {@code null}. - * @throws AssertionError if the actual map not contains the given {@code key}. - * @throws AssertionError if the actual map contains the given key, but value not pass the given {@code valueRequirements}. - */ - @SuppressWarnings("unchecked") public void assertHasEntrySatisfying(AssertionInfo info, Map actual, K key, Consumer valueRequirements) { - assertContainsKeys(info, actual, key); + assertContainsKey(info, actual, key); requireNonNull(valueRequirements, "The Consumer expressing the assertions requirements must not be null"); V value = actual.get(key); valueRequirements.accept(value); } - /** - * Verifies that the given {@code Map} contains an entry satisfying given {@code entryCondition}. - * - * @param key type - * @param value type - * @param info contains information about the assertion. - * @param actual the given {@code Map}. - * @param entryCondition the condition for searching entry. - * @throws NullPointerException if the given condition is {@code null}. - * @throws AssertionError if the actual map is {@code null}. - * @throws AssertionError if there is no entry matching given {@code entryCondition}. - * @since 2.7.0 / 3.7.0 - */ public void assertHasEntrySatisfying(AssertionInfo info, Map actual, - Condition> entryCondition) { + Condition> entryCondition) { assertNotNull(info, actual); conditions.assertIsNotNull(entryCondition); - for (Map.Entry entry : actual.entrySet()) { + for (Entry entry : actual.entrySet()) { if (entryCondition.matches(entry)) return; } throw failures.failure(info, shouldContainEntry(actual, entryCondition)); } - /** - * Verifies that the given {@code Map} contains an entry with key satisfying {@code keyCondition} - * and value satisfying {@code valueCondition}. - * - * @param key type - * @param value type - * @param info contains information about the assertion. - * @param actual the given {@code Map}. - * @param keyCondition the condition for entry key. - * @param valueCondition the condition for entry value. - * @throws NullPointerException if any of the given conditions is {@code null}. - * @throws AssertionError if the actual map is {@code null}. - * @throws AssertionError if there is no entry matching given {@code keyCondition} and {@code valueCondition}. - * @since 2.7.0 / 3.7.0 - */ - public void assertHasEntrySatisfyingConditions(AssertionInfo info, Map actual, - Condition keyCondition, + public void assertHasEntrySatisfyingConditions(AssertionInfo info, Map actual, Condition keyCondition, Condition valueCondition) { assertNotNull(info, actual); conditions.assertIsNotNull(keyCondition, "The condition to evaluate for entries key should not be null"); conditions.assertIsNotNull(valueCondition, "The condition to evaluate for entries value should not be null"); - for (Map.Entry entry : actual.entrySet()) { + for (Entry entry : actual.entrySet()) { if (keyCondition.matches(entry.getKey()) && valueCondition.matches(entry.getValue())) return; } throw failures.failure(info, shouldContainEntry(actual, keyCondition, valueCondition)); } - /** - * Verifies that the given {@code Map} contains an entry with key satisfying {@code keyCondition}. - * - * @param key type - * @param info contains information about the assertion. - * @param actual the given {@code Map}. - * @param keyCondition the condition for key search. - * @throws NullPointerException if the given condition is {@code null}. - * @throws AssertionError if the actual map is {@code null}. - * @throws AssertionError if there is no key matching given {@code keyCondition}. - * @since 2.7.0 / 3.7.0 - */ public void assertHasKeySatisfying(AssertionInfo info, Map actual, Condition keyCondition) { assertNotNull(info, actual); conditions.assertIsNotNull(keyCondition); @@ -493,18 +300,6 @@ public void assertHasKeySatisfying(AssertionInfo info, Map actual, Con throw failures.failure(info, shouldContainKey(actual, keyCondition)); } - /** - * Verifies that the given {@code Map} contains an entry with value satisfying {@code valueCondition}. - * - * @param value type - * @param info contains information about the assertion. - * @param actual the given {@code Map}. - * @param valueCondition the condition for value search. - * @throws NullPointerException if the given condition is {@code null}. - * @throws AssertionError if the actual map is {@code null}. - * @throws AssertionError if there is no value matching given {@code valueCondition}. - * @since 2.7.0 / 3.7.0 - */ public void assertHasValueSatisfying(AssertionInfo info, Map actual, Condition valueCondition) { assertNotNull(info, actual); conditions.assertIsNotNull(valueCondition); @@ -516,26 +311,11 @@ public void assertHasValueSatisfying(AssertionInfo info, Map actual, C throw failures.failure(info, shouldContainValue(actual, valueCondition)); } - /** - * Asserts that the given {@code Map} does not contain the given entries. - * - * @param key type - * @param value type - * @param info contains information about the assertion. - * @param actual the given {@code Map}. - * @param entries the entries that are expected to be in the given {@code Map}. - * @throws NullPointerException if the array of entries is {@code null}. - * @throws IllegalArgumentException if the array of entries is empty. - * @throws NullPointerException if any of the entries in the given array is {@code null}. - * @throws AssertionError if the given {@code Map} is {@code null}. - * @throws AssertionError if the given {@code Map} contains any of the given entries. - */ - public void assertDoesNotContain(AssertionInfo info, Map actual, - Map.Entry[] entries) { + public void assertDoesNotContain(AssertionInfo info, Map actual, Entry[] entries) { failIfNullOrEmpty(entries); assertNotNull(info, actual); - Set> found = new LinkedHashSet<>(); - for (Map.Entry entry : entries) { + Set> found = new LinkedHashSet<>(); + for (Entry entry : entries) { if (containsEntry(actual, entry)) { found.add(entry); } @@ -544,157 +324,116 @@ public void assertDoesNotContain(AssertionInfo info, Map actual, throw failures.failure(info, shouldNotContain(actual, entries, found)); } - /** - * Verifies that the actual map contain the given key. - * - * @param key type - * @param value type - * @param info contains information about the assertion. - * @param actual the given {@code Map}. - * @param keys the given keys - * @throws AssertionError if the actual map is {@code null}. - * @throws AssertionError if the actual map not contains the given key. - */ - public void assertContainsKeys(AssertionInfo info, Map actual, - @SuppressWarnings("unchecked") K... keys) { + public void assertContainsKeys(AssertionInfo info, Map actual, K[] keys) { assertNotNull(info, actual); - Set notFound = new LinkedHashSet<>(); - for (K key : keys) { - if (!actual.containsKey(key)) { - notFound.add(key); - } - } + Set notFound = getNotFoundKeys(actual, keys); if (notFound.isEmpty()) return; throw failures.failure(info, shouldContainKeys(actual, notFound)); } - /** - * Verifies that the actual map not contains the given key. - * - * @param key type - * @param value type - * @param info contains information about the assertion. - * @param actual the given {@code Map}. - * @param key the given key - * @throws AssertionError if the actual map is {@code null}. - * @throws AssertionError if the actual map contains the given key. - */ + public void assertContainsKey(AssertionInfo info, Map actual, K key) { + assertContainsKeys(info, actual, array(key)); + } + public void assertDoesNotContainKey(AssertionInfo info, Map actual, K key) { assertNotNull(info, actual); if (actual.containsKey(key)) throw failures.failure(info, shouldNotContainKey(actual, key)); } - /** - * Verifies that the actual map not contains all the given keys. - * - * @param key type - * @param value type - * @param info contains information about the assertion. - * @param actual the given {@code Map}. - * @param keys the given keys - * @throws AssertionError if the actual map is {@code null}. - * @throws AssertionError if the actual map contains all the given keys. - */ - public void assertDoesNotContainKeys(AssertionInfo info, Map actual, - @SuppressWarnings("unchecked") K... keys) { + public void assertDoesNotContainKeys(AssertionInfo info, Map actual, K[] keys) { assertNotNull(info, actual); - Set found = new LinkedHashSet<>(); - for (K key : keys) { - if (key != null && actual.containsKey(key)) { - found.add(key); - } - } + requireNonNull(keys, keysToLookForIsNull("array of keys")); + Set found = getFoundKeys(actual, keys); if (!found.isEmpty()) throw failures.failure(info, shouldNotContainKeys(actual, found)); } - /** - * Verifies that the actual map contains only the given keys and nothing else, in any order. - * - * @param key type - * @param value type - * @param info contains information about the assertion. - * @param actual the given {@code Map}. - * @param keys the keys that are expected to be in the given {@code Map}. - * @throws NullPointerException if the array of keys is {@code null}. - * @throws IllegalArgumentException if the array of keys is empty. - * @throws AssertionError if the given {@code Map} is {@code null}. - * @throws AssertionError if the given {@code Map} does not contain the given keys or if the given {@code Map} - * contains keys that are not in the given array. - */ - public void assertContainsOnlyKeys(AssertionInfo info, Map actual, - @SuppressWarnings("unchecked") K... keys) { + public void assertContainsOnlyKeys(AssertionInfo info, Map actual, K[] keys) { assertContainsOnlyKeys(info, actual, "array of keys", keys); } - /** - * Verifies that the actual map contains only the given keys and nothing else, in any order. - * - * @param key type - * @param value type - * @param info contains information about the assertion. - * @param actual the given {@code Map}. - * @param keys the keys that are expected to be in the given {@code Map}. - * @throws NullPointerException if the array of keys is {@code null}. - * @throws IllegalArgumentException if the array of keys is empty. - * @throws AssertionError if the given {@code Map} is {@code null}. - * @throws AssertionError if the given {@code Map} does not contain the given keys or if the given {@code Map} - * contains keys that are not in the given array. - */ - public void assertContainsOnlyKeys(AssertionInfo info, Map actual, - Iterable keys) { + public void assertContainsOnlyKeys(AssertionInfo info, Map actual, Iterable keys) { final K[] keysAsArray = toArray(keys); assertContainsOnlyKeys(info, actual, "keys iterable", keysAsArray); } - @VisibleForTesting - public void assertContainsOnlyKeys(AssertionInfo info, Map actual, - String placeholderForErrorMessages, K[] keys) { + private void assertContainsOnlyKeys(AssertionInfo info, Map actual, String placeholderForErrorMessages, K[] keys) { assertNotNull(info, actual); - failIfNull(keys, keysToLookForIsNull(placeholderForErrorMessages)); + requireNonNull(keys, keysToLookForIsNull(placeholderForErrorMessages)); if (actual.isEmpty() && keys.length == 0) { return; } failIfEmpty(keys, keysToLookForIsEmpty(placeholderForErrorMessages)); - Set notFound = new LinkedHashSet<>(); - Set notExpected = new LinkedHashSet<>(); - - compareActualMapAndExpectedKeys(actual, keys, notExpected, notFound); + Set notFound = getNotFoundKeys(actual, keys); + Set notExpected = getNotExpectedKeys(actual, keys); if (!notFound.isEmpty() || !notExpected.isEmpty()) throw failures.failure(info, shouldContainOnlyKeys(actual, keys, notFound, notExpected)); } - /** - * Verifies that the actual map contain the given value. - * - * @param key type - * @param value type - * @param info contains information about the assertion. - * @param actual the given {@code Map}. - * @param value the given value - * @throws AssertionError if the actual map is {@code null}. - * @throws AssertionError if the actual map not contains the given value. - */ + private static Set getFoundKeys(Map actual, K[] expectedKeys) { + // Stream API avoided for performance reasons + Set found = new LinkedHashSet<>(); + for (K expectedKey : expectedKeys) { + if (actual.containsKey(expectedKey)) found.add(expectedKey); + } + return found; + } + + private static Set getNotFoundKeys(Map actual, K[] expectedKeys) { + // Stream API avoided for performance reasons + Set notFound = new LinkedHashSet<>(); + for (K expectedKey : expectedKeys) { + if (!actual.containsKey(expectedKey)) notFound.add(expectedKey); + } + return notFound; + } + + private static Set getNotExpectedKeys(Map actual, K[] expectedKeys) { + // Stream API avoided for performance reasons + try { + Map clonedMap = clone(actual); + for (K expectedKey : expectedKeys) { + clonedMap.remove(expectedKey); + } + return clonedMap.keySet(); + } catch (NoSuchMethodException | UnsupportedOperationException e) { + // actual cannot be cloned or is unmodifiable, falling back to LinkedHashMap + Map copiedMap = new LinkedHashMap<>(actual); + for (K expectedKey : expectedKeys) { + copiedMap.remove(expectedKey); + } + return copiedMap.keySet(); + } + } + + @SuppressWarnings("unchecked") + private static Map clone(Map map) throws NoSuchMethodException { + try { + if (map instanceof Cloneable) { + return (Map) map.getClass().getMethod("clone").invoke(map); + } + + try { + // try with copying constructor + return map.getClass().getConstructor(Map.class).newInstance(map); + } catch (NoSuchMethodException e) { + // try with default constructor + Map newMap = map.getClass().getConstructor().newInstance(); + newMap.putAll(map); + return newMap; + } + } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) { + throw new IllegalStateException(e); + } + } + public void assertContainsValue(AssertionInfo info, Map actual, V value) { assertNotNull(info, actual); if (!actual.containsValue(value)) throw failures.failure(info, shouldContainValue(actual, value)); } - /** - * Verifies that the actual map contain the given values. - * - * @param key type - * @param value type - * @param info contains information about the assertion. - * @param actual the given {@code Map}. - * @param values the given values - * @throws AssertionError if the actual map is {@code null}. - * @throws AssertionError if the actual map not contains the given values. - * @throws NullPointerException if values vararg is {@code null}. - */ - public void assertContainsValues(AssertionInfo info, Map actual, - @SuppressWarnings("unchecked") V... values) { + public void assertContainsValues(AssertionInfo info, Map actual, V[] values) { assertNotNull(info, actual); requireNonNull(values, "The array of values to look for should not be null"); if (actual.isEmpty() && values.length == 0) return; @@ -706,79 +445,69 @@ public void assertContainsValues(AssertionInfo info, Map actual, if (!valuesNotFound.isEmpty()) throw failures.failure(info, shouldContainValues(actual, valuesNotFound)); } - /** - * Verifies that the actual map not contains the given value. - * - * @param key type - * @param value type - * @param info contains information about the assertion. - * @param actual the given {@code Map}. - * @param value the given value - * @throws AssertionError if the actual map is {@code null}. - * @throws AssertionError if the actual map contains the given value. - */ public void assertDoesNotContainValue(AssertionInfo info, Map actual, V value) { assertNotNull(info, actual); if (actual.containsValue(value)) throw failures.failure(info, shouldNotContainValue(actual, value)); } - /** - * Verifies that the actual map contains only the given entries and nothing else, in any order. - * - * @param key type - * @param value type - * @param info contains information about the assertion. - * @param actual the given {@code Map}. - * @param entries the entries that should be in the actual map. - * @throws AssertionError if the actual map is {@code null}. - * @throws NullPointerException if the given entries array is {@code null}. - * @throws IllegalArgumentException if the given entries array is empty. - * @throws AssertionError if the actual map does not contain the given entries, i.e. the actual map contains some or - * none of the given entries, or the actual map contains more entries than the given ones. - */ - public void assertContainsOnly(AssertionInfo info, Map actual, - @SuppressWarnings("unchecked") Map.Entry... entries) { + public void assertContainsOnly(AssertionInfo info, Map actual, Entry[] entries) { doCommonContainsCheck(info, actual, entries); - if (actual.isEmpty() && entries.length == 0) { - return; - } - failIfEmpty(entries); - - Set> notFound = new LinkedHashSet<>(); - Set> notExpected = new LinkedHashSet<>(); + if (actual.isEmpty() && entries.length == 0) return; + failIfEntriesIsEmptyEmptySinceActualIsNotEmpty(info, actual, entries); - compareActualMapAndExpectedEntries(actual, entries, notExpected, notFound); + Set> notFound = getNotFoundEntries(actual, entries); + Set> notExpected = getNotExpectedEntries(actual, entries); - if (!notFound.isEmpty() || !notExpected.isEmpty()) + if (!(notFound.isEmpty() && notExpected.isEmpty())) throw failures.failure(info, shouldContainOnly(actual, entries, notFound, notExpected)); } - /** - * Verifies that the actual map contains only the given entries and nothing else, in order.
    - * This assertion should only be used with map that have a consistent iteration order (i.e. don't use it with - * {@link java.util.HashMap}). - * - * @param key type - * @param value type - * @param info contains information about the assertion. - * @param actual the given {@code Map}. - * @param entries the given entries. - * @throws NullPointerException if the given entries array is {@code null}. - * @throws AssertionError if the actual map is {@code null}. - * @throws IllegalArgumentException if the given entries array is empty. - * @throws AssertionError if the actual map does not contain the given entries with same order, i.e. the actual map - * contains some or none of the given entries, or the actual map contains more entries than the given ones - * or entries are the same but the order is not. - */ - public void assertContainsExactly(AssertionInfo info, Map actual, - @SuppressWarnings("unchecked") Map.Entry... entries) { + private static Set> getNotFoundEntries(Map actual, + Entry[] entries) { + // Stream API avoided for performance reasons + Set> notFound = new LinkedHashSet<>(); + for (Entry entry : entries) { + if (!containsEntry(actual, entry)) notFound.add(entry); + } + return notFound; + } + + private static Set> getNotExpectedEntries(Map actual, Entry[] entries) { + // Stream API avoided for performance reasons + Set> notExpected = new LinkedHashSet<>(); + for (Entry entry : mapWithoutExpectedEntries(actual, entries).entrySet()) { + MapEntry mapEntry = entry(entry.getKey(), entry.getValue()); + notExpected.add(mapEntry); + } + return notExpected; + } + + private static Map mapWithoutExpectedEntries(Map actual, Entry[] expectedEntries) { + // Stream API avoided for performance reasons + try { + Map clonedMap = clone(actual); + for (Entry expectedEntry : expectedEntries) { + clonedMap.remove(expectedEntry.getKey(), expectedEntry.getValue()); + } + return clonedMap; + } catch (NoSuchMethodException | UnsupportedOperationException e) { + // actual cannot be cloned or is unmodifiable, falling back to LinkedHashMap + Map copiedMap = new LinkedHashMap<>(actual); + for (Entry expectedEntry : expectedEntries) { + copiedMap.remove(expectedEntry.getKey(), expectedEntry.getValue()); + } + return copiedMap; + } + } + + public void assertContainsExactly(AssertionInfo info, Map actual, Entry[] entries) { doCommonContainsCheck(info, actual, entries); if (actual.isEmpty() && entries.length == 0) return; - failIfEmpty(entries); + failIfEntriesIsEmptyEmptySinceActualIsNotEmpty(info, actual, entries); assertHasSameSizeAs(info, actual, entries); - Set> notFound = new LinkedHashSet<>(); - Set> notExpected = new LinkedHashSet<>(); + Set> notFound = new LinkedHashSet<>(); + Set> notExpected = new LinkedHashSet<>(); compareActualMapAndExpectedEntries(actual, entries, notExpected, notFound); @@ -787,7 +516,7 @@ public void assertContainsExactly(AssertionInfo info, Map actual, int index = 0; for (K keyFromActual : actual.keySet()) { if (!areEqual(keyFromActual, entries[index].getKey())) { - Map.Entry actualEntry = entry(keyFromActual, actual.get(keyFromActual)); + Entry actualEntry = entry(keyFromActual, actual.get(keyFromActual)); throw failures.failure(info, elementsDifferAtIndex(actualEntry, entries[index], index)); } index++; @@ -799,30 +528,12 @@ public void assertContainsExactly(AssertionInfo info, Map actual, throw failures.failure(info, shouldContainExactly(actual, asList(entries), notFound, notExpected)); } - private void compareActualMapAndExpectedKeys(Map actual, K[] keys, Set notExpected, - Set notFound) { - - Map actualEntries = new LinkedHashMap<>(actual); - for (K key : keys) { - if (actualEntries.containsKey(key)) { - // this is an expected key - actualEntries.remove(key); - } else { - // this is a not found key - notFound.add(key); - } - } - // All remaining keys from actual copy are not expected entries. - notExpected.addAll(actualEntries.keySet()); - } - - private void compareActualMapAndExpectedEntries(Map actual, - Map.Entry[] entries, - Set> notExpected, - Set> notFound) { + private void compareActualMapAndExpectedEntries(Map actual, Entry[] entries, + Set> notExpected, + Set> notFound) { Map expectedEntries = entriesToMap(entries); Map actualEntries = new LinkedHashMap<>(actual); - for (Map.Entry entry : expectedEntries.entrySet()) { + for (Entry entry : expectedEntries.entrySet()) { if (containsEntry(actualEntries, entry(entry.getKey(), entry.getValue()))) { // this is an expected entry actualEntries.remove(entry.getKey()); @@ -832,20 +543,28 @@ private void compareActualMapAndExpectedEntries(Map actual, } } // All remaining entries from actual copy are not expected entries. - for (Map.Entry entry : actualEntries.entrySet()) { + for (Entry entry : actualEntries.entrySet()) { notExpected.add(entry(entry.getKey(), entry.getValue())); } } - private void doCommonContainsCheck(AssertionInfo info, Map actual, - Map.Entry[] entries) { + private void doCommonContainsCheck(AssertionInfo info, Map actual, Entry[] entries) { assertNotNull(info, actual); failIfNull(entries); } - private static Map entriesToMap(Map.Entry[] entries) { + private void failIfAnyEntryNotFoundInActualMap(AssertionInfo info, Map actual, + Entry[] entries) { + Set> notFound = new LinkedHashSet<>(); + for (Entry entry : entries) { + if (!containsEntry(actual, entry)) notFound.add(entry); + } + if (!notFound.isEmpty()) throw failures.failure(info, shouldContain(actual, entries, notFound)); + } + + private static Map entriesToMap(Entry[] entries) { Map expectedEntries = new LinkedHashMap<>(); - for (Map.Entry entry : entries) { + for (Entry entry : entries) { expectedEntries.put(entry.getKey(), entry.getValue()); } return expectedEntries; @@ -855,34 +574,36 @@ private static void failIfEmpty(K[] keys, String errorMessage) { checkArgument(keys.length > 0, errorMessage); } - private static void failIfEmpty(Map.Entry[] entries) { + private static void failIfEmpty(Entry[] entries) { checkArgument(entries.length > 0, "The array of entries to look for should not be empty"); } - private static void failIfNullOrEmpty(Map.Entry[] entries) { + private static void failIfNullOrEmpty(Entry[] entries) { failIfNull(entries); failIfEmpty(entries); } - private static void failIfNull(K[] keys, String errorMessage) { - requireNonNull(keys, errorMessage); + private static void failIfNull(Entry[] entries) { + requireNonNull(entries, ErrorMessages.entriesToLookForIsNull()); } - private static void failIfNull(Map.Entry[] entries) { - requireNonNull(entries, ErrorMessages.entriesToLookForIsNull()); + private static void failIfNull(Map map) { + requireNonNull(map, ErrorMessages.mapOfEntriesToLookForIsNull()); } - private boolean containsEntry(Map actual, Map.Entry entry) { - requireNonNull(entry, "Entries to look for should not be null"); - return actual.containsKey(entry.getKey()) && areEqual(actual.get(entry.getKey()), entry.getValue()); + private static boolean containsEntry(Map actual, Entry entry) { + requireNonNull(entry, ErrorMessages.entryToLookForIsNull()); + return actual.containsKey(entry.getKey()) && deepEquals(actual.get(entry.getKey()), entry.getValue()); } private void assertNotNull(AssertionInfo info, Map actual) { Objects.instance().assertNotNull(info, actual); } - private static void failIfEmptySinceActualIsNotEmpty(Map.Entry[] values) { - if (values.length == 0) throw new AssertionError("actual is not empty"); + // this should be only called when actual is not empty + private void failIfEntriesIsEmptyEmptySinceActualIsNotEmpty(AssertionInfo info, Map actual, + Entry[] entries) { + if (entries.length == 0) throw failures.failure(info, shouldBeEmpty(actual)); } } diff --git a/src/main/java/org/assertj/core/internal/ObjectArrayElementComparisonStrategy.java b/src/main/java/org/assertj/core/internal/ObjectArrayElementComparisonStrategy.java index d6e5cfe74ee..0b47399970a 100644 --- a/src/main/java/org/assertj/core/internal/ObjectArrayElementComparisonStrategy.java +++ b/src/main/java/org/assertj/core/internal/ObjectArrayElementComparisonStrategy.java @@ -19,7 +19,7 @@ public class ObjectArrayElementComparisonStrategy extends StandardComparisonStrategy { - private Comparator elementComparator; + private final Comparator elementComparator; public ObjectArrayElementComparisonStrategy(Comparator elementComparator) { this.elementComparator = elementComparator; diff --git a/src/main/java/org/assertj/core/internal/ObjectArrays.java b/src/main/java/org/assertj/core/internal/ObjectArrays.java index e10166acec2..cf7fc696639 100644 --- a/src/main/java/org/assertj/core/internal/ObjectArrays.java +++ b/src/main/java/org/assertj/core/internal/ObjectArrays.java @@ -12,23 +12,33 @@ */ package org.assertj.core.internal; -import org.assertj.core.api.ArraySortedAssert; -import org.assertj.core.api.AssertionInfo; -import org.assertj.core.api.Condition; -import org.assertj.core.data.Index; -import org.assertj.core.util.VisibleForTesting; - -import java.util.*; - +import static java.util.stream.Collectors.toList; import static org.assertj.core.error.ShouldHaveAtLeastOneElementOfType.shouldHaveAtLeastOneElementOfType; +import static org.assertj.core.error.ShouldHaveExactlyTypes.elementsTypesDifferAtIndex; +import static org.assertj.core.error.ShouldHaveExactlyTypes.shouldHaveTypes; import static org.assertj.core.error.ShouldHaveOnlyElementsOfType.shouldHaveOnlyElementsOfType; import static org.assertj.core.error.ShouldNotHaveAnyElementsOfTypes.shouldNotHaveAnyElementsOfTypes; import static org.assertj.core.internal.CommonValidations.checkIsNotNullAndNotEmpty; +import static org.assertj.core.internal.IterableDiff.diff; +import static org.assertj.core.util.Lists.list; import static org.assertj.core.util.Lists.newArrayList; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +import org.assertj.core.api.ArraySortedAssert; +import org.assertj.core.api.AssertionInfo; +import org.assertj.core.api.Condition; +import org.assertj.core.data.Index; +import org.assertj.core.util.VisibleForTesting; + /** * Reusable assertions for arrays of objects. - * + * * @author Alex Ruiz * @author Joel Costigliola * @author Nicolas François @@ -40,7 +50,7 @@ public class ObjectArrays { /** * Returns the singleton instance of this class. - * + * * @return the singleton instance of this class. */ public static ObjectArrays instance() { @@ -81,7 +91,7 @@ public ComparisonStrategy getComparisonStrategy() { /** * Asserts that the given array is {@code null} or empty. - * + * * @param info contains information about the assertion. * @param actual the given array. * @throws AssertionError if the given array is not {@code null} *and* contains one or more elements. @@ -92,7 +102,7 @@ public void assertNullOrEmpty(AssertionInfo info, Object[] actual) { /** * Asserts that the given array is empty. - * + * * @param info contains information about the assertion. * @param actual the given array. * @throws AssertionError if the given array is {@code null}. @@ -104,7 +114,7 @@ public void assertEmpty(AssertionInfo info, Object[] actual) { /** * Asserts that the given array is not empty. - * + * * @param info contains information about the assertion. * @param actual the given array. * @throws AssertionError if the given array is {@code null}. @@ -116,7 +126,7 @@ public void assertNotEmpty(AssertionInfo info, Object[] actual) { /** * Asserts that the number of elements in the given array is equal to the expected one. - * + * * @param info contains information about the assertion. * @param actual the given array. * @param expectedSize the expected size of {@code actual}. @@ -195,7 +205,7 @@ public void assertHasSizeBetween(AssertionInfo info, Object[] actual, int lowerB /** * Assert that the actual array has the same size as the other {@code Iterable}. - * + * * @param info contains information about the assertion. * @param actual the given iterable. * @param other the group to compare @@ -209,7 +219,7 @@ public void assertHasSameSizeAs(AssertionInfo info, Object[] actual, Iterable /** * Assert that the actual array has the same size as the other array. - * + * * @param info contains information about the assertion. * @param actual the given array. * @param other the group to compare @@ -223,7 +233,7 @@ public void assertHasSameSizeAs(AssertionInfo info, Object[] actual, Object othe /** * Asserts that the given array contains the given values, in any order. - * + * * @param info contains information about the assertion. * @param actual the given array. * @param values the values that are expected to be in the given array. @@ -238,7 +248,7 @@ public void assertContains(AssertionInfo info, Object[] actual, Object[] values) /** * Verifies that the given array contains the given object at the given index. - * + * * @param info contains information about the assertion. * @param actual the given array. * @param value the object to look for. @@ -255,7 +265,7 @@ public void assertContains(AssertionInfo info, Object[] actual, Object value, In /** * Verifies that the given array does not contain the given object at the given index. - * + * * @param info contains information about the assertion. * @param actual the given array. * @param value the object to look for. @@ -270,7 +280,7 @@ public void assertDoesNotContain(AssertionInfo info, Object[] actual, Object val /** * Asserts that the given array contains only the given values and nothing else, in any order. - * + * * @param info contains information about the assertion. * @param actual the given array. * @param values the values that are expected to be in the given array. @@ -294,7 +304,7 @@ public void assertContainsExactlyInAnyOrder(AssertionInfo info, Object[] actual, /** * Asserts that the given array contains only once the given values. - * + * * @param info contains information about the assertion. * @param actual the given array. * @param values the values that are expected to be in the given array. @@ -323,7 +333,7 @@ public void assertContainsOnlyNulls(AssertionInfo info, Object[] actual) { /** * Verifies that the given array contains the given sequence of objects, without any other objects between them. - * + * * @param info contains information about the assertion. * @param actual the given array. * @param sequence the sequence of objects to look for. @@ -353,7 +363,7 @@ public void assertDoesNotContainSequence(AssertionInfo info, Object[] actual, Ob /** * Verifies that the given array contains the given subsequence of objects (possibly with other values between them). - * + * * @param info contains information about the assertion. * @param actual the given array. * @param subsequence the subsequence of objects to look for. @@ -384,7 +394,7 @@ public void assertDoesNotContainSubsequence(AssertionInfo info, Object[] actual, /** * Asserts that the given array does not contain the given values. - * + * * @param info contains information about the assertion. * @param actual the given array. * @param values the values that are expected not to be in the given array. @@ -406,7 +416,7 @@ public void assertDoesNotContainAnyElementsOf(AssertionInfo info, Object[] a /** * Asserts that the given array does not have duplicate values. - * + * * @param info contains information about the assertion. * @param actual the given array. * @throws NullPointerException if the array of values is {@code null}. @@ -422,7 +432,7 @@ public void assertDoesNotHaveDuplicates(AssertionInfo info, Object[] actual) { * Verifies that the given array starts with the given sequence of objects, without any other objects between them. * Similar to {@link #assertContainsSequence(AssertionInfo, Object[], Object[])}, but it also verifies * that the first element in the sequence is also the first element of the given array. - * + * * @param info contains information about the assertion. * @param actual the given array. * @param sequence the sequence of objects to look for. @@ -474,7 +484,7 @@ public void assertIsSubsetOf(AssertionInfo info, Object actual, Iterable valu /** * Asserts that the given array contains at least a null element. - * + * * @param info contains information about the assertion. * @param actual the given array. * @throws AssertionError if the given array is {@code null}. @@ -486,7 +496,7 @@ public void assertContainsNull(AssertionInfo info, Object[] actual) { /** * Asserts that the given array does not contain null elements. - * + * * @param info contains information about the assertion. * @param actual the given array. * @throws AssertionError if the given array is {@code null}. @@ -498,7 +508,7 @@ public void assertDoesNotContainNull(AssertionInfo info, Object[] actual) { /** * Assert that each element of given array satisfies the given condition. - * + * * @param element type * @param info contains information about the assertion. * @param actual the given array. @@ -512,7 +522,7 @@ public void assertAre(AssertionInfo info, E[] actual, Condition c /** * Assert that each element of given array not satisfies the given condition. - * + * * @param element type * @param info contains information about the assertion. * @param actual the given array. @@ -526,7 +536,7 @@ public void assertAreNot(AssertionInfo info, E[] actual, Condition element type * @param info contains information about the assertion. * @param actual the given array. @@ -540,7 +550,7 @@ public void assertHave(AssertionInfo info, E[] actual, Condition /** * Assert that each element of given array not satisfies the given condition. - * + * * @param element type * @param info contains information about the assertion. * @param actual the given array. @@ -554,7 +564,7 @@ public void assertDoNotHave(AssertionInfo info, E[] actual, Conditionat least n array elements satisfying the given condition. - * + * * @param element type * @param info contains information about the assertion. * @param actual the given array. @@ -569,7 +579,7 @@ public void assertAreAtLeast(AssertionInfo info, E[] actual, int n, Conditio /** * Assert that there are at most n array elements satisfying the given condition. - * + * * @param element type * @param info contains information about the assertion. * @param actual the given array. @@ -584,7 +594,7 @@ public void assertAreAtMost(AssertionInfo info, E[] actual, int n, Condition /** * Verifies that there are exactly n array elements satisfying the given condition. - * + * * @param element type * @param info contains information about the assertion. * @param actual the given array. @@ -600,7 +610,7 @@ public void assertAreExactly(AssertionInfo info, E[] actual, int n, Conditio /** * An alias method of {@link #assertAreAtLeast(AssertionInfo, Object[], int, Condition)} to provide a richer fluent * api (same logic, only error message differs). - * + * * @param element type * @param info contains information about the assertion. * @param actual the given array. @@ -616,7 +626,7 @@ public void assertHaveAtLeast(AssertionInfo info, E[] actual, int times, Con /** * An alias method of {@link #assertAreAtMost(AssertionInfo, Object[], int, Condition)} to provide a richer fluent api * (same logic, only error message differs). - * + * * @param element type * @param info contains information about the assertion. * @param actual the given array. @@ -632,7 +642,7 @@ public void assertHaveAtMost(AssertionInfo info, E[] actual, int times, Cond /** * An alias method of {@link #assertAreExactly(AssertionInfo, Object[], int, Condition)} to provide a richer fluent * api (same logic, only error message differs). - * + * * @param element type * @param info contains information about the assertion. * @param actual the given array. @@ -669,6 +679,23 @@ public void assertHasOnlyElementsOfTypes(AssertionInfo info, E[] actual, Cla arrays.assertHasOnlyElementsOfTypes(info, failures, actual, types); } + public void assertHasExactlyElementsOfTypes(AssertionInfo info, E[] actual, Class... expectedTypes) { + Objects.instance().assertNotNull(info, actual); + List> actualTypeList = Stream.of(actual).map(Object::getClass).collect(toList()); + IterableDiff> typesDiff = diff(actualTypeList, list(expectedTypes)); + if (typesDiff.differencesFound()) { + throw failures.failure(info, shouldHaveTypes(actual, list(expectedTypes), typesDiff.missing, typesDiff.unexpected)); + } + // actual elements have the expected types but are they in the correct order? + int i = 0; + for (E actualElement : actual) { + if (!java.util.Objects.equals(actualElement.getClass(), expectedTypes[i])) { + throw failures.failure(info, elementsTypesDifferAtIndex(actualElement, expectedTypes[i], i)); + } + i++; + } + } + public void assertDoesNotHaveAnyElementsOfTypes(AssertionInfo info, E[] actual, Class... unexpectedTypes) { Objects.instance().assertNotNull(info, actual); Map, List> nonMatchingElementsByType = new LinkedHashMap<>(); @@ -689,7 +716,7 @@ public void assertDoesNotHaveAnyElementsOfTypes(AssertionInfo info, E[] actu /** * Concrete implementation of {@link ArraySortedAssert#isSorted()}. - * + * * @param info contains information about the assertion. * @param actual the given array. */ @@ -699,7 +726,7 @@ public void assertIsSorted(AssertionInfo info, Object[] actual) { /** * Concrete implementation of {@link ArraySortedAssert#isSortedAccordingTo(Comparator)}. - * + * * @param element type * @param info contains information about the assertion. * @param actual the given array. @@ -712,7 +739,7 @@ public void assertIsSortedAccordingToComparator(AssertionInfo info, E[] actu /** * Asserts that the given array contains all the elements of the given {@code Iterable}, in any order. - * + * * @param element type * @param info contains information about the assertion. * @param actual the given array. diff --git a/src/main/java/org/assertj/core/internal/Objects.java b/src/main/java/org/assertj/core/internal/Objects.java index 9f755d73ef6..5aaed209011 100644 --- a/src/main/java/org/assertj/core/internal/Objects.java +++ b/src/main/java/org/assertj/core/internal/Objects.java @@ -13,6 +13,7 @@ package org.assertj.core.internal; import static java.lang.String.format; +import static java.lang.reflect.Modifier.isStatic; import static java.util.Arrays.asList; import static java.util.Arrays.stream; import static java.util.Objects.deepEquals; @@ -880,9 +881,12 @@ public void assertHasOnlyFields(AssertionInfo info, A actual, String... name assertNotNull(info, actual); checkArgument(names != null, "Given fields/properties are null"); List expectedFields = stream(names).sorted().collect(toList()); - List actualFields = stream(actual.getClass().getDeclaredFields()).map(Field::getName) - .sorted() - .collect(toList()); + Field[] declaredFields = actual.getClass().getDeclaredFields(); + List actualFields = stream(declaredFields).filter(field -> !isStatic(field.getModifiers())) + .filter(field -> !field.isSynthetic()) + .map(Field::getName) + .sorted() + .collect(toList()); if (!expectedFields.equals(actualFields)) { List fieldsNotFound = stream(names).filter(name -> !actualFields.contains(name)).collect(toList()); List extraFields = actualFields.stream() diff --git a/src/main/java/org/assertj/core/internal/OnFieldsComparator.java b/src/main/java/org/assertj/core/internal/OnFieldsComparator.java index 987f4ecfe80..35dac745071 100644 --- a/src/main/java/org/assertj/core/internal/OnFieldsComparator.java +++ b/src/main/java/org/assertj/core/internal/OnFieldsComparator.java @@ -22,9 +22,19 @@ import java.util.HashMap; import java.util.Map; +import org.assertj.core.api.AbstractIterableAssert; +import org.assertj.core.api.AbstractObjectAssert; +import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration; import org.assertj.core.util.VisibleForTesting; import org.assertj.core.util.introspection.IntrospectionError; +/** + * @deprecated + * This comparator is deprecated because it performs a shallow field by field comparison, i.e. elements are compared + * field by field but the fields are compared with equals, use {@link AbstractIterableAssert#usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration)} + * or {@link AbstractObjectAssert#usingRecursiveComparison()} instead to perform a true recursive comparison. + */ +@Deprecated public class OnFieldsComparator extends FieldByFieldComparator { private final String[] fields; diff --git a/src/main/java/org/assertj/core/internal/RealNumbers.java b/src/main/java/org/assertj/core/internal/RealNumbers.java index 137e09c2abb..48a201da4ad 100644 --- a/src/main/java/org/assertj/core/internal/RealNumbers.java +++ b/src/main/java/org/assertj/core/internal/RealNumbers.java @@ -14,6 +14,8 @@ import static org.assertj.core.error.ShouldBeFinite.shouldBeFinite; import static org.assertj.core.error.ShouldBeInfinite.shouldBeInfinite; +import static org.assertj.core.error.ShouldNotBeFinite.shouldNotBeFinite; +import static org.assertj.core.error.ShouldNotBeInfinite.shouldNotBeInfinite; import org.assertj.core.api.AssertionInfo; @@ -69,6 +71,14 @@ public void assertIsFinite(AssertionInfo info, NUMBER actual) { protected abstract boolean isFinite(NUMBER value); + public void assertIsNotFinite(AssertionInfo info, NUMBER actual) { + assertNotNull(info, actual); + if (isNotFinite(actual)) return; + throw failures.failure(info, shouldNotBeFinite(actual)); + } + + protected abstract boolean isNotFinite(NUMBER value); + public void assertIsInfinite(AssertionInfo info, NUMBER actual) { assertNotNull(info, actual); if (isInfinite(actual)) return; @@ -76,4 +86,12 @@ public void assertIsInfinite(AssertionInfo info, NUMBER actual) { } protected abstract boolean isInfinite(NUMBER value); + + public void assertIsNotInfinite(AssertionInfo info, NUMBER actual) { + assertNotNull(info, actual); + if (isNotInfinite(actual)) return; + throw failures.failure(info, shouldNotBeInfinite(actual)); + } + + protected abstract boolean isNotInfinite(NUMBER value); } diff --git a/src/main/java/org/assertj/core/internal/RecursiveFieldByFieldComparator.java b/src/main/java/org/assertj/core/internal/RecursiveFieldByFieldComparator.java deleted file mode 100644 index d8547329008..00000000000 --- a/src/main/java/org/assertj/core/internal/RecursiveFieldByFieldComparator.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - * Copyright 2012-2021 the original author or authors. - */ -package org.assertj.core.internal; - -import static org.assertj.core.internal.DeepDifference.determineDifferences; - -import java.util.Comparator; -import java.util.Map; - -import org.assertj.core.util.introspection.IntrospectionError; - -/** - * Compares objects field/property by field/property recursively. - */ -public class RecursiveFieldByFieldComparator extends FieldByFieldComparator { - - public RecursiveFieldByFieldComparator(Map> comparatorByPropertyOrField, - TypeComparators comparatorByType) { - super(comparatorByPropertyOrField, comparatorByType); - } - - @Override - protected boolean areEqual(Object actual, Object other) { - try { - return determineDifferences(actual, other, comparatorsByPropertyOrField, comparatorsByType).isEmpty(); - } catch (IntrospectionError e) { - return false; - } - } - - @Override - protected String description() { - return "recursive field/property by field/property comparator on all fields/properties"; - } -} diff --git a/src/main/java/org/assertj/core/internal/StandardComparisonStrategy.java b/src/main/java/org/assertj/core/internal/StandardComparisonStrategy.java index b049427c2fa..a66368c213b 100644 --- a/src/main/java/org/assertj/core/internal/StandardComparisonStrategy.java +++ b/src/main/java/org/assertj/core/internal/StandardComparisonStrategy.java @@ -66,15 +66,51 @@ public String asText() { } /** - * Returns true if actual and other are equal based on {@link java.util.Objects#deepEquals(Object, Object)}, false otherwise. + * Returns {@code true} if the arguments are deeply equal to each other, {@code false} otherwise. + *

    + * It mimics the behavior of {@link java.util.Objects#deepEquals(Object, Object)}, but without performing a reference + * check between the two arguments. According to {@code deepEquals} javadoc, the reference check should be delegated + * to the {@link Object#equals equals} method of the first argument, but this is not happening. Bug JDK-8196069 also + * mentions this gap. + * + * @param actual the object to compare to {@code other} + * @param other the object to compare to {@code actual} + * @return {@code true} if the arguments are deeply equal to each other, {@code false} otherwise + * + * @see JDK-8196069 * - * @param actual the object to compare to other - * @param other the object to compare to actual - * @return true if actual and other are equal based on {@link java.util.Objects#deepEquals(Object, Object)}, false otherwise. */ @Override public boolean areEqual(Object actual, Object other) { - return java.util.Objects.deepEquals(actual, other); + if (actual == null) return other == null; + Class actualClass = actual.getClass(); + if (actualClass.isArray()) { + Class otherClass = other.getClass(); + if (otherClass.isArray()) { + if (actualClass.getComponentType().isPrimitive() && otherClass.getComponentType().isPrimitive()) { + if (actual instanceof byte[] && other instanceof byte[]) + return java.util.Arrays.equals((byte[]) actual, (byte[]) other); + if (actual instanceof short[] && other instanceof short[]) + return java.util.Arrays.equals((short[]) actual, (short[]) other); + if (actual instanceof int[] && other instanceof int[]) + return java.util.Arrays.equals((int[]) actual, (int[]) other); + if (actual instanceof long[] && other instanceof long[]) + return java.util.Arrays.equals((long[]) actual, (long[]) other); + if (actual instanceof char[] && other instanceof char[]) + return java.util.Arrays.equals((char[]) actual, (char[]) other); + if (actual instanceof float[] && other instanceof float[]) + return java.util.Arrays.equals((float[]) actual, (float[]) other); + if (actual instanceof double[] && other instanceof double[]) + return java.util.Arrays.equals((double[]) actual, (double[]) other); + if (actual instanceof boolean[] && other instanceof boolean[]) + return java.util.Arrays.equals((boolean[]) actual, (boolean[]) other); + } + + if (actual instanceof Object[] && other instanceof Object[]) + return java.util.Arrays.deepEquals((Object[]) actual, (Object[]) other); + } + } + return actual.equals(other); } /** diff --git a/src/main/java/org/assertj/core/internal/Strings.java b/src/main/java/org/assertj/core/internal/Strings.java index 06e213f3b15..aea57bd2674 100644 --- a/src/main/java/org/assertj/core/internal/Strings.java +++ b/src/main/java/org/assertj/core/internal/Strings.java @@ -35,6 +35,7 @@ import static org.assertj.core.error.ShouldBeUpperCase.shouldBeUpperCase; import static org.assertj.core.error.ShouldContainCharSequence.shouldContain; import static org.assertj.core.error.ShouldContainCharSequence.shouldContainIgnoringCase; +import static org.assertj.core.error.ShouldContainCharSequence.shouldContainIgnoringWhitespaces; import static org.assertj.core.error.ShouldContainCharSequenceOnlyOnce.shouldContainOnlyOnce; import static org.assertj.core.error.ShouldContainOneOrMoreWhitespaces.shouldContainOneOrMoreWhitespaces; import static org.assertj.core.error.ShouldContainOnlyDigits.shouldContainOnlyDigits; @@ -99,6 +100,7 @@ */ public class Strings { + private static final String EMPTY_STRING = ""; private static final Strings INSTANCE = new Strings(); private static final String PUNCTUATION_REGEX = "\\p{Punct}"; private final ComparisonStrategy comparisonStrategy; @@ -517,6 +519,30 @@ public void assertContainsIgnoringCase(AssertionInfo info, CharSequence actual, throw failures.failure(info, shouldContainIgnoringCase(actual, sequence)); } + /** + * Verifies that the given {@code CharSequence} contains the given strings, ignoring whitespaces. + * + * @param info contains information about the assertion. + * @param actual the actual {@code CharSequence}. + * @param values the values to look for. + * @throws NullPointerException if the given sequence is {@code null}. + * @throws IllegalArgumentException if the given values is empty. + * @throws AssertionError if the given {@code CharSequence} is {@code null}. + * @throws AssertionError if the actual {@code CharSequence} does not contain the given sequence. + */ + public void assertContainsIgnoringWhitespaces(AssertionInfo info, CharSequence actual, CharSequence... values) { + doCommonCheckForCharSequence(info, actual, values); + String actualWithoutWhitespace = removeAllWhitespaces(actual); + Set notFound = stream(values).map(Strings::removeAllWhitespaces) + .filter(value -> !stringContains(actualWithoutWhitespace, value)) + .collect(toCollection(LinkedHashSet::new)); + if (notFound.isEmpty()) return; + if (values.length == 1) { + throw failures.failure(info, shouldContainIgnoringWhitespaces(actual, values[0], comparisonStrategy)); + } + throw failures.failure(info, shouldContainIgnoringWhitespaces(actual, values, notFound, comparisonStrategy)); + } + /** * Verifies that the given {@code CharSequence} does not contain any one of the given values, ignoring case considerations. * @@ -653,7 +679,7 @@ private boolean areEqualIgnoringWhitespace(CharSequence actual, CharSequence exp return removeAllWhitespaces(actual).equals(removeAllWhitespaces(expected)); } - private String removeAllWhitespaces(CharSequence toBeStripped) { + private static String removeAllWhitespaces(CharSequence toBeStripped) { final StringBuilder result = new StringBuilder(toBeStripped.length()); for (int i = 0; i < toBeStripped.length(); i++) { char c = toBeStripped.charAt(i); @@ -741,7 +767,7 @@ private static String normalizeWhitespaceAndPunctuation(CharSequence toNormalize if (toNormalize == null) { return null; } - return normalizeWhitespace(toNormalize.toString().replaceAll(PUNCTUATION_REGEX, "")); + return normalizeWhitespace(toNormalize.toString().replaceAll(PUNCTUATION_REGEX, EMPTY_STRING)); } /** @@ -766,7 +792,8 @@ public void assertEqualsToNormalizingUnicode(AssertionInfo info, CharSequence ac String normalizedActual = Normalizer.normalize(actual, Normalizer.Form.NFC); String normalizedExpected = Normalizer.normalize(expected, Normalizer.Form.NFC); if (!java.util.Objects.equals(normalizedActual, normalizedExpected)) - throw failures.failure(info, shouldBeEqualNormalizingUnicode(actual, expected, normalizedActual, normalizedExpected), normalizedActual, normalizedExpected); + throw failures.failure(info, shouldBeEqualNormalizingUnicode(actual, expected, normalizedActual, normalizedExpected), + normalizedActual, normalizedExpected); } /** @@ -994,7 +1021,7 @@ public void assertContainsSequence(AssertionInfo info, CharSequence actual, Char // convert all values to one char sequence to compare with the actual char sequence String strActual = actual.toString(); - String strSequence = String.join("", sequence); + String strSequence = String.join(EMPTY_STRING, sequence); if (!stringContains(strActual, strSequence)) { throw failures.failure(info, shouldContainSequence(actual, sequence, comparisonStrategy)); } @@ -1044,16 +1071,21 @@ public void assertContainsSubsequence(AssertionInfo info, CharSequence actual, C } private String removeUpTo(String string, CharSequence toRemove) { + // we have already checked that toRemove was not null in doCommonCheckForCharSequence and this point string is not neither int index = indexOf(string, toRemove); // remove the start of string up to toRemove included return string.substring(index + toRemove.length()); } private int indexOf(String string, CharSequence toFind) { + if (EMPTY_STRING.equals(string) && EMPTY_STRING.equals(toFind.toString())) return 0; for (int i = 0; i < string.length(); i++) { if (comparisonStrategy.stringStartsWith(string.substring(i), toFind.toString())) return i; } - return -1; + // should not arrive here since we this method is used from assertContainsSubsequence at a step where we know that toFind + // was found and we are checking whether it was at the right place/order. + throw new IllegalStateException(format("%s should have been found in %s, please raise an assertj-core issue", toFind, + string)); } public void assertXmlEqualsTo(AssertionInfo info, CharSequence actualXml, CharSequence expectedXml) { @@ -1200,7 +1232,7 @@ public void assertIsBase64(AssertionInfo info, String actual) { private static String removeNewLines(CharSequence text) { String normalizedText = normalizeNewlines(text); - return normalizedText.replace("\n", ""); + return normalizedText.replace("\n", EMPTY_STRING); } private void doCommonCheckForCharSequence(AssertionInfo info, CharSequence actual, CharSequence[] sequence) { diff --git a/src/main/java/org/assertj/core/internal/TypeComparators.java b/src/main/java/org/assertj/core/internal/TypeComparators.java index 93d6c08385e..7561925a630 100644 --- a/src/main/java/org/assertj/core/internal/TypeComparators.java +++ b/src/main/java/org/assertj/core/internal/TypeComparators.java @@ -15,6 +15,7 @@ import static java.lang.String.format; import static org.assertj.core.util.Strings.join; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Comparator; import java.util.List; @@ -25,6 +26,7 @@ import org.assertj.core.util.DoubleComparator; import org.assertj.core.util.FloatComparator; +import org.assertj.core.util.PathNaturalOrderComparator; import org.assertj.core.util.VisibleForTesting; import org.assertj.core.util.introspection.ClassUtils; @@ -42,6 +44,8 @@ public class TypeComparators { private static final float FLOAT_COMPARATOR_PRECISION = 1e-6f; private static final FloatComparator DEFAULT_FLOAT_COMPARATOR = new FloatComparator(FLOAT_COMPARATOR_PRECISION); + private static final Comparator DEFAULT_PATH_COMPARATOR = PathNaturalOrderComparator.INSTANCE; + // don't convert it to a lambda as it degrades TypeComparatorsPerfTest execution time by ~66% private static final Comparator> CLASS_COMPARATOR = new Comparator>() { @@ -58,6 +62,7 @@ public static TypeComparators defaultTypeComparators() { TypeComparators comparatorByType = new TypeComparators(); comparatorByType.put(Double.class, DEFAULT_DOUBLE_COMPARATOR); comparatorByType.put(Float.class, DEFAULT_FLOAT_COMPARATOR); + comparatorByType.put(Path.class, DEFAULT_PATH_COMPARATOR); return comparatorByType; } diff --git a/src/main/java/org/assertj/core/presentation/StandardRepresentation.java b/src/main/java/org/assertj/core/presentation/StandardRepresentation.java index 37842ec9002..4e5b4193c75 100644 --- a/src/main/java/org/assertj/core/presentation/StandardRepresentation.java +++ b/src/main/java/org/assertj/core/presentation/StandardRepresentation.java @@ -80,6 +80,7 @@ * Standard java object representation. * * @author Mariusz Smykula + * @author Jack Gough */ public class StandardRepresentation implements Representation { @@ -212,9 +213,13 @@ public String toStringOf(Object object) { if (object instanceof OffsetDateTime) return toStringOf((OffsetDateTime) object); if (object instanceof ZonedDateTime) return toStringOf((ZonedDateTime) object); if (object instanceof LongAdder) return toStringOf((LongAdder) object); - if (object instanceof AtomicReference) return toStringOf((AtomicReference) object); - if (object instanceof AtomicMarkableReference) return toStringOf((AtomicMarkableReference) object); - if (object instanceof AtomicStampedReference) return toStringOf((AtomicStampedReference) object); + // if object was a subtype of any atomic type overriding toString, use it as it's more relevant than our generic + // representation, if that's not the case (e.g. an AtomicReference subclass not overriding String) we use our representation. + if (isInstanceOfNotOverridingToString(object, AtomicReference.class)) return toStringOf((AtomicReference) object); + if (isInstanceOfNotOverridingToString(object, AtomicMarkableReference.class)) + return toStringOf((AtomicMarkableReference) object); + if (isInstanceOfNotOverridingToString(object, AtomicStampedReference.class)) + return toStringOf((AtomicStampedReference) object); if (object instanceof AtomicIntegerFieldUpdater) return AtomicIntegerFieldUpdater.class.getSimpleName(); if (object instanceof AtomicLongFieldUpdater) return AtomicLongFieldUpdater.class.getSimpleName(); if (object instanceof AtomicReferenceFieldUpdater) return AtomicReferenceFieldUpdater.class.getSimpleName(); @@ -238,7 +243,7 @@ public String toStringOf(Object object) { // Only format Iterables that are not collections and have not overridden toString // ex: JsonNode is an Iterable that is best formatted with its own String // Path is another example but we can deal with it specifically as it is part of the JDK. - if (object instanceof Iterable && !hasOverriddenToString((Iterable) object)) return smartFormat((Iterable) object); + if (object instanceof Iterable && !hasOverriddenToString(object.getClass())) return smartFormat((Iterable) object); if (object instanceof AtomicInteger) return toStringOf((AtomicInteger) object); if (object instanceof AtomicBoolean) return toStringOf((AtomicBoolean) object); if (object instanceof AtomicLong) return toStringOf((AtomicLong) object); @@ -247,18 +252,40 @@ public String toStringOf(Object object) { return fallbackToStringOf(object); } - private static boolean hasOverriddenToString(Iterable iterable) { + private static boolean isInstanceOfNotOverridingToString(Object object, Class type) { + return type.isInstance(object) && !hasOverriddenToStringInSubclassOf(object.getClass(), type); + } + + private static boolean hasOverriddenToString(Class clazz) { try { - Method method = iterable.getClass().getMethod("toString"); - Class declaringClass = method.getDeclaringClass(); - return !Object.class.equals(declaringClass); + Class classDeclaringToString = clazz.getMethod("toString").getDeclaringClass(); + return !Object.class.equals(classDeclaringToString); } catch (NoSuchMethodException | SecurityException e) { // NoSuchMethodException should not occur as toString is always defined. - // if SecurityException occurs, returning false will lead to format iterable + // if SecurityException occurs, returning false to use our own representation return false; } } + // this method assumes that objectClass is a subclass of clazz, it checks that toString is not + // declared in clazz or any superclass of clazz. + // this typically used to check whether an AtomicReference subclass has overridden toString. + private static boolean hasOverriddenToStringInSubclassOf(Class objectClass, Class clazz) { + try { + Class classDeclaringToString = objectClass.getMethod("toString").getDeclaringClass(); + // check if any classes between objectClass and clazz (excluded) have overridden toString + Class classToCheck = objectClass; + while (!classToCheck.equals(clazz)) { + if (classDeclaringToString.equals(classToCheck)) return true; + classToCheck = classToCheck.getSuperclass(); + } + } catch (NoSuchMethodException | SecurityException e) { + // NoSuchMethodException should not occur as toString is always defined. + // if SecurityException occurs, returning false to use our own representation + } + return false; + } + @Override public String unambiguousToStringOf(Object obj) { // some types have already an unambiguous toString, no need to double down @@ -455,7 +482,8 @@ protected String toStringOf(Map map) { protected String toStringOf(Throwable throwable) { StackTraceElement[] elements = throwable.getStackTrace(); // if the line limit is 0, we assume the user don't want to print stack trace - if (maxStackTraceElementsDisplayed == 0) return throwable.toString(); + // the null check is for user convenience when they mock throwable (otherwise elements is not nul) + if (maxStackTraceElementsDisplayed == 0 || elements == null) return throwable.toString(); // display the full stack trace if (maxStackTraceElementsDisplayed >= elements.length) return getStackTrace(throwable); @@ -478,16 +506,18 @@ protected String toStringOf(Throwable throwable) { } protected String toStringOf(AtomicReference atomicReference) { - return String.format("AtomicReference[%s]", toStringOf(atomicReference.get())); + return String.format("%s[%s]", atomicReference.getClass().getSimpleName(), toStringOf(atomicReference.get())); } protected String toStringOf(AtomicMarkableReference atomicMarkableReference) { - return String.format("AtomicMarkableReference[marked=%s, reference=%s]", atomicMarkableReference.isMarked(), + return String.format("%s[marked=%s, reference=%s]", atomicMarkableReference.getClass().getSimpleName(), + atomicMarkableReference.isMarked(), toStringOf(atomicMarkableReference.getReference())); } protected String toStringOf(AtomicStampedReference atomicStampedReference) { - return String.format("AtomicStampedReference[stamp=%s, reference=%s]", atomicStampedReference.getStamp(), + return String.format("%s[stamp=%s, reference=%s]", atomicStampedReference.getClass().getSimpleName(), + atomicStampedReference.getStamp(), toStringOf(atomicStampedReference.getReference())); } diff --git a/src/main/java/org/assertj/core/util/Lists.java b/src/main/java/org/assertj/core/util/Lists.java index 860681df6c1..d15356bd066 100644 --- a/src/main/java/org/assertj/core/util/Lists.java +++ b/src/main/java/org/assertj/core/util/Lists.java @@ -20,13 +20,19 @@ import java.util.List; /** - * Utility methods related to {@code java.util.List}s. + * Utility methods related to {@link List}s. * * @author Yvonne Wang * @author Alex Ruiz * @author Joel Costigliola */ public final class Lists { + + @SafeVarargs + public static List list(T... elements) { + return newArrayList(elements); + } + /** * Creates a mutable {@link ArrayList} containing the given elements. * @@ -44,16 +50,6 @@ public static ArrayList newArrayList(T... elements) { return list; } - @SafeVarargs - public static List list(T... elements) { - if (elements == null) { - return null; - } - ArrayList list = newArrayList(); - Collections.addAll(list, elements); - return list; - } - /** * Creates a mutable {@link ArrayList} containing the given elements. * @@ -100,6 +96,5 @@ public static List emptyList() { return Collections.emptyList(); } - private Lists() { - } + private Lists() {} } diff --git a/src/main/java/org/assertj/core/api/ProxyableMapAssert.java b/src/main/java/org/assertj/core/util/NaturalOrderComparator.java similarity index 50% rename from src/main/java/org/assertj/core/api/ProxyableMapAssert.java rename to src/main/java/org/assertj/core/util/NaturalOrderComparator.java index acfe041c78e..4a8ba58456a 100644 --- a/src/main/java/org/assertj/core/api/ProxyableMapAssert.java +++ b/src/main/java/org/assertj/core/util/NaturalOrderComparator.java @@ -10,23 +10,32 @@ * * Copyright 2012-2021 the original author or authors. */ -package org.assertj.core.api; +package org.assertj.core.util; -import java.util.List; -import java.util.Map; +import static java.lang.String.format; -/** - * Concrete assertions for {@link Map}s without any final methods to allow proxying. - */ -public class ProxyableMapAssert extends AbstractMapAssert, Map, KEY, VALUE> { +import java.util.Comparator; + +public class NaturalOrderComparator> extends NullSafeComparator { + + private String description; + + public NaturalOrderComparator(Class clazz) { + this.description = format("%s natural order", clazz.getSimpleName()); + } + + public NaturalOrderComparator(String description) { + this.description = description; + } - public ProxyableMapAssert(Map actual) { - super(actual, ProxyableMapAssert.class); + @Override + protected int compareNonNull(T o1, T o2) { + return Comparator. naturalOrder().compare(o1, o2); } @Override - protected AbstractListAssert, ELEMENT, ObjectAssert> newListAssertInstance(List newActual) { - return new ProxyableListAssert<>(newActual); + public String toString() { + return description; } } diff --git a/src/test/java/org/assertj/core/api/Assertions_tuple_Test.java b/src/main/java/org/assertj/core/util/PathNaturalOrderComparator.java similarity index 63% rename from src/test/java/org/assertj/core/api/Assertions_tuple_Test.java rename to src/main/java/org/assertj/core/util/PathNaturalOrderComparator.java index 5b5dd36b440..0796dc97127 100644 --- a/src/test/java/org/assertj/core/api/Assertions_tuple_Test.java +++ b/src/main/java/org/assertj/core/util/PathNaturalOrderComparator.java @@ -10,19 +10,16 @@ * * Copyright 2012-2021 the original author or authors. */ -package org.assertj.core.api; +package org.assertj.core.util; -import static org.assertj.core.api.Assertions.assertThat; +import java.nio.file.Path; -import org.assertj.core.groups.Tuple; -import org.junit.jupiter.api.Test; +public class PathNaturalOrderComparator extends NaturalOrderComparator { -class Assertions_tuple_Test { + public static final PathNaturalOrderComparator INSTANCE = new PathNaturalOrderComparator(); - @Test - void should_create_tuple() { - Tuple tuple = Assertions.tuple("Yoda", 800, "Jedi"); - assertThat(tuple).isEqualTo(new Tuple("Yoda", 800, "Jedi")); + private PathNaturalOrderComparator() { + super("lexicographic comparator (Path natural order)"); } } diff --git a/src/main/java/org/assertj/core/util/Sets.java b/src/main/java/org/assertj/core/util/Sets.java index 8e4dd2b5ee5..ec9536445f7 100644 --- a/src/main/java/org/assertj/core/util/Sets.java +++ b/src/main/java/org/assertj/core/util/Sets.java @@ -22,9 +22,22 @@ /** * Utility methods related to {@link Set}s. * - * @author alruiz + * @author Alex Ruiz */ public final class Sets { + + /** + * Creates a mutable {@link HashSet} containing the given elements. + * + * @param the generic type of the {@code HashSet} to create. + * @param elements the elements to store in the {@code HashSet}. + * @return the created {@code HashSet}, or {@code null} if the given array of elements is {@code null}. + */ + @SafeVarargs + public static Set set(T... elements) { + return newLinkedHashSet(elements); + } + /** * Creates a mutable {@code HashSet}. * diff --git a/src/main/java/org/assertj/core/util/introspection/Introspection.java b/src/main/java/org/assertj/core/util/introspection/Introspection.java index 17a68745d07..3ee5092ad50 100644 --- a/src/main/java/org/assertj/core/util/introspection/Introspection.java +++ b/src/main/java/org/assertj/core/util/introspection/Introspection.java @@ -81,7 +81,7 @@ public static void setExtractBareNamePropertyMethods(boolean barenamePropertyMet } @VisibleForTesting - public static boolean canIntrospectExtractBareNamePropertyMethods() { + public static boolean canExtractBareNamePropertyMethods() { return bareNamePropertyMethods; } diff --git a/src/main/java/org/assertj/core/util/introspection/PropertyOrFieldSupport.java b/src/main/java/org/assertj/core/util/introspection/PropertyOrFieldSupport.java index 5de3798f20f..78f3095d711 100644 --- a/src/main/java/org/assertj/core/util/introspection/PropertyOrFieldSupport.java +++ b/src/main/java/org/assertj/core/util/introspection/PropertyOrFieldSupport.java @@ -74,7 +74,7 @@ public Object getSimpleValue(String name, Object input) { // if the input object is a map, try name as a map key if (input instanceof Map) { Map map = (Map) input; - return map.get(name); + if (map.containsKey(name)) return map.get(name); } // no value found with given name, it is considered as an error diff --git a/src/test/java/org/assertj/core/api/AbstractTemporalAssert_isCloseTo_Test.java b/src/test/java/org/assertj/core/api/AbstractTemporalAssert_isCloseTo_Test.java index 26d3c1d8849..46515ac2afc 100644 --- a/src/test/java/org/assertj/core/api/AbstractTemporalAssert_isCloseTo_Test.java +++ b/src/test/java/org/assertj/core/api/AbstractTemporalAssert_isCloseTo_Test.java @@ -121,21 +121,21 @@ public class AbstractTemporalAssert_isCloseTo_Test { }; private static final String[] differenceMessages = { - format("%nExpecting:%n %s%nto be close to:%n %s%nwithin 50 Hours but difference was 96 Hours", + format("%nExpecting actual:%n %s%nto be close to:%n %s%nwithin 50 Hours but difference was 96 Hours", _2017_Mar_12_07_10_Instant, _2017_Mar_08_07_10_Instant), - format("%nExpecting:%n %s%nto be close to:%n %s%nwithin 2 Millis but difference was PT8765837682367H10M", + format("%nExpecting actual:%n %s%nto be close to:%n %s%nwithin 2 Millis but difference was PT8765837682367H10M", _2017_Mar_12_07_10_Instant, Instant.MIN), - format("%nExpecting:%n %s%nto be close to:%n %s%nwithin 50 Hours but difference was 96 Hours", + format("%nExpecting actual:%n %s%nto be close to:%n %s%nwithin 50 Hours but difference was 96 Hours", _2017_Mar_12_07_10, _2017_Mar_08_07_10), - format("%nExpecting:%n %s%nto be close to:%n %s%nwithin 3 Days but difference was 15 Days", + format("%nExpecting actual:%n %s%nto be close to:%n %s%nwithin 3 Days but difference was 15 Days", _2017_Mar_12, _2017_Mar_27), - format("%nExpecting:%n %s%nto be close to:%n %s%nwithin 5 Minutes but difference was 13 Minutes", + format("%nExpecting actual:%n %s%nto be close to:%n %s%nwithin 5 Minutes but difference was 13 Minutes", _07_10, _07_23), - format("%nExpecting:%n %s%nto be close to:%n %s%nwithin 10 Minutes but difference was 13 Minutes", + format("%nExpecting actual:%n %s%nto be close to:%n %s%nwithin 10 Minutes but difference was 13 Minutes", OffsetDateTime.of(_2017_Mar_12_07_10, UTC), OffsetDateTime.of(_2017_Mar_12_07_23, UTC)), - format("%nExpecting:%n %s%nto be close to:%n %s%nby less than 95 Hours but difference was 95 Hours", + format("%nExpecting actual:%n %s%nto be close to:%n %s%nby less than 95 Hours but difference was 95 Hours", ZonedDateTime.of(_2017_Mar_12_07_10, NEW_YORK_ZONE), ZonedDateTime.of(_2017_Mar_08_07_10, NEW_YORK_ZONE)), - format("%nExpecting:%n %s%nto be close to:%n %s%nwithin 2 Minutes but difference was 13 Minutes", + format("%nExpecting actual:%n %s%nto be close to:%n %s%nwithin 2 Minutes but difference was 13 Minutes", OffsetTime.of(_07_10, UTC), OffsetTime.of(_07_23, UTC)), }; diff --git a/src/test/java/org/assertj/core/api/Assertions_assertThatThrownBy_Test.java b/src/test/java/org/assertj/core/api/Assertions_assertThatThrownBy_Test.java new file mode 100644 index 00000000000..783bf81ffdc --- /dev/null +++ b/src/test/java/org/assertj/core/api/Assertions_assertThatThrownBy_Test.java @@ -0,0 +1,71 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static java.lang.String.format; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions_catchThrowableOfType_Test.raisingException; +import static org.assertj.core.api.Assertions_catchThrowable_Test.codeThrowing; +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.util.AssertionsUtil.expectAssertionError; + +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; +import org.junit.jupiter.api.Test; + +class Assertions_assertThatThrownBy_Test { + + @Test + void should_build_ThrowableAssert_with_runtime_exception_thrown() { + assertThatThrownBy(codeThrowing(new IllegalArgumentException("boom"))).isInstanceOf(IllegalArgumentException.class) + .hasMessage("boom"); + } + + @Test + void should_build_ThrowableAssert_with_throwable_thrown() { + assertThatThrownBy(codeThrowing(new Throwable("boom"))).isInstanceOf(Throwable.class) + .hasMessage("boom"); + } + + @Test + void should_be_able_to_pass_a_description_to_assertThatThrownBy() { + // GIVEN + // make assertThatThrownBy fail to verify the description afterwards + ThrowingCallable code = () -> assertThatThrownBy(raisingException("boom"), "Test %s", "code").hasMessage("bam"); + // WHEN + AssertionError assertionError = expectAssertionError(code); + // THEN + then(assertionError).hasMessageContaining("[Test code]"); + } + + @Test + void should_fail_if_no_throwable_was_thrown() { + // GIVEN + ThrowingCallable code = () -> {}; + // WHEN + AssertionError assertionError = expectAssertionError(() -> assertThatThrownBy(code).hasMessage("boom ?")); + // THEN + then(assertionError).hasMessage(format("%nExpecting code to raise a throwable.")); + } + + @Test + void should_fail_with_good_message_when_assertion_is_failing() { + // WHEN + AssertionError assertionError = expectAssertionError(() -> assertThatThrownBy(raisingException("boom")).hasMessage("bam")); + // THEN + then(assertionError).hasMessageContainingAll("Expecting message to be:", + "\"bam\"", + "but was:", + "\"boom\""); + } + +} diff --git a/src/test/java/org/assertj/core/api/Assertions_assertWith_Test.java b/src/test/java/org/assertj/core/api/Assertions_assertWith_Test.java new file mode 100644 index 00000000000..60c830508d9 --- /dev/null +++ b/src/test/java/org/assertj/core/api/Assertions_assertWith_Test.java @@ -0,0 +1,47 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatNullPointerException; +import static org.assertj.core.api.Assertions.assertWith; + +import java.util.function.Consumer; + +import org.assertj.core.test.Jedi; +import org.junit.jupiter.api.Test; + +class Assertions_assertWith_Test { + + private Jedi yoda = new Jedi("Yoda", "Green"); + + @Test + void delegates_to_satisfies_object_assertion() { + assertWith(yoda, jedi -> assertThat(jedi.lightSaberColor).isEqualTo("Green")); + } + + @Test + void should_allow_strongly_typed_assertion() { + assertWith("foo", string -> assertThat(string).startsWith("f")); + } + + @Test + void should_fail_when_consumer_is_null() { + // GIVEN + Consumer nullRequirements = null; + // WHEN/THEN + assertThatNullPointerException().isThrownBy(() -> assertWith(yoda, nullRequirements)) + .withMessage("The Consumer expressing the assertions requirements must not be null"); + } + +} diff --git a/src/test/java/org/assertj/core/api/Assertions_catchThrowableOfType_Test.java b/src/test/java/org/assertj/core/api/Assertions_catchThrowableOfType_Test.java index 00be69356d7..ba1f8fd18f1 100644 --- a/src/test/java/org/assertj/core/api/Assertions_catchThrowableOfType_Test.java +++ b/src/test/java/org/assertj/core/api/Assertions_catchThrowableOfType_Test.java @@ -12,13 +12,13 @@ */ package org.assertj.core.api; -import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.catchThrowable; import static org.assertj.core.api.Assertions.catchThrowableOfType; +import static org.assertj.core.api.Assertions_catchThrowable_Test.codeThrowing; +import static org.assertj.core.api.BDDAssertions.then; import static org.assertj.core.util.AssertionsUtil.expectAssertionError; +import static org.mockito.Mockito.mock; import java.io.IOException; @@ -27,39 +27,6 @@ class Assertions_catchThrowableOfType_Test { - @Test - void should_build_ThrowableAssert_with_runtime_exception_thrown() { - assertThatThrownBy(codeThrowing(new IllegalArgumentException("boom"))).isInstanceOf(IllegalArgumentException.class) - .hasMessage("boom"); - } - - @Test - void should_build_ThrowableAssert_with_throwable_thrown() { - assertThatThrownBy(codeThrowing(new Throwable("boom"))).isInstanceOf(Throwable.class) - .hasMessage("boom"); - } - - @Test - void should_be_able_to_pass_a_description_to_assertThatThrownBy() { - // GIVEN - // make assertThatThrownBy fail to verify the description afterwards - ThrowingCallable code = () -> assertThatThrownBy(raisingException("boom"), "Test %s", "code").hasMessage("bam"); - // WHEN - AssertionError assertionError = expectAssertionError(code); - // THEN - assertThat(assertionError).hasMessageContaining("[Test code]"); - } - - @Test - void should_fail_if_no_throwable_was_thrown() { - // GIVEN - ThrowingCallable code = () -> {}; - // WHEN - AssertionError assertionError = expectAssertionError(() -> assertThatThrownBy(code).hasMessage("boom ?")); - // THEN - assertThat(assertionError).hasMessage(format("%nExpecting code to raise a throwable.")); - } - @Test void can_capture_exception_and_then_assert_following_AAA_or_BDD_style() { // GIVEN @@ -67,7 +34,7 @@ void can_capture_exception_and_then_assert_following_AAA_or_BDD_style() { // WHEN Throwable boom = catchThrowable(codeThrowing(exception)); // THEN - assertThat(boom).isSameAs(exception); + then(boom).isSameAs(exception); } @Test @@ -75,7 +42,7 @@ void catchThrowable_returns_null_when_no_exception_thrown() { // WHEN Throwable boom = catchThrowable(() -> {}); // THEN - assertThat(boom).isNull(); + then(boom).isNull(); } @Test @@ -95,37 +62,29 @@ void catchThrowableOfType_should_succeed_and_return_actual_instance_with_correct // WHEN Exception actual = catchThrowableOfType(codeThrowing(expected), Exception.class); // THEN - assertThat(actual).isSameAs(expected); + then(actual).isSameAs(expected); } @Test void catchThrowableOfType_should_succeed_and_return_null_if_no_exception_thrown() { + // WHEN IOException actual = catchThrowableOfType(() -> {}, IOException.class); - assertThat(actual).isNull(); - } - - @Test - void should_fail_with_good_message_when_assertion_is_failing() { - assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThatThrownBy(raisingException("boom")).hasMessage("bam")) - .withMessageContaining("Expecting message to be:") - .withMessageContaining("\"bam\"") - .withMessageContaining("but was:") - .withMessageContaining("\"boom\""); + // THEN + then(actual).isNull(); } @Test - void should_pass_if_message_does_not_contain_description() { - assertThatExceptionOfType(Exception.class).isThrownBy(codeThrowing(new Exception("boom"))) - .withMessageNotContaining("bam"); + void should_catch_mocked_throwable() { + // GIVEN + Throwable throwable = mock(Throwable.class); + // WHEN + Throwable actual = catchThrowableOfType(codeThrowing(throwable), Throwable.class); + // THEN + then(actual).isSameAs(throwable); } - private static ThrowingCallable raisingException(final String reason) { + static ThrowingCallable raisingException(final String reason) { return codeThrowing(new Exception(reason)); } - private static ThrowingCallable codeThrowing(Throwable t) { - return () -> { - throw t; - }; - } } diff --git a/src/test/java/org/assertj/core/api/Assertions_catchThrowable_Test.java b/src/test/java/org/assertj/core/api/Assertions_catchThrowable_Test.java new file mode 100644 index 00000000000..c539558cb95 --- /dev/null +++ b/src/test/java/org/assertj/core/api/Assertions_catchThrowable_Test.java @@ -0,0 +1,46 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.assertj.core.api.BDDAssertions.then; + +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; +import org.junit.jupiter.api.Test; + +class Assertions_catchThrowable_Test { + + @Test + void can_capture_exception_and_then_assert_following_AAA_or_BDD_style() { + // GIVEN + Exception exception = new Exception("boom!!"); + // WHEN + Throwable boom = catchThrowable(codeThrowing(exception)); + // THEN + then(boom).isSameAs(exception); + } + + @Test + void catchThrowable_returns_null_when_no_exception_thrown() { + // WHEN + Throwable boom = catchThrowable(() -> {}); + // THEN + then(boom).isNull(); + } + + static ThrowingCallable codeThrowing(Throwable t) { + return () -> { + throw t; + }; + } +} diff --git a/src/test/java/org/assertj/core/api/Assertions_fail_Test.java b/src/test/java/org/assertj/core/api/Assertions_fail_Test.java deleted file mode 100644 index 757568cf20e..00000000000 --- a/src/test/java/org/assertj/core/api/Assertions_fail_Test.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - * Copyright 2012-2021 the original author or authors. - */ -package org.assertj.core.api; - -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.assertj.core.api.Assertions.fail; - -import java.util.Optional; - -import org.junit.jupiter.api.Test; - -class Assertions_fail_Test { - - @Test - void should_include_message_when_failing() { - assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> fail("Failed :(")) - .withMessage("Failed :("); - } - - @Test - void should_include_message_with_parameters_when_failing() { - assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> fail("Failed %s", ":(")) - .withMessage("Failed :("); - } - - @Test - void should_include_message_with_cause_when_failing() { - String message = "Some Throwable"; - Throwable cause = new Throwable(); - assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> fail(message, cause)) - .withMessage(message).withCause(cause); - } - - @Test - void should_return_a_value_to_allow_using_optional_orElseGet() { - // GIVEN - Optional empty = Optional.empty(); - // THEN - assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> doSomethingWithInt(empty.orElseGet(() -> fail("Failed :(")))) - .withMessage("Failed :("); - } - - private void doSomethingWithInt(@SuppressWarnings("unused") int parameter) { - // just to illustrate the previous test - } -} diff --git a/src/test/java/org/assertj/core/api/Assertions_sync_assertThat_with_BDD_and_Soft_variants_Test.java b/src/test/java/org/assertj/core/api/Assertions_sync_assertThat_with_BDD_and_Soft_variants_Test.java index 493c5b5ab95..d8d0012ecfc 100644 --- a/src/test/java/org/assertj/core/api/Assertions_sync_assertThat_with_BDD_and_Soft_variants_Test.java +++ b/src/test/java/org/assertj/core/api/Assertions_sync_assertThat_with_BDD_and_Soft_variants_Test.java @@ -15,8 +15,10 @@ import static java.util.Arrays.stream; import static java.util.stream.Collectors.toSet; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.util.Lists.list; import java.lang.reflect.Method; +import java.util.List; import java.util.Set; import org.junit.jupiter.api.Test; @@ -28,60 +30,81 @@ class Assertions_sync_assertThat_with_BDD_and_Soft_variants_Test extends BaseAss @Test void standard_assertions_and_bdd_assertions_should_have_the_same_assertions_methods() { - Method[] assertThatMethods = findMethodsWithName(Assertions.class, "assertThat"); - Method[] thenMethods = findMethodsWithName(BDDAssertions.class, "then"); + Method[] assertThat_Assertions_methods = findMethodsWithName(Assertions.class, "assertThat"); + Method[] then_Assertions_methods = findMethodsWithName(BDDAssertions.class, "then"); - assertThat(thenMethods).usingElementComparator(IGNORING_DECLARING_CLASS_AND_METHOD_NAME) - .containsExactlyInAnyOrder(assertThatMethods); + assertThat(then_Assertions_methods).usingElementComparator(IGNORING_DECLARING_CLASS_AND_METHOD_NAME) + .containsExactlyInAnyOrder(assertThat_Assertions_methods); } @Test void standard_assertions_and_with_assertions_should_have_the_same_assertions_methods() { - Method[] assertionsMethods = findMethodsWithName(Assertions.class, "assertThat"); - Method[] withAssertionsMethods = findMethodsWithName(WithAssertions.class, "assertThat"); + Method[] assertThat_Assertions_methods = findMethodsWithName(Assertions.class, "assertThat"); + Method[] assertThat_WithAssertions_methods = findMethodsWithName(WithAssertions.class, "assertThat"); - assertThat(withAssertionsMethods).usingElementComparator(IGNORING_DECLARING_CLASS_ONLY) - .containsExactlyInAnyOrder(assertionsMethods); + assertThat(assertThat_WithAssertions_methods).usingElementComparator(IGNORING_DECLARING_CLASS_ONLY) + .containsExactlyInAnyOrder(assertThat_Assertions_methods); } @Test void standard_assertions_and_with_assertions_should_have_the_same_non_assertions_methods() { - Set nonAssertionsMethods = nonAssertionsMethodsOf(Assertions.class.getDeclaredMethods()); - Set nonWithAssertionsMethods = nonAssertionsMethodsOf(WithAssertions.class.getDeclaredMethods()); + Set non_assertThat_Assertions_methods = non_assertThat_methodsOf(Assertions.class.getDeclaredMethods()); + Set non_assertThat_WithAssertions_methods = non_assertThat_methodsOf(WithAssertions.class.getDeclaredMethods()); - assertThat(nonWithAssertionsMethods).usingElementComparator(IGNORING_DECLARING_CLASS_ONLY) - .containsExactlyInAnyOrderElementsOf(nonAssertionsMethods); + assertThat(non_assertThat_WithAssertions_methods).usingElementComparator(IGNORING_DECLARING_CLASS_ONLY) + .containsExactlyInAnyOrderElementsOf(non_assertThat_Assertions_methods); + } + + @Test + void standard_assertions_and_bdd_assertions_should_have_the_same_non_assertions_methods() { + + List methodsToIgnore = list("failBecauseExceptionWasNotThrown", "filter", "offset"); + Set non_assertThat_methods = non_assertThat_methodsOf(Assertions.class.getDeclaredMethods()); + non_assertThat_methods = removeMethods(non_assertThat_methods, methodsToIgnore); + Set non_then_methods = non_then_methodsOf(BDDAssertions.class.getDeclaredMethods()); + non_then_methods = removeMethods(non_then_methods, methodsToIgnore); + + assertThat(non_then_methods).usingElementComparator(IGNORING_DECLARING_CLASS_AND_METHOD_NAME) + .containsExactlyInAnyOrderElementsOf(non_assertThat_methods); + } + + private static Set removeMethods(Set methods, List methodsToRemove) { + return methods.stream() + .filter(method -> !methodsToRemove.contains(method.getName())) + .collect(toSet()); } @Test void standard_assertions_and_soft_assertions_should_have_the_same_assertions_methods() { // Until the SpecialIgnoredReturnTypes like AssertProvider, XXXNavigableXXXAssert are implemented for // the soft assertions we need to ignore them - Method[] assertThatMethods = findMethodsWithName(Assertions.class, "assertThat", SPECIAL_IGNORED_RETURN_TYPES); - Method[] assertThatSoftMethods = findMethodsWithName(StandardSoftAssertionsProvider.class, "assertThat"); + Method[] assertThat_Assertions_methods = findMethodsWithName(Assertions.class, "assertThat", SPECIAL_IGNORED_RETURN_TYPES); + Method[] assertThat_SoftAssertions_methods = findMethodsWithName(StandardSoftAssertionsProvider.class, "assertThat"); // ignore the return type of soft assertions until they have the same as the Assertions - assertThat(assertThatMethods).usingElementComparator(IGNORING_DECLARING_CLASS_AND_RETURN_TYPE) - .containsExactlyInAnyOrder(assertThatSoftMethods); - + assertThat(assertThat_Assertions_methods).usingElementComparator(IGNORING_DECLARING_CLASS_ONLY) + .containsExactlyInAnyOrder(assertThat_SoftAssertions_methods); } @Test void bdd_assertions_and_bdd_soft_assertions_should_have_the_same_assertions_methods() { // Until the SpecialIgnoredReturnTypes like AssertProvider, XXXNavigableXXXAssert are implemented for // the soft assertions we need to ignore them - Method[] thenMethods = findMethodsWithName(BDDAssertions.class, "then", SPECIAL_IGNORED_RETURN_TYPES); - Method[] thenSoftMethods = findMethodsWithName(BDDSoftAssertionsProvider.class, "then"); + Method[] then_Assertions_methods = findMethodsWithName(BDDAssertions.class, "then", SPECIAL_IGNORED_RETURN_TYPES); + Method[] then_BDDSoftAssertions_methods = findMethodsWithName(BDDSoftAssertionsProvider.class, "then"); // ignore the return type of soft assertions until they have the same as the Assertions - assertThat(thenMethods).usingElementComparator(IGNORING_DECLARING_CLASS_AND_RETURN_TYPE) - .containsExactlyInAnyOrder(thenSoftMethods); + assertThat(then_Assertions_methods).usingElementComparator(IGNORING_DECLARING_CLASS_ONLY) + .containsExactlyInAnyOrder(then_BDDSoftAssertions_methods); + } + private static Set non_assertThat_methodsOf(Method[] declaredMethods) { + return stream(declaredMethods).filter(method -> !method.getName().startsWith("assert")).collect(toSet()); } - private static Set nonAssertionsMethodsOf(Method[] declaredMethods) { - return stream(declaredMethods).filter(method -> !method.getName().equals("assertThat")).collect(toSet()); + private static Set non_then_methodsOf(Method[] declaredMethods) { + return stream(declaredMethods).filter(method -> !method.getName().startsWith("then")).collect(toSet()); } } diff --git a/src/test/java/org/assertj/core/api/Assertions_sync_with_Assumptions_Test.java b/src/test/java/org/assertj/core/api/Assertions_sync_with_Assumptions_Test.java index 6083fe562e3..60c9eff52ab 100644 --- a/src/test/java/org/assertj/core/api/Assertions_sync_with_Assumptions_Test.java +++ b/src/test/java/org/assertj/core/api/Assertions_sync_with_Assumptions_Test.java @@ -25,7 +25,7 @@ void standard_assertions_and_assumptions_should_have_the_same_assertions_methods Method[] assertThatMethods = findMethodsWithName(Assertions.class, "assertThat", SPECIAL_IGNORED_RETURN_TYPES); Method[] assumeThatMethods = findMethodsWithName(Assumptions.class, "assumeThat"); - assertThat(assertThatMethods).usingElementComparator(IGNORING_DECLARING_CLASS_RETURN_TYPE_AND_METHOD_NAME) + assertThat(assertThatMethods).usingElementComparator(IGNORING_DECLARING_CLASS_AND_METHOD_NAME) .containsExactlyInAnyOrder(assumeThatMethods); } diff --git a/src/test/java/org/assertj/core/api/Assertions_sync_with_BDDAssumptions_Test.java b/src/test/java/org/assertj/core/api/Assertions_sync_with_BDDAssumptions_Test.java index 528c912e2e3..e5ea4ad6f8f 100644 --- a/src/test/java/org/assertj/core/api/Assertions_sync_with_BDDAssumptions_Test.java +++ b/src/test/java/org/assertj/core/api/Assertions_sync_with_BDDAssumptions_Test.java @@ -25,7 +25,7 @@ void standard_assertions_and_bdd_assumptions_should_have_the_same_assertions_met Method[] assertThatMethods = findMethodsWithName(Assertions.class, "assertThat", SPECIAL_IGNORED_RETURN_TYPES); Method[] givenMethods = findMethodsWithName(BDDAssumptions.class, "given"); - assertThat(givenMethods).usingElementComparator(IGNORING_DECLARING_CLASS_RETURN_TYPE_AND_METHOD_NAME) + assertThat(givenMethods).usingElementComparator(IGNORING_DECLARING_CLASS_AND_METHOD_NAME) .contains(assertThatMethods); } @@ -34,7 +34,7 @@ void object_assertions_and_bdd_assumptions_should_have_the_same_assertions_metho Method[] assertThatMethods = findMethodsWithName(Assertions.class, "assertThatObject", SPECIAL_IGNORED_RETURN_TYPES); Method[] givenMethods = findMethodsWithName(BDDAssumptions.class, "givenObject"); - assertThat(givenMethods).usingElementComparator(IGNORING_DECLARING_CLASS_RETURN_TYPE_AND_METHOD_NAME) + assertThat(givenMethods).usingElementComparator(IGNORING_DECLARING_CLASS_AND_METHOD_NAME) .contains(assertThatMethods); } @@ -43,7 +43,7 @@ void code_assertions_and_bdd_assumptions_should_have_the_same_assertions_methods Method[] assertThatMethods = findMethodsWithName(Assertions.class, "assertThatCode", SPECIAL_IGNORED_RETURN_TYPES); Method[] givenMethods = findMethodsWithName(BDDAssumptions.class, "givenCode"); - assertThat(givenMethods).usingElementComparator(IGNORING_DECLARING_CLASS_RETURN_TYPE_AND_METHOD_NAME) + assertThat(givenMethods).usingElementComparator(IGNORING_DECLARING_CLASS_AND_METHOD_NAME) .contains(assertThatMethods); } diff --git a/src/test/java/org/assertj/core/api/Assertions_sync_with_InstanceOfAssertFactories_Test.java b/src/test/java/org/assertj/core/api/Assertions_sync_with_InstanceOfAssertFactories_Test.java index 68d1009b0ec..af9b600b26d 100644 --- a/src/test/java/org/assertj/core/api/Assertions_sync_with_InstanceOfAssertFactories_Test.java +++ b/src/test/java/org/assertj/core/api/Assertions_sync_with_InstanceOfAssertFactories_Test.java @@ -36,7 +36,7 @@ class Assertions_sync_with_InstanceOfAssertFactories_Test extends BaseAssertions private static final Class[] FIELD_FACTORIES_IGNORED_TYPES = { // There can be no Comparable field factory with a base type. - AbstractComparableAssert.class, + GenericComparableAssert.class, // The comparison of the input GenericArrayTypes will always fail, since it verifies the inner TypeVariable which // returns the defining Method as result of TypeVariable#getGenericDeclaration(). ObjectArrayAssert.class, diff --git a/src/test/java/org/assertj/core/api/BDDAssertions_then_Test.java b/src/test/java/org/assertj/core/api/BDDAssertions_then_Test.java index 741d2560597..77026596753 100644 --- a/src/test/java/org/assertj/core/api/BDDAssertions_then_Test.java +++ b/src/test/java/org/assertj/core/api/BDDAssertions_then_Test.java @@ -14,6 +14,7 @@ import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.as; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.BDDAssertions.and; import static org.assertj.core.api.BDDAssertions.then; import static org.assertj.core.api.BDDAssertions.thenExceptionOfType; @@ -24,6 +25,7 @@ import static org.assertj.core.api.BDDAssertions.thenNullPointerException; import static org.assertj.core.api.BDDAssertions.thenObject; import static org.assertj.core.api.BDDAssertions.thenThrownBy; +import static org.assertj.core.api.BDDAssertions.thenWith; import static org.assertj.core.api.InstanceOfAssertFactories.INTEGER; import static org.assertj.core.api.InstanceOfAssertFactories.STRING; import static org.assertj.core.util.Lists.list; @@ -300,6 +302,11 @@ void then_explicit_Object() { thenObject(new LinkedList<>()).matches(l -> l.peek() == null); } + @Test + void then_with() { + thenWith("foo", string -> assertThat(string).startsWith("f")); + } + @Test void then_URI() { then(URI.create("http://assertj.org")).hasNoPort(); diff --git a/src/test/java/org/assertj/core/api/BDDSoftAssertionsTest.java b/src/test/java/org/assertj/core/api/BDDSoftAssertionsTest.java index f2281db3738..c834d0e79c8 100644 --- a/src/test/java/org/assertj/core/api/BDDSoftAssertionsTest.java +++ b/src/test/java/org/assertj/core/api/BDDSoftAssertionsTest.java @@ -163,7 +163,6 @@ void all_assertions_should_pass() { softly.assertAll(); } - @SuppressWarnings("unchecked") @Test void should_be_able_to_catch_exceptions_thrown_by_map_assertions() { // GIVEN @@ -183,7 +182,7 @@ void should_be_able_to_catch_exceptions_thrown_by_map_assertions() { } - @SuppressWarnings({ "unchecked", "deprecation" }) + @SuppressWarnings({ "deprecation" }) @Test void should_be_able_to_catch_exceptions_thrown_by_all_proxied_methods() throws MalformedURLException { // GIVEN @@ -346,15 +345,15 @@ public String toString() { assertThat(errors.get(45)).contains(shouldBeEqualMessage("OptionalLong[0]", "1L")); assertThat(errors.get(46)).contains("Expecting port of"); assertThat(errors.get(47)).contains("to have failed"); - assertThat(errors.get(48)).contains(format("%nExpecting:%n given predicate%n" + assertThat(errors.get(48)).contains(format("%nExpecting actual:%n given predicate%n" + "to accept \"something else\" but it did not.")); - assertThat(errors.get(49)).contains(format("%nExpecting:%n given predicate%n" + assertThat(errors.get(49)).contains(format("%nExpecting actual:%n given predicate%n" + "to accept 2 but it did not.")); - assertThat(errors.get(50)).contains(format("%nExpecting:%n given predicate%n" + assertThat(errors.get(50)).contains(format("%nExpecting actual:%n given predicate%n" + "to accept 2L but it did not.")); - assertThat(errors.get(51)).contains(format("%nExpecting:%n given predicate%n" + assertThat(errors.get(51)).contains(format("%nExpecting actual:%n given predicate%n" + "to accept 2.0 but it did not.")); - assertThat(errors.get(52)).contains(format("%nExpecting:%n" + assertThat(errors.get(52)).contains(format("%nExpecting actual:%n" + " %n" + "not to have a port but had:%n" + " <80>")); @@ -369,7 +368,6 @@ public String toString() { assertThat(errors.get(61)).contains("LongAdder check"); } - @SuppressWarnings("unchecked") @Test void should_pass_when_using_extracting_with_object() { // GIVEN @@ -736,6 +734,10 @@ void should_propagate_AssertionError_from_nested_proxied_calls() { softly.then(emptyList()).element(1); // the nested proxied call to isNotEmpty() throw an Assertion error that must be propagated to the caller. softly.then(emptyList()).element(1, as(STRING)); + // the nested proxied call to isNotEmpty() throw an Assertion error that must be propagated to the caller. + softly.then(emptyList()).elements(0, 1, 2); + // the nested proxied call to checkIndexValidity throw an Assertion error that must be propagated to the caller. + softly.then(list("a", "b")).elements(0, 5); // the nested proxied call to assertHasSize() throw an Assertion error that must be propagated to the caller. softly.then(emptyList()).singleElement(); // the nested proxied call to assertHasSize() throw an Assertion error that must be propagated to the caller. @@ -747,7 +749,7 @@ void should_propagate_AssertionError_from_nested_proxied_calls() { // nested proxied call to isCompleted softly.then(new CompletableFuture()).isCompletedWithValue("done"); // it must be caught by softly.assertAll() - assertThat(softly.errorsCollected()).hasSize(11); + assertThat(softly.errorsCollected()).hasSize(13); } // bug #447 @@ -944,15 +946,21 @@ void iterable_soft_assertions_should_work_with_navigation_methods() { .last() .as("last element") .isNull(); + softly.then(names) + .as("elements(0, 1)") + .overridingErrorMessage("error message") + .elements(0, 1) + .isNull(); // THEN List errorsCollected = softly.errorsCollected(); - assertThat(errorsCollected).hasSize(6); + assertThat(errorsCollected).hasSize(7); assertThat(errorsCollected.get(0)).hasMessageContaining("10"); assertThat(errorsCollected.get(1)).hasMessageContaining("22"); assertThat(errorsCollected.get(2)).hasMessageContaining("empty"); assertThat(errorsCollected.get(3)).hasMessageContaining("first element"); assertThat(errorsCollected.get(4)).hasMessageContaining("element(0)"); assertThat(errorsCollected.get(5)).hasMessageContaining("last element"); + assertThat(errorsCollected.get(6)).hasMessage("[elements(0, 1)] error message"); } @Test @@ -980,15 +988,21 @@ void list_soft_assertions_should_work_with_navigation_methods() { .last() .as("last element") .isNull(); + softly.then(names) + .as("elements(0, 1)") + .overridingErrorMessage("error message") + .elements(0, 1) + .isNull(); // THEN List errorsCollected = softly.errorsCollected(); - assertThat(errorsCollected).hasSize(6); + assertThat(errorsCollected).hasSize(7); assertThat(errorsCollected.get(0)).hasMessageContaining("10"); assertThat(errorsCollected.get(1)).hasMessageContaining("22"); assertThat(errorsCollected.get(2)).hasMessageContaining("empty"); assertThat(errorsCollected.get(3)).hasMessageContaining("first element"); assertThat(errorsCollected.get(4)).hasMessageContaining("element(0)"); assertThat(errorsCollected.get(5)).hasMessageContaining("last element"); + assertThat(errorsCollected.get(5)).hasMessageContaining("last element"); } @Test @@ -1030,7 +1044,6 @@ void list_soft_assertions_should_work_with_singleElement_navigation() { } // the test would fail if any method was not proxyable as the assertion error would not be softly caught - @SuppressWarnings("unchecked") @Test void iterable_soft_assertions_should_report_errors_on_final_methods_and_methods_that_switch_the_object_under_test() { // GIVEN @@ -1231,7 +1244,6 @@ void iterable_soft_assertions_should_report_errors_on_final_methods_and_methods_ } // the test would fail if any method was not proxyable as the assertion error would not be softly caught - @SuppressWarnings("unchecked") @Test void list_soft_assertions_should_report_errors_on_final_methods_and_methods_that_switch_the_object_under_test() { // GIVEN @@ -1433,7 +1445,6 @@ void list_soft_assertions_should_report_errors_on_final_methods_and_methods_that } // the test would fail if any method was not proxyable as the assertion error would not be softly caught - @SuppressWarnings("unchecked") @Test void object_array_soft_assertions_should_report_errors_on_final_methods_and_methods_that_switch_the_object_under_test() { // GIVEN @@ -1569,7 +1580,6 @@ void object_array_soft_assertions_should_report_errors_on_final_methods_and_meth } // the test would fail if any method was not proxyable as the assertion error would not be softly caught - @SuppressWarnings("unchecked") @Test void class_soft_assertions_should_report_errors_on_final_methods() { // GIVEN @@ -1586,7 +1596,6 @@ void class_soft_assertions_should_report_errors_on_final_methods() { } // the test would fail if any method was not proxyable as the assertion error would not be softly caught - @SuppressWarnings("unchecked") @Test void object_soft_assertions_should_report_errors_on_final_methods_and_methods_that_switch_the_object_under_test() { // GIVEN @@ -1632,7 +1641,6 @@ void object_soft_assertions_should_report_errors_on_final_methods_and_methods_th } // the test would fail if any method was not proxyable as the assertion error would not be softly caught - @SuppressWarnings("unchecked") @Test void map_soft_assertions_should_report_errors_on_final_methods_and_methods_that_switch_the_object_under_test() { // GIVEN @@ -1716,7 +1724,6 @@ void map_soft_assertions_should_work_with_navigation_methods() { assertThat(errorsCollected.get(3)).hasMessageContaining("check size after navigating back"); } - @SuppressWarnings("unchecked") @Test void predicate_soft_assertions_should_report_errors_on_final_methods() { // GIVEN @@ -1799,7 +1806,6 @@ class ExtractingFromEntries { MapEntry.entry(david, list(new Animal("scoubi"), new Animal("peter")))); @Test - @SuppressWarnings("unchecked") void should_pass_when_using_extractingFromEntries_with_map() { // WHEN softly.then(map) @@ -1815,7 +1821,6 @@ void should_pass_when_using_extractingFromEntries_with_map() { } @Test - @SuppressWarnings("unchecked") void should_collect_errors_when_using_extractingFromEntries_with_map() { // WHEN softly.then(map) diff --git a/src/test/java/org/assertj/core/api/BaseAssertionsTest.java b/src/test/java/org/assertj/core/api/BaseAssertionsTest.java index 9866cd2ebf5..2cf951c2013 100644 --- a/src/test/java/org/assertj/core/api/BaseAssertionsTest.java +++ b/src/test/java/org/assertj/core/api/BaseAssertionsTest.java @@ -37,13 +37,8 @@ public abstract class BaseAssertionsTest { static final Comparator IGNORING_DECLARING_CLASS_AND_METHOD_NAME = internalMethodComparator(false, true); - static final Comparator IGNORING_DECLARING_CLASS_AND_RETURN_TYPE = internalMethodComparator(true, false); - static final Comparator IGNORING_DECLARING_CLASS_ONLY = internalMethodComparator(false, false); - static final Comparator IGNORING_DECLARING_CLASS_RETURN_TYPE_AND_METHOD_NAME = internalMethodComparator(true, - true); - // Object is ignored because of the AssertProvider static final Class[] SPECIAL_IGNORED_RETURN_TYPES = array(AssertDelegateTarget.class, FactoryBasedNavigableListAssert.class, FactoryBasedNavigableIterableAssert.class, diff --git a/src/test/java/org/assertj/core/api/Assertions_as_with_InstanceOfAssertFactory_Test.java b/src/test/java/org/assertj/core/api/Condition_status_Test.java similarity index 57% rename from src/test/java/org/assertj/core/api/Assertions_as_with_InstanceOfAssertFactory_Test.java rename to src/test/java/org/assertj/core/api/Condition_status_Test.java index 60c7c89e0e8..fa346c715cd 100644 --- a/src/test/java/org/assertj/core/api/Assertions_as_with_InstanceOfAssertFactory_Test.java +++ b/src/test/java/org/assertj/core/api/Condition_status_Test.java @@ -13,25 +13,33 @@ package org.assertj.core.api; import static org.assertj.core.api.BDDAssertions.then; -import static org.mockito.Mockito.mock; +import org.assertj.core.api.Condition.Status; +import org.assertj.core.condition.JediCondition; import org.junit.jupiter.api.Test; -/** - * Tests for {@link Assertions#as(InstanceOfAssertFactory)}. - * - * @author Stefano Cordio - */ -class Assertions_as_with_InstanceOfAssertFactory_Test { +class Condition_status_Test { + + private Condition jediCondition = new JediCondition(); + + @Test + void should_return_success_status() { + // GIVEN + String yoda = "Yoda"; + // WHEN + Status status = jediCondition.status(yoda); + // THEN + then(status).isEqualTo(Status.SUCCESS); + } @Test - void should_return_the_given_assert_factory() { + void should_return_description_with_failed_status() { // GIVEN - InstanceOfAssertFactory> assertFactory = mock(InstanceOfAssertFactory.class); + String vader = "Vader"; // WHEN - InstanceOfAssertFactory> result = Assertions.as(assertFactory); + Status status = jediCondition.status(vader); // THEN - then(result).isSameAs(assertFactory); + then(status).isEqualTo(Status.FAIL); } } diff --git a/src/main/java/org/assertj/core/api/ProxyableClassAssert.java b/src/test/java/org/assertj/core/api/EntryPointAssertionsBaseTest.java similarity index 69% rename from src/main/java/org/assertj/core/api/ProxyableClassAssert.java rename to src/test/java/org/assertj/core/api/EntryPointAssertionsBaseTest.java index 7995eec0374..7a31c1d7835 100644 --- a/src/main/java/org/assertj/core/api/ProxyableClassAssert.java +++ b/src/test/java/org/assertj/core/api/EntryPointAssertionsBaseTest.java @@ -12,14 +12,11 @@ */ package org.assertj.core.api; +import static org.mockito.Answers.CALLS_REAL_METHODS; +import static org.mockito.Mockito.mock; -/** - * Concrete assertions for {@link Class}s without any final methods to allow proxying. - */ -public class ProxyableClassAssert extends AbstractClassAssert { +public class EntryPointAssertionsBaseTest { + + protected static final WithAssertions withAssertions = mock(WithAssertions.class, CALLS_REAL_METHODS); - public ProxyableClassAssert(Class actual) { - super(actual, ProxyableClassAssert.class); - } - } diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_allOf_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_allOf_Test.java new file mode 100644 index 00000000000..f40b90ed902 --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_allOf_Test.java @@ -0,0 +1,70 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.Assertions.as; +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.api.InstanceOfAssertFactories.ITERABLE; +import static org.assertj.core.util.Arrays.array; +import static org.assertj.core.util.Lists.list; + +import java.util.Collection; +import java.util.function.Function; +import java.util.stream.Stream; + +import org.assertj.core.condition.AllOf; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPoint assertions allOf method") +class EntryPointAssertions_allOf_Test extends EntryPointAssertionsBaseTest { + + @ParameterizedTest + @MethodSource("allOfWithArrayFactories") + void should_create_allOf_condition_from_condition_array(Function[], Condition> allOfFactory) { + // GIVEN + Condition condition1 = new TestCondition<>("condition 1"); + Condition condition2 = new TestCondition<>("condition 2"); + // WHEN + Condition allOfCondition = allOfFactory.apply(array(condition1, condition2)); + // THEN + then(allOfCondition).isInstanceOf(AllOf.class) + .extracting("conditions", as(ITERABLE)) + .containsExactly(condition1, condition2); + } + + @SuppressWarnings("unchecked") + private static Stream[], Condition>> allOfWithArrayFactories() { + return Stream.of(Assertions::allOf, BDDAssertions::allOf, withAssertions::allOf); + } + + @ParameterizedTest + @MethodSource("allOfWithCollectionFactories") + void should_create_allOf_condition_from_condition_collection(Function>, Condition> allOfFactory) { + // GIVEN + Condition condition1 = new TestCondition<>("condition 1"); + Condition condition2 = new TestCondition<>("condition 2"); + // WHEN + Condition allOfCondition = allOfFactory.apply(list(condition1, condition2)); + // THEN + then(allOfCondition).isInstanceOf(AllOf.class) + .extracting("conditions", as(ITERABLE)) + .containsExactly(condition1, condition2); + } + + private static Stream>, Condition>> allOfWithCollectionFactories() { + return Stream.of(Assertions::allOf, BDDAssertions::allOf, withAssertions::allOf); + } + +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_anyOf_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_anyOf_Test.java new file mode 100644 index 00000000000..b3c18ecff82 --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_anyOf_Test.java @@ -0,0 +1,70 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.Assertions.as; +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.api.InstanceOfAssertFactories.ITERABLE; +import static org.assertj.core.util.Arrays.array; +import static org.assertj.core.util.Lists.list; + +import java.util.Collection; +import java.util.function.Function; +import java.util.stream.Stream; + +import org.assertj.core.condition.AnyOf; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPoint assertions anyOf method") +class EntryPointAssertions_anyOf_Test extends EntryPointAssertionsBaseTest { + + @ParameterizedTest + @MethodSource("anyOfWithArrayFactories") + void should_create_anyOf_condition_from_condition_array(Function[], Condition> anyOfFactory) { + // GIVEN + Condition condition1 = new TestCondition<>("condition 1"); + Condition condition2 = new TestCondition<>("condition 2"); + // WHEN + Condition anyOfCondition = anyOfFactory.apply(array(condition1, condition2)); + // THEN + then(anyOfCondition).isInstanceOf(AnyOf.class) + .extracting("conditions", as(ITERABLE)) + .containsExactly(condition1, condition2); + } + + @SuppressWarnings("unchecked") + private static Stream[], Condition>> anyOfWithArrayFactories() { + return Stream.of(Assertions::anyOf, BDDAssertions::anyOf, withAssertions::anyOf); + } + + @ParameterizedTest + @MethodSource("anyOfWithCollectionFactories") + void should_create_anyOf_condition_from_condition_collection(Function>, Condition> anyOfFactory) { + // GIVEN + Condition condition1 = new TestCondition<>("condition 1"); + Condition condition2 = new TestCondition<>("condition 2"); + // WHEN + Condition anyOfCondition = anyOfFactory.apply(list(condition1, condition2)); + // THEN + then(anyOfCondition).isInstanceOf(AnyOf.class) + .extracting("conditions", as(ITERABLE)) + .containsExactly(condition1, condition2); + } + + private static Stream>, Condition>> anyOfWithCollectionFactories() { + return Stream.of(Assertions::anyOf, BDDAssertions::anyOf, withAssertions::anyOf); + } + +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_as_with_InstanceOfAssertFactory_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_as_with_InstanceOfAssertFactory_Test.java new file mode 100644 index 00000000000..4e32f629ccd --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_as_with_InstanceOfAssertFactory_Test.java @@ -0,0 +1,48 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.BDDAssertions.then; +import static org.mockito.Mockito.mock; + +import java.util.function.Function; +import java.util.stream.Stream; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * Tests for {@link Assertions#as(InstanceOfAssertFactory)}. + * + * @author Stefano Cordio + */ +@DisplayName("EntryPoint assertions as(InstanceOfAssertFactory) method") +class EntryPointAssertions_as_with_InstanceOfAssertFactory_Test extends EntryPointAssertionsBaseTest { + + @ParameterizedTest + @MethodSource("asInstanceOfAssertFactoryFactories") + void should_return_the_given_assert_factory(Function>, InstanceOfAssertFactory>> asInstanceOfAssertFactory) { + // GIVEN + InstanceOfAssertFactory> assertFactory = mock(InstanceOfAssertFactory.class); + // WHEN + InstanceOfAssertFactory> result = asInstanceOfAssertFactory.apply(assertFactory); + // THEN + then(result).isSameAs(assertFactory); + } + + private static Stream>, InstanceOfAssertFactory>>> asInstanceOfAssertFactoryFactories() { + return Stream.of(Assertions::as, BDDAssertions::as, withAssertions::as); + } + +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_atIndex_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_atIndex_Test.java new file mode 100644 index 00000000000..014213e953b --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_atIndex_Test.java @@ -0,0 +1,43 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.BDDAssertions.then; + +import java.util.function.Function; +import java.util.stream.Stream; + +import org.assertj.core.data.Index; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPoint assertions atIndex method") +class EntryPointAssertions_atIndex_Test extends EntryPointAssertionsBaseTest { + + @ParameterizedTest + @MethodSource("indexFactories") + void should_create_index(Function indexFactory) { + // GIVEN + int indexValue = 1; + // WHEN + Index index = indexFactory.apply(indexValue); + // THEN + then(index).isEqualTo(Index.atIndex(indexValue)); + } + + private static Stream> indexFactories() { + return Stream.of(Assertions::atIndex, BDDAssertions::atIndex, withAssertions::atIndex); + } + +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_byLessThan_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_byLessThan_Test.java new file mode 100644 index 00000000000..60bf436b5a2 --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_byLessThan_Test.java @@ -0,0 +1,171 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.data.Offset.strictOffset; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.time.temporal.ChronoUnit; +import java.time.temporal.TemporalUnit; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.stream.Stream; + +import org.assertj.core.data.Offset; +import org.assertj.core.data.TemporalUnitLessThanOffset; +import org.assertj.core.data.TemporalUnitOffset; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPoint assertions byLessThan method") +class EntryPointAssertions_byLessThan_Test extends EntryPointAssertionsBaseTest { + + @ParameterizedTest + @MethodSource("bigDecimalOffsetFactories") + void should_create_BigDecimal_strictOffset(Function> offsetFactory) { + // GIVEN + BigDecimal offsetValue = BigDecimal.ONE; + // WHEN + Offset index = offsetFactory.apply(offsetValue); + // THEN + then(index).isEqualTo(strictOffset(offsetValue)); + } + + private static Stream>> bigDecimalOffsetFactories() { + return Stream.of(Assertions::byLessThan, BDDAssertions::byLessThan, withAssertions::byLessThan); + } + + @ParameterizedTest + @MethodSource("bigIntegerOffsetFactories") + void should_create_BigInteger_strictOffset(Function> offsetFactory) { + // GIVEN + BigInteger offsetValue = BigInteger.ONE; + // WHEN + Offset index = offsetFactory.apply(offsetValue); + // THEN + then(index).isEqualTo(strictOffset(offsetValue)); + } + + private static Stream>> bigIntegerOffsetFactories() { + return Stream.of(Assertions::byLessThan, BDDAssertions::byLessThan, withAssertions::byLessThan); + } + + @ParameterizedTest + @MethodSource("byteOffsetFactories") + void should_create_Byte_strictOffset(Function> offsetFactory) { + // GIVEN + Byte offsetValue = Byte.MAX_VALUE; + // WHEN + Offset index = offsetFactory.apply(offsetValue); + // THEN + then(index).isEqualTo(strictOffset(offsetValue)); + } + + private static Stream>> byteOffsetFactories() { + return Stream.of(Assertions::byLessThan, BDDAssertions::byLessThan, withAssertions::byLessThan); + } + + @ParameterizedTest + @MethodSource("doubleOffsetFactories") + void should_create_Double_strictOffset(Function> offsetFactory) { + // GIVEN + Double offsetValue = Double.MAX_VALUE; + // WHEN + Offset index = offsetFactory.apply(offsetValue); + // THEN + then(index).isEqualTo(strictOffset(offsetValue)); + } + + private static Stream>> doubleOffsetFactories() { + return Stream.of(Assertions::byLessThan, BDDAssertions::byLessThan, withAssertions::byLessThan); + } + + @ParameterizedTest + @MethodSource("floatOffsetFactories") + void should_create_Float_strictOffset(Function> offsetFactory) { + // GIVEN + Float offsetValue = Float.MAX_VALUE; + // WHEN + Offset index = offsetFactory.apply(offsetValue); + // THEN + then(index).isEqualTo(strictOffset(offsetValue)); + } + + private static Stream>> floatOffsetFactories() { + return Stream.of(Assertions::byLessThan, BDDAssertions::byLessThan, withAssertions::byLessThan); + } + + @ParameterizedTest + @MethodSource("integerOffsetFactories") + void should_create_Integer_strictOffset(Function> offsetFactory) { + // GIVEN + Integer offsetValue = Integer.MAX_VALUE; + // WHEN + Offset index = offsetFactory.apply(offsetValue); + // THEN + then(index).isEqualTo(strictOffset(offsetValue)); + } + + private static Stream>> integerOffsetFactories() { + return Stream.of(Assertions::byLessThan, BDDAssertions::byLessThan, withAssertions::byLessThan); + } + + @ParameterizedTest + @MethodSource("longOffsetFactories") + void should_create_Long_strictOffset(Function> offsetFactory) { + // GIVEN + Long offsetValue = Long.MAX_VALUE; + // WHEN + Offset index = offsetFactory.apply(offsetValue); + // THEN + then(index).isEqualTo(strictOffset(offsetValue)); + } + + private static Stream>> longOffsetFactories() { + return Stream.of(Assertions::byLessThan, BDDAssertions::byLessThan, withAssertions::byLessThan); + } + + @ParameterizedTest + @MethodSource("temporalOffsetFactories") + void should_create_temporal_strictOffset(BiFunction offsetFactory) { + // GIVEN + Long value = Long.MAX_VALUE; + TemporalUnit temporalUnit = ChronoUnit.MINUTES; + // WHEN + TemporalUnitOffset index = offsetFactory.apply(value, temporalUnit); + // THEN + then(index).isEqualTo(new TemporalUnitLessThanOffset(value, temporalUnit)); + } + + private static Stream> temporalOffsetFactories() { + return Stream.of(Assertions::byLessThan, BDDAssertions::byLessThan, withAssertions::byLessThan); + } + + @ParameterizedTest + @MethodSource("shortOffsetFactories") + void should_create_Short_strictOffset(Function> offsetFactory) { + // GIVEN + Short offsetValue = Short.MAX_VALUE; + // WHEN + Offset index = offsetFactory.apply(offsetValue); + // THEN + then(index).isEqualTo(strictOffset(offsetValue)); + } + + private static Stream>> shortOffsetFactories() { + return Stream.of(Assertions::byLessThan, BDDAssertions::byLessThan, withAssertions::byLessThan); + } +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_catchThrowableOfType_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_catchThrowableOfType_Test.java new file mode 100644 index 00000000000..6422e48d8cb --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_catchThrowableOfType_Test.java @@ -0,0 +1,45 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.BDDAssertions.then; + +import java.util.function.BiFunction; +import java.util.stream.Stream; + +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +class EntryPointAssertions_catchThrowableOfType_Test extends EntryPointAssertionsBaseTest { + + private static final RuntimeException RUNTIME_EXCEPTION = new RuntimeException(); + + @ParameterizedTest + @MethodSource("catchThrowableOfTypes") + void should_catch_throwable_of_type(BiFunction, RuntimeException> catchThrowableOfType) { + // GIVEN + ThrowingCallable throwingCallable = () -> { + throw RUNTIME_EXCEPTION; + }; + // WHEN + RuntimeException throwable = catchThrowableOfType.apply(throwingCallable, RuntimeException.class); + // THEN + then(throwable).isSameAs(RUNTIME_EXCEPTION); + } + + private static Stream, RuntimeException>> catchThrowableOfTypes() { + return Stream.of(Assertions::catchThrowableOfType, BDDAssertions::catchThrowableOfType, withAssertions::catchThrowableOfType); + } + +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_catchThrowable_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_catchThrowable_Test.java new file mode 100644 index 00000000000..7ddad44c333 --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_catchThrowable_Test.java @@ -0,0 +1,47 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.BDDAssertions.then; + +import java.util.function.Function; +import java.util.stream.Stream; + +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPoint assertions catchThrowable method") +class EntryPointAssertions_catchThrowable_Test extends EntryPointAssertionsBaseTest { + + private static final RuntimeException RUNTIME_EXCEPTION = new RuntimeException(); + + @ParameterizedTest + @MethodSource("catchThrowables") + void should_catch_throwables(Function catchThrowable) { + // GIVEN + ThrowingCallable throwingCallable = () -> { + throw RUNTIME_EXCEPTION; + }; + // WHEN + Throwable throwable = catchThrowable.apply(throwingCallable); + // THEN + then(throwable).isSameAs(RUNTIME_EXCEPTION); + } + + private static Stream> catchThrowables() { + return Stream.of(Assertions::catchThrowable, BDDAssertions::catchThrowable, withAssertions::catchThrowable); + } + +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_contentOf_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_contentOf_Test.java new file mode 100644 index 00000000000..7f75a83f719 --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_contentOf_Test.java @@ -0,0 +1,122 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.assertj.core.api.BDDAssertions.then; + +import java.io.File; +import java.net.URL; +import java.nio.charset.Charset; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.stream.Stream; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPoint assertions contentOf method") +class EntryPointAssertions_contentOf_Test extends EntryPointAssertionsBaseTest { + + @ParameterizedTest + @MethodSource("fileContentOfWithCharsetFunctions") + void should_read_file_content_with_charset(BiFunction contentOfWithCharsetFunction) { + // GIVEN + File sampleFile = new File("src/test/resources/utf8.txt"); + // WHEN + String content = contentOfWithCharsetFunction.apply(sampleFile, UTF_8); + // THEN + then(content).isEqualTo("A text file encoded in UTF-8, with diacritics:\né à"); + } + + private static Stream> fileContentOfWithCharsetFunctions() { + return Stream.of(Assertions::contentOf, BDDAssertions::contentOf, withAssertions::contentOf); + } + + @ParameterizedTest + @MethodSource("fileContentOfWithCharsetAsStringFunctions") + void should_read_file_content_with_charset_as_string(BiFunction contentOfWithCharsetFunction) { + // GIVEN + File sampleFile = new File("src/test/resources/utf8.txt"); + // WHEN + String content = contentOfWithCharsetFunction.apply(sampleFile, "UTF8"); + // THEN + then(content).isEqualTo("A text file encoded in UTF-8, with diacritics:\né à"); + } + + private static Stream> fileContentOfWithCharsetAsStringFunctions() { + return Stream.of(Assertions::contentOf, BDDAssertions::contentOf, withAssertions::contentOf); + } + + @ParameterizedTest + @MethodSource("fileContentOfWithDefaultCharsetFunctions") + void should_read_file_content_with_default_charset(Function contentOfWithDefaultCharsetFunction) { + // GIVEN + File sampleFile = new File("src/test/resources/ascii.txt"); + // WHEN + String content = contentOfWithDefaultCharsetFunction.apply(sampleFile); + // THEN + then(content).isEqualTo("abc"); + } + + private static Stream> fileContentOfWithDefaultCharsetFunctions() { + return Stream.of(Assertions::contentOf, BDDAssertions::contentOf, withAssertions::contentOf); + } + + @ParameterizedTest + @MethodSource("urlContentOfWithCharsetFunctions") + void should_read_url_content_with_charset(BiFunction contentOfWithCharsetFunction) { + // GIVEN + URL sampleUrl = ClassLoader.getSystemResource("utf8.txt"); + // WHEN + String content = contentOfWithCharsetFunction.apply(sampleUrl, UTF_8); + // THEN + then(content).isEqualTo("A text file encoded in UTF-8, with diacritics:\né à"); + } + + private static Stream> urlContentOfWithCharsetFunctions() { + return Stream.of(Assertions::contentOf, BDDAssertions::contentOf, withAssertions::contentOf); + } + + @ParameterizedTest + @MethodSource("urlContentOfWithCharsetAsStringFunctions") + void should_read_url_content_with_charset_as_string(BiFunction contentOfWithCharsetFunction) { + // GIVEN + URL sampleUrl = ClassLoader.getSystemResource("utf8.txt"); + // WHEN + String content = contentOfWithCharsetFunction.apply(sampleUrl, "UTF8"); + // THEN + then(content).isEqualTo("A text file encoded in UTF-8, with diacritics:\né à"); + } + + private static Stream> urlContentOfWithCharsetAsStringFunctions() { + return Stream.of(Assertions::contentOf, BDDAssertions::contentOf, withAssertions::contentOf); + } + + @ParameterizedTest + @MethodSource("urlContentOfWithDefaultCharsetFunctions") + void should_read_URL_content_with_default_charset(Function contentOfWithDefaultCharsetFunction) { + // GIVEN + URL sampleUrl = ClassLoader.getSystemResource("ascii.txt"); + // WHEN + String content = contentOfWithDefaultCharsetFunction.apply(sampleUrl); + // THEN + then(content).isEqualTo("abc"); + } + + private static Stream> urlContentOfWithDefaultCharsetFunctions() { + return Stream.of(Assertions::contentOf, BDDAssertions::contentOf, withAssertions::contentOf); + } + +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_doesNotHave_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_doesNotHave_Test.java new file mode 100644 index 00000000000..9e910ddff4a --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_doesNotHave_Test.java @@ -0,0 +1,45 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.BDDAssertions.then; + +import java.util.function.Function; +import java.util.stream.Stream; + +import org.assertj.core.condition.DoesNotHave; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPoint assertions doesNotHave method") +class EntryPointAssertions_doesNotHave_Test extends EntryPointAssertionsBaseTest { + + @ParameterizedTest + @MethodSource("doesNotHaveFactories") + void should_create_allOf_condition_from_condition_array(Function, DoesNotHave> doesNotHaveFactory) { + // GIVEN + Condition condition = new TestCondition<>("condition"); + // WHEN + DoesNotHave doesNotHave = doesNotHaveFactory.apply(condition); + // THEN + then(doesNotHave).extracting("condition") + .isEqualTo(condition); + + } + + private static Stream, DoesNotHave>> doesNotHaveFactories() { + return Stream.of(Assertions::doesNotHave, BDDAssertions::doesNotHave, withAssertions::doesNotHave); + } + +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_entry_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_entry_Test.java new file mode 100644 index 00000000000..99c9f5ed242 --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_entry_Test.java @@ -0,0 +1,45 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.data.MapEntry.entry; + +import java.util.function.BiFunction; +import java.util.stream.Stream; + +import org.assertj.core.data.MapEntry; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPoint assertions entry method") +class EntryPointAssertions_entry_Test extends EntryPointAssertionsBaseTest { + + @ParameterizedTest + @MethodSource("entryFactories") + void should_create_entry(BiFunction> entryFactory) { + // GIVEN + String key = "key"; + String value = "value"; + // WHEN + MapEntry entry = entryFactory.apply(key, value); + // THEN + then(entry).isEqualTo(entry(key, value)); + } + + private static Stream>> entryFactories() { + return Stream.of(Assertions::entry, BDDAssertions::entry, withAssertions::entry); + } + +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_extractProperties_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_extractProperties_Test.java new file mode 100644 index 00000000000..ef05cf76f37 --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_extractProperties_Test.java @@ -0,0 +1,61 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.BDDAssertions.then; + +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.stream.Stream; + +import org.assertj.core.groups.Properties; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPoint assertions extractProperty method") +class EntryPointAssertions_extractProperties_Test extends EntryPointAssertionsBaseTest { + + @ParameterizedTest + @MethodSource("extractPropertiesFunctions") + void should_create_Properties(Function> extractPropertiesFunction) { + // GIVEN + String property = "name"; + // WHEN + Properties properties = extractPropertiesFunction.apply(property); + // THEN + then(properties).extracting("propertyName") + .isEqualTo(property); + } + + private static Stream>> extractPropertiesFunctions() { + return Stream.of(Assertions::extractProperty, BDDAssertions::extractProperty, withAssertions::extractProperty); + } + + @ParameterizedTest + @MethodSource("extractTypedPropertiesFunctions") + void should_create_strongly_typed_Properties(BiFunction, Properties> extractTypedPropertiesFunction) { + // GIVEN + String property = "name"; + // WHEN + Properties properties = extractTypedPropertiesFunction.apply(property, String.class); + // THEN + then(properties).extracting("propertyName") + .isEqualTo(property); + } + + private static Stream, Properties>> extractTypedPropertiesFunctions() { + return Stream.of(Assertions::extractProperty, BDDAssertions::extractProperty, withAssertions::extractProperty); + } + +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_fail_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_fail_Test.java new file mode 100644 index 00000000000..9a53d08d9c7 --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_fail_Test.java @@ -0,0 +1,93 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.util.Arrays.array; +import static org.assertj.core.util.AssertionsUtil.expectAssertionError; + +import java.util.Optional; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.stream.Stream; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPoint assertions fail method") +class EntryPointAssertions_fail_Test extends EntryPointAssertionsBaseTest { + + @ParameterizedTest + @MethodSource("failFunctions") + void should_fail_with_given_message(Function failFunction) { + // GIVEN + String message = "boom!"; + // WHEN + AssertionError assertionError = expectAssertionError(() -> failFunction.apply(message)); + // THEN + then(assertionError).hasMessage(message); + } + + private static Stream> failFunctions() { + return Stream.of(Assertions::fail, BDDAssertions::fail, withAssertions::fail); + } + + @ParameterizedTest + @MethodSource("failWithParamFunctions") + void should_fail_with_given_message_formatted_with_arguments(BiFunction failWithParamFunction) { + // GIVEN + String message = "%sm!"; + // WHEN + AssertionError assertionError = expectAssertionError(() -> failWithParamFunction.apply(message, array("boo"))); + // THEN + then(assertionError).hasMessage("boom!"); + } + + private static Stream> failWithParamFunctions() { + return Stream.of(Assertions::fail, BDDAssertions::fail, withAssertions::fail); + } + + @ParameterizedTest + @MethodSource("failWithCauseFunctions") + void should_fail_with_given_message_with_cause(BiFunction failWithCauseFunction) { + // GIVEN + String message = "boom!"; + Throwable cause = new NullPointerException(); + // WHEN + AssertionError assertionError = expectAssertionError(() -> failWithCauseFunction.apply(message, cause)); + // THEN + then(assertionError).hasMessage("boom!") + .hasCause(cause); + } + + private static Stream> failWithCauseFunctions() { + return Stream.of(Assertions::fail, BDDAssertions::fail, withAssertions::fail); + } + + @ParameterizedTest + @MethodSource("failFunctions") + void should_return_a_value_to_allow_using_optional_orElseGet(Function failFunction) { + // GIVEN + String message = "boom!"; + Optional empty = Optional.empty(); + // WHEN + AssertionError assertionError = expectAssertionError(() -> doSomethingWithInt(empty.orElseGet(() -> failFunction.apply(message)))); + // THEN + then(assertionError).hasMessage("boom!"); + } + + private void doSomethingWithInt(@SuppressWarnings("unused") int parameter) { + // just to illustrate the previous test + } +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_from_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_from_Test.java new file mode 100644 index 00000000000..c2f1b358ebd --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_from_Test.java @@ -0,0 +1,42 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.BDDAssertions.then; + +import java.util.function.Function; +import java.util.stream.Stream; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPoint assertions from method") +class EntryPointAssertions_from_Test extends EntryPointAssertionsBaseTest { + + @ParameterizedTest + @MethodSource("fromFunctions") + void should_return_same_function(Function, Function> fromFunction) { + // GIVEN + Function identity = t -> t; + // WHEN + Function fromResult = fromFunction.apply(identity); + // THEN + then(fromResult).isSameAs(identity); + } + + private static Stream, Function>> fromFunctions() { + return Stream.of(Assertions::from, BDDAssertions::from, withAssertions::from); + } + +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_in_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_in_Test.java new file mode 100644 index 00000000000..ce20e289c82 --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_in_Test.java @@ -0,0 +1,44 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.BDDAssertions.then; + +import java.util.function.Function; +import java.util.stream.Stream; + +import org.assertj.core.api.filter.InFilter; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPoint assertions in filter method") +class EntryPointAssertions_in_Test extends EntryPointAssertionsBaseTest { + + @ParameterizedTest + @MethodSource("inFunctions") + void should_create_allOf_condition_from_condition_array(Function inFunction) { + // GIVEN + String[] names = { "joe", "jack" }; + // WHEN + InFilter inFilter = inFunction.apply(names); + // THEN + then(inFilter).extracting("filterParameter") + .isEqualTo(names); + } + + private static Stream> inFunctions() { + return Stream.of(Assertions::in, BDDAssertions::in, withAssertions::in); + } + +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_linesOf_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_linesOf_Test.java new file mode 100644 index 00000000000..ac2c2752530 --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_linesOf_Test.java @@ -0,0 +1,123 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.assertj.core.api.BDDAssertions.then; + +import java.io.File; +import java.net.URL; +import java.nio.charset.Charset; +import java.util.List; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.stream.Stream; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPoint assertions linesOf method") +class EntryPointAssertionsOf_linesOf_Test extends EntryPointAssertionsBaseTest { + + @ParameterizedTest + @MethodSource("fileLinesOfWithCharsetFunctions") + void should_read_file_lines_with_charset(BiFunction> linesOfWithCharsetFunction) { + // GIVEN + File sampleFile = new File("src/test/resources/utf8.txt"); + // WHEN + List lines = linesOfWithCharsetFunction.apply(sampleFile, UTF_8); + // THEN + then(lines).containsExactly("A text file encoded in UTF-8, with diacritics:", "é à"); + } + + private static Stream>> fileLinesOfWithCharsetFunctions() { + return Stream.of(Assertions::linesOf, BDDAssertions::linesOf, withAssertions::linesOf); + } + + @ParameterizedTest + @MethodSource("fileLinesOfWithCharsetAsStringFunctions") + void should_read_file_lines_with_charset_as_string(BiFunction> linesOfWithCharsetFunction) { + // GIVEN + File sampleFile = new File("src/test/resources/utf8.txt"); + // WHEN + List lines = linesOfWithCharsetFunction.apply(sampleFile, "UTF8"); + // THEN + then(lines).containsExactly("A text file encoded in UTF-8, with diacritics:", "é à"); + } + + private static Stream>> fileLinesOfWithCharsetAsStringFunctions() { + return Stream.of(Assertions::linesOf, BDDAssertions::linesOf, withAssertions::linesOf); + } + + @ParameterizedTest + @MethodSource("fileLinesOfWithDefaultCharsetFunctions") + void should_read_file_lines_with_default_charset(Function> linesOfWithDefaultCharsetFunction) { + // GIVEN + File sampleFile = new File("src/test/resources/ascii.txt"); + // WHEN + List lines = linesOfWithDefaultCharsetFunction.apply(sampleFile); + // THEN + then(lines).containsExactly("abc"); + } + + private static Stream>> fileLinesOfWithDefaultCharsetFunctions() { + return Stream.of(Assertions::linesOf, BDDAssertions::linesOf, withAssertions::linesOf); + } + + @ParameterizedTest + @MethodSource("urlLinesOfWithCharsetFunctions") + void should_read_url_lines_with_charset(BiFunction> linesOfWithCharsetFunction) { + // GIVEN + URL sampleUrl = ClassLoader.getSystemResource("utf8.txt"); + // WHEN + List lines = linesOfWithCharsetFunction.apply(sampleUrl, UTF_8); + // THEN + then(lines).containsExactly("A text file encoded in UTF-8, with diacritics:", "é à"); + } + + private static Stream>> urlLinesOfWithCharsetFunctions() { + return Stream.of(Assertions::linesOf, BDDAssertions::linesOf, withAssertions::linesOf); + } + + @ParameterizedTest + @MethodSource("urlLinesOfWithCharsetAsStringFunctions") + void should_read_url_lines_with_charset_as_string(BiFunction> linesOfWithCharsetFunction) { + // GIVEN + URL sampleUrl = ClassLoader.getSystemResource("utf8.txt"); + // WHEN + List lines = linesOfWithCharsetFunction.apply(sampleUrl, "UTF8"); + // THEN + then(lines).containsExactly("A text file encoded in UTF-8, with diacritics:", "é à"); + } + + private static Stream>> urlLinesOfWithCharsetAsStringFunctions() { + return Stream.of(Assertions::linesOf, BDDAssertions::linesOf, withAssertions::linesOf); + } + + @ParameterizedTest + @MethodSource("urlLinesOfWithDefaultCharsetFunctions") + void should_read_URL_lines_with_default_charset(Function> linesOfWithDefaultCharsetFunction) { + // GIVEN + URL sampleUrl = ClassLoader.getSystemResource("ascii.txt"); + // WHEN + List lines = linesOfWithDefaultCharsetFunction.apply(sampleUrl); + // THEN + then(lines).containsExactly("abc"); + } + + private static Stream>> urlLinesOfWithDefaultCharsetFunctions() { + return Stream.of(Assertions::linesOf, BDDAssertions::linesOf, withAssertions::linesOf); + } + +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_notCondition_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_notCondition_Test.java new file mode 100644 index 00000000000..51bc7132c67 --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_notCondition_Test.java @@ -0,0 +1,45 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.BDDAssertions.then; + +import java.util.function.Function; +import java.util.stream.Stream; + +import org.assertj.core.condition.Not; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPoint assertions not condition method") +class EntryPointAssertions_notCondition_Test extends EntryPointAssertionsBaseTest { + + @ParameterizedTest + @MethodSource("notFactories") + void should_create_allOf_condition_from_condition_array(Function, Not> notFactory) { + // GIVEN + Condition condition = new TestCondition<>("condition"); + // WHEN + Not not = notFactory.apply(condition); + // THEN + then(not).extracting("condition") + .isEqualTo(condition); + + } + + private static Stream, Not>> notFactories() { + return Stream.of(Assertions::not, BDDAssertions::not, withAssertions::not); + } + +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_notIn_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_notIn_Test.java new file mode 100644 index 00000000000..01524839fe6 --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_notIn_Test.java @@ -0,0 +1,44 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.BDDAssertions.then; + +import java.util.function.Function; +import java.util.stream.Stream; + +import org.assertj.core.api.filter.NotInFilter; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPoint assertions notIn filter method") +class EntryPointAssertions_notIn_Test extends EntryPointAssertionsBaseTest { + + @ParameterizedTest + @MethodSource("notInFunctions") + void should_create_allOf_condition_from_condition_array(Function notInFunction) { + // GIVEN + String[] names = { "joe", "jack" }; + // WHEN + NotInFilter notInFilter = notInFunction.apply(names); + // THEN + then(notInFilter).extracting("filterParameter") + .isEqualTo(names); + } + + private static Stream> notInFunctions() { + return Stream.of(Assertions::notIn, BDDAssertions::notIn, withAssertions::notIn); + } + +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_not_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_not_Test.java new file mode 100644 index 00000000000..06e788281db --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_not_Test.java @@ -0,0 +1,44 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.BDDAssertions.then; + +import java.util.function.Function; +import java.util.stream.Stream; + +import org.assertj.core.api.filter.NotFilter; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPoint assertions not filter method") +class EntryPointAssertions_not_Test extends EntryPointAssertionsBaseTest { + + @ParameterizedTest + @MethodSource("notFunctions") + void should_create_allOf_condition_from_condition_array(Function notFunction) { + // GIVEN + String name = "joe"; + // WHEN + NotFilter notFilter = notFunction.apply(name); + // THEN + then(notFilter).extracting("filterParameter") + .isEqualTo(name); + } + + private static Stream> notFunctions() { + return Stream.of(Assertions::not, BDDAssertions::not, withAssertions::not); + } + +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_registerDateFormat_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_registerDateFormat_Test.java new file mode 100644 index 00000000000..fedda63896c --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_registerDateFormat_Test.java @@ -0,0 +1,76 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.BDDAssertions.then; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.function.Consumer; +import java.util.stream.Stream; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPoint assertions registerCustomDateFormat method") +class EntryPointAssertions_registerDateFormat_Test extends EntryPointAssertionsBaseTest { + + @BeforeEach + void beforeEachTest() { + // reset to the default value to avoid side effects on the other tests + AbstractDateAssert.useDefaultDateFormatsOnly(); + } + + @AfterEach + void afterEachTest() { + // reset to the default value to avoid side effects on the other tests + AbstractDateAssert.useDefaultDateFormatsOnly(); + } + + @ParameterizedTest + @MethodSource("registerCustomDateFormatFunctions") + void should_register_DateFormat(Consumer registerCustomDateFormatFunction) { + // GIVEN + DateFormat dateFormat = new SimpleDateFormat(); + // WHEN + registerCustomDateFormatFunction.accept(dateFormat); + // THEN + then(AbstractDateAssert.userDateFormats.get()).hasSize(1); + } + + private static Stream> registerCustomDateFormatFunctions() { + return Stream.of(Assertions::registerCustomDateFormat, + BDDAssertions::registerCustomDateFormat, + withAssertions::registerCustomDateFormat); + } + + @ParameterizedTest + @MethodSource("registerCustomDateFormatAsStringFunctions") + void should_register_DateFormat_as_string(Consumer registerCustomDateFormatFunction) { + // GIVEN + String dateFormatAsString = "yyyyddMM"; + // WHEN + registerCustomDateFormatFunction.accept(dateFormatAsString); + // THEN + then(AbstractDateAssert.userDateFormats.get()).hasSize(1); + } + + private static Stream> registerCustomDateFormatAsStringFunctions() { + return Stream.of(Assertions::registerCustomDateFormat, + BDDAssertions::registerCustomDateFormat, + withAssertions::registerCustomDateFormat); + } +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_registerFormatterForType_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_registerFormatterForType_Test.java new file mode 100644 index 00000000000..9fa84479cdb --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_registerFormatterForType_Test.java @@ -0,0 +1,51 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static java.lang.String.format; +import static org.assertj.core.api.BDDAssertions.then; + +import java.util.function.BiConsumer; +import java.util.function.Function; +import java.util.stream.Stream; + +import org.assertj.core.presentation.StandardRepresentation; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPoint assertions registerFormatterForType method") +class EntryPointAssertions_registerFormatterForType_Test extends EntryPointAssertionsBaseTest { + + @AfterEach + void afterEachTest() { + StandardRepresentation.removeAllRegisteredFormatters(); + } + + @ParameterizedTest + @MethodSource("registerFormatterForTypeFunctions") + void should_register_DateFormat(BiConsumer, Function> registerFormatterForTypeFunction) { + // WHEN + registerFormatterForTypeFunction.accept(Long.class, l -> format("%s long", l)); + // THEN + then(StandardRepresentation.STANDARD_REPRESENTATION.toStringOf(3L)).isEqualTo("3 long"); + } + + private static Stream, Function>> registerFormatterForTypeFunctions() { + return Stream.of(Assertions::registerFormatterForType, + BDDAssertions::registerFormatterForType, + withAssertions::registerFormatterForType); + } + +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_setAllowComparingPrivateFields_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_setAllowComparingPrivateFields_Test.java new file mode 100644 index 00000000000..f97915adfbf --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_setAllowComparingPrivateFields_Test.java @@ -0,0 +1,54 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.BDDAssertions.then; + +import java.util.function.Consumer; +import java.util.stream.Stream; + +import org.assertj.core.util.introspection.FieldSupport; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPoint assertions setAllowComparingPrivateFields method") +class EntryPointAssertions_setAllowComparingPrivateFields_Test extends EntryPointAssertionsBaseTest { + + private static final boolean DEFAULT_ALLOW_COMPARING_PRIVATE_FIELDS = FieldSupport.comparison().isAllowedToUsePrivateFields(); + + @AfterEach + void afterEachTest() { + // reset to the default value to avoid side effects on the other tests + FieldSupport.comparison().setAllowUsingPrivateFields(DEFAULT_ALLOW_COMPARING_PRIVATE_FIELDS); + } + + @ParameterizedTest + @MethodSource("setAllowComparingPrivateFieldsFunctions") + void should_set_allowComparingPrivateFields_value(Consumer setAllowComparingPrivateFieldsFunction) { + // GIVEN + boolean allowComparingPrivateFields = !DEFAULT_ALLOW_COMPARING_PRIVATE_FIELDS; + // WHEN + setAllowComparingPrivateFieldsFunction.accept(allowComparingPrivateFields); + // THEN + then(FieldSupport.comparison().isAllowedToUsePrivateFields()).isEqualTo(allowComparingPrivateFields); + } + + private static Stream> setAllowComparingPrivateFieldsFunctions() { + return Stream.of(Assertions::setAllowComparingPrivateFields, + BDDAssertions::setAllowComparingPrivateFields, + withAssertions::setAllowComparingPrivateFields); + } + +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_setAllowExtractingPrivateFields_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_setAllowExtractingPrivateFields_Test.java new file mode 100644 index 00000000000..c48b65a90d4 --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_setAllowExtractingPrivateFields_Test.java @@ -0,0 +1,54 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.BDDAssertions.then; + +import java.util.function.Consumer; +import java.util.stream.Stream; + +import org.assertj.core.util.introspection.FieldSupport; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPoint assertions setAllowExtractingPrivateFields method") +class EntryPointAssertions_setAllowExtractingPrivateFields_Test extends EntryPointAssertionsBaseTest { + + private static final boolean DEFAULT_ALLOW_EXTRACTING_PRIVATE_FIELDS = FieldSupport.comparison().isAllowedToUsePrivateFields(); + + @AfterEach + void afterEachTest() { + // reset to the default value to avoid side effects on the other tests + FieldSupport.extraction().setAllowUsingPrivateFields(DEFAULT_ALLOW_EXTRACTING_PRIVATE_FIELDS); + } + + @ParameterizedTest + @MethodSource("setAllowExtractingPrivateFieldsFunctions") + void should_set_allowComparingPrivateFields_value(Consumer setAllowExtractingPrivateFieldsFunction) { + // GIVEN + boolean allowComparingPrivateFields = !DEFAULT_ALLOW_EXTRACTING_PRIVATE_FIELDS; + // WHEN + setAllowExtractingPrivateFieldsFunction.accept(allowComparingPrivateFields); + // THEN + then(FieldSupport.extraction().isAllowedToUsePrivateFields()).isEqualTo(allowComparingPrivateFields); + } + + private static Stream> setAllowExtractingPrivateFieldsFunctions() { + return Stream.of(Assertions::setAllowExtractingPrivateFields, + BDDAssertions::setAllowExtractingPrivateFields, + withAssertions::setAllowExtractingPrivateFields); + } + +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_setExtractBareNamePropertyMethods_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_setExtractBareNamePropertyMethods_Test.java new file mode 100644 index 00000000000..6b2eb9dca72 --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_setExtractBareNamePropertyMethods_Test.java @@ -0,0 +1,54 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.BDDAssertions.then; + +import java.util.function.Consumer; +import java.util.stream.Stream; + +import org.assertj.core.util.introspection.Introspection; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPoint assertions setExtractBareNamePropertyMethods method") +class EntryPointAssertions_setExtractBareNamePropertyMethods_Test extends EntryPointAssertionsBaseTest { + + private static final boolean DEFAULT_EXTRACTING_BARE_NAME_PROPERTY_METHODS = Introspection.canExtractBareNamePropertyMethods(); + + @AfterEach + void afterEachTest() { + // reset to the default value to avoid side effects on the other tests + Introspection.setExtractBareNamePropertyMethods(DEFAULT_EXTRACTING_BARE_NAME_PROPERTY_METHODS); + } + + @ParameterizedTest + @MethodSource("setAllowExtractingBareNamePropertyMethodsFunctions") + void should_set_allowComparingPrivateFields_value(Consumer setAllowExtractingBareNamePropertyMethodsFunction) { + // GIVEN + boolean extractBareNamePropertyMethods = !DEFAULT_EXTRACTING_BARE_NAME_PROPERTY_METHODS; + // WHEN + setAllowExtractingBareNamePropertyMethodsFunction.accept(extractBareNamePropertyMethods); + // THEN + then(Introspection.canExtractBareNamePropertyMethods()).isEqualTo(extractBareNamePropertyMethods); + } + + private static Stream> setAllowExtractingBareNamePropertyMethodsFunctions() { + return Stream.of(Assertions::setExtractBareNamePropertyMethods, + BDDAssertions::setExtractBareNamePropertyMethods, + withAssertions::setExtractBareNamePropertyMethods); + } + +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_setLenientDateParsing_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_setLenientDateParsing_Test.java new file mode 100644 index 00000000000..2b80538fadd --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_setLenientDateParsing_Test.java @@ -0,0 +1,50 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.BDDAssertions.then; + +import java.text.DateFormat; +import java.util.function.Consumer; +import java.util.stream.Stream; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPoint assertions setLenientDateParsing method") +class EntryPointAssertions_setLenientDateParsing_Test extends EntryPointAssertionsBaseTest { + + @AfterEach + void afterEachTest() { + // reset to the default value to avoid side effects on the other tests + AbstractDateAssert.setLenientDateParsing(false); + } + + @ParameterizedTest + @MethodSource("setLenientDateParsingFunctions") + void should_setLenientDateParsing(Consumer setLenientDateParsingFunction) { + // WHEN + setLenientDateParsingFunction.accept(true); + // THEN + then(AbstractDateAssert.DEFAULT_DATE_FORMATS).allMatch(DateFormat::isLenient); + } + + private static Stream> setLenientDateParsingFunctions() { + return Stream.of(Assertions::setLenientDateParsing, + BDDAssertions::setLenientDateParsing, + withAssertions::setLenientDateParsing); + } + +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_setMaxElementsForPrinting_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_setMaxElementsForPrinting_Test.java new file mode 100644 index 00000000000..a124e9f09a5 --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_setMaxElementsForPrinting_Test.java @@ -0,0 +1,54 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.BDDAssertions.then; + +import java.util.function.Consumer; +import java.util.stream.Stream; + +import org.assertj.core.presentation.StandardRepresentation; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPoint assertions setMaxElementsForPrinting method") +class EntryPointAssertions_setMaxElementsForPrinting_Test extends EntryPointAssertionsBaseTest { + + private static final int DEFAULT_MAX_ELEMENTS_FOR_PRINTING = StandardRepresentation.getMaxElementsForPrinting(); + + @AfterEach + void afterEachTest() { + // reset to the default value to avoid side effects on the other tests + StandardRepresentation.setMaxElementsForPrinting(DEFAULT_MAX_ELEMENTS_FOR_PRINTING); + } + + @ParameterizedTest + @MethodSource("setMaxElementsForPrintingFunctions") + void should_set_maxElementsForPrinting_value(Consumer setMaxElementsForPrintingFunction) { + // GIVEN + int maxElementsForPrinting = DEFAULT_MAX_ELEMENTS_FOR_PRINTING + 1; + // WHEN + setMaxElementsForPrintingFunction.accept(maxElementsForPrinting); + // THEN + then(StandardRepresentation.getMaxElementsForPrinting()).isEqualTo(maxElementsForPrinting); + } + + private static Stream> setMaxElementsForPrintingFunctions() { + return Stream.of(Assertions::setMaxElementsForPrinting, + BDDAssertions::setMaxElementsForPrinting, + withAssertions::setMaxElementsForPrinting); + } + +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_setMaxLengthForSingleLineDescription_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_setMaxLengthForSingleLineDescription_Test.java new file mode 100644 index 00000000000..bb5607ae69d --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_setMaxLengthForSingleLineDescription_Test.java @@ -0,0 +1,52 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.BDDAssertions.then; + +import java.util.function.Consumer; +import java.util.stream.Stream; + +import org.assertj.core.presentation.StandardRepresentation; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +class EntryPointAssertions_setMaxLengthForSingleLineDescription_Test extends EntryPointAssertionsBaseTest { + + private static final int DEFAULT_MAX_LENGTH_FOR_SINGLE_LINE = StandardRepresentation.getMaxLengthForSingleLineDescription(); + + @AfterEach + void afterEachTest() { + // reset to the default value to avoid side effects on the other tests + StandardRepresentation.setMaxLengthForSingleLineDescription(DEFAULT_MAX_LENGTH_FOR_SINGLE_LINE); + } + + @ParameterizedTest + @MethodSource("setMaxLengthForSingleLineDescriptionFunctions") + void should_set_maxLengthForSingleLineDescription_value(Consumer setMaxLengthForSingleLineDescriptionFunction) { + // GIVEN + int maxLengthForSingleLineDescription = DEFAULT_MAX_LENGTH_FOR_SINGLE_LINE + 1; + // WHEN + setMaxLengthForSingleLineDescriptionFunction.accept(maxLengthForSingleLineDescription); + // THEN + then(StandardRepresentation.getMaxLengthForSingleLineDescription()).isEqualTo(maxLengthForSingleLineDescription); + } + + private static Stream> setMaxLengthForSingleLineDescriptionFunctions() { + return Stream.of(Assertions::setMaxLengthForSingleLineDescription, + BDDAssertions::setMaxLengthForSingleLineDescription, + withAssertions::setMaxLengthForSingleLineDescription); + } + +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_setMaxStackTraceElementsDisplayed_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_setMaxStackTraceElementsDisplayed_Test.java new file mode 100644 index 00000000000..6c9b97c6702 --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_setMaxStackTraceElementsDisplayed_Test.java @@ -0,0 +1,54 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.BDDAssertions.then; + +import java.util.function.Consumer; +import java.util.stream.Stream; + +import org.assertj.core.presentation.StandardRepresentation; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPoint assertions setMaxStackTraceElementsDisplayed method") +class EntryPointAssertions_setMaxStackTraceElementsDisplayed_Test extends EntryPointAssertionsBaseTest { + + private static final int DEFAULT_MAX_STACK_TRACE_ELEMENTS_DISPLAYED = StandardRepresentation.getMaxStackTraceElementsDisplayed(); + + @AfterEach + void afterEachTest() { + // reset to the default value to avoid side effects on the other tests + StandardRepresentation.setMaxStackTraceElementsDisplayed(DEFAULT_MAX_STACK_TRACE_ELEMENTS_DISPLAYED); + } + + @ParameterizedTest + @MethodSource("setMaxStackTraceElementsDisplayedFunctions") + void should_set_maxStackTraceElementsDisplayed_value(Consumer setMaxStackTraceElementsDisplayedFunction) { + // GIVEN + int maxStackTraceElementsDisplayed = DEFAULT_MAX_STACK_TRACE_ELEMENTS_DISPLAYED + 1; + // WHEN + setMaxStackTraceElementsDisplayedFunction.accept(maxStackTraceElementsDisplayed); + // THEN + then(StandardRepresentation.getMaxStackTraceElementsDisplayed()).isEqualTo(maxStackTraceElementsDisplayed); + } + + private static Stream> setMaxStackTraceElementsDisplayedFunctions() { + return Stream.of(Assertions::setMaxStackTraceElementsDisplayed, + BDDAssertions::setMaxStackTraceElementsDisplayed, + withAssertions::setMaxStackTraceElementsDisplayed); + } + +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_setPrintAssertionsDescription_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_setPrintAssertionsDescription_Test.java new file mode 100644 index 00000000000..c80984554b4 --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_setPrintAssertionsDescription_Test.java @@ -0,0 +1,53 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.BDDAssertions.then; + +import java.util.function.Consumer; +import java.util.stream.Stream; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPoint assertions setPrintAssertionsDescription method") +class EntryPointAssertions_setPrintAssertionsDescription_Test extends EntryPointAssertionsBaseTest { + + private static final boolean DEFAULT_EXTRACTING_BARE_NAME_PROPERTY_METHODS = AbstractAssert.printAssertionsDescription; + + @AfterEach + void afterEachTest() { + // reset to the default value to avoid side effects on the other tests + AbstractAssert.printAssertionsDescription = DEFAULT_EXTRACTING_BARE_NAME_PROPERTY_METHODS; + } + + @ParameterizedTest + @MethodSource("setPrintAssertionsDescriptionMethodsFunctions") + void should_set_printAssertionsDescription_value(Consumer setPrintAssertionsDescriptionMethodsFunction) { + // GIVEN + boolean printAssertionsDescription = !DEFAULT_EXTRACTING_BARE_NAME_PROPERTY_METHODS; + // WHEN + setPrintAssertionsDescriptionMethodsFunction.accept(printAssertionsDescription); + // THEN + then(AbstractAssert.printAssertionsDescription).isEqualTo(printAssertionsDescription); + } + + private static Stream> setPrintAssertionsDescriptionMethodsFunctions() { + return Stream.of(Assertions::setPrintAssertionsDescription, + BDDAssertions::setPrintAssertionsDescription, + WithAssertions::setPrintAssertionsDescription); + } + +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_setRemoveAssertJRelatedElementsFromStackTrace_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_setRemoveAssertJRelatedElementsFromStackTrace_Test.java new file mode 100644 index 00000000000..7b2df8154d4 --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_setRemoveAssertJRelatedElementsFromStackTrace_Test.java @@ -0,0 +1,55 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.BDDAssertions.then; + +import java.util.function.Consumer; +import java.util.stream.Stream; + +import org.assertj.core.internal.Failures; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPoint assertions setRemoveAssertJRelatedElementsFromStackTrace method") +class EntryPointAssertions_setRemoveAssertJRelatedElementsFromStackTrace_Test extends EntryPointAssertionsBaseTest { + + private static final Failures FAILURES = Failures.instance(); + private static final boolean DEFAULT_REMOVE_ASSERTJ_FROM_STACK_TRACE = FAILURES.isRemoveAssertJRelatedElementsFromStackTrace(); + + @AfterEach + void afterEachTest() { + // reset to the default value to avoid side effects on the other tests + FAILURES.setRemoveAssertJRelatedElementsFromStackTrace(DEFAULT_REMOVE_ASSERTJ_FROM_STACK_TRACE); + } + + @ParameterizedTest + @MethodSource("setRemoveAssertJRelatedElementsFromStackTraceMethodsFunctions") + void should_set_removeAssertJRelatedElementsFromStackTrace_value(Consumer setRemoveAssertJRelatedElementsFromStackTraceMethodsFunction) { + // GIVEN + boolean removeAssertJRelatedElementsFromStackTrace = !DEFAULT_REMOVE_ASSERTJ_FROM_STACK_TRACE; + // WHEN + setRemoveAssertJRelatedElementsFromStackTraceMethodsFunction.accept(removeAssertJRelatedElementsFromStackTrace); + // THEN + then(FAILURES.isRemoveAssertJRelatedElementsFromStackTrace()).isEqualTo(removeAssertJRelatedElementsFromStackTrace); + } + + private static Stream> setRemoveAssertJRelatedElementsFromStackTraceMethodsFunctions() { + return Stream.of(Assertions::setRemoveAssertJRelatedElementsFromStackTrace, + BDDAssertions::setRemoveAssertJRelatedElementsFromStackTrace, + withAssertions::setRemoveAssertJRelatedElementsFromStackTrace); + } + +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_shouldHaveThrown_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_shouldHaveThrown_Test.java new file mode 100644 index 00000000000..c1cb45b2d9d --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_shouldHaveThrown_Test.java @@ -0,0 +1,43 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.util.AssertionsUtil.expectAssertionError; + +import java.util.function.Function; +import java.util.stream.Stream; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPointAssertions shouldHaveThrown") +class EntryPointAssertions_shouldHaveThrown_Test extends EntryPointAssertionsBaseTest { + + @ParameterizedTest + @MethodSource("shouldHaveThrownFunction") + void should_throw_an_AssertionError_with_message_indicating_the_expected_excepion(Function, T> shouldHaveThrownFunction) { + // GIVEN + Class throwableClass = NullPointerException.class; + // WHEN + AssertionError assertionError = expectAssertionError(() -> shouldHaveThrownFunction.apply(throwableClass)); + // THEN + then(assertionError).hasMessage("NullPointerException should have been thrown"); + } + + private static Stream, T>> shouldHaveThrownFunction() { + return Stream.of(Assertions::shouldHaveThrown, BDDAssertions::shouldHaveThrown, withAssertions::shouldHaveThrown); + } + +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_tuple_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_tuple_Test.java new file mode 100644 index 00000000000..4721c76ba27 --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_tuple_Test.java @@ -0,0 +1,47 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.BDDAssertions.then; + +import java.util.function.Function; +import java.util.stream.Stream; + +import org.assertj.core.groups.Tuple; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPoint assertions tuple method") +class EntryPointAssertions_tuple_Test extends EntryPointAssertionsBaseTest { + + private static final int AGE = 800; + private static final String JEDI = "Jedi"; + private static final String YODA = "Yoda"; + + @ParameterizedTest + @MethodSource("tupleFactories") + void should_create_tuple(Function tupleFactory) { + // GIVEN + Object[] values = { YODA, AGE, JEDI }; + // WHEN + Tuple result = tupleFactory.apply(values); + // THEN + then(result).isEqualTo(new Tuple(YODA, AGE, JEDI)); + } + + private static Stream> tupleFactories() { + return Stream.of(Assertions::tuple, BDDAssertions::tuple, withAssertions::tuple); + } + +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_useDefaultDateFormatsOnly_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_useDefaultDateFormatsOnly_Test.java new file mode 100644 index 00000000000..4908b985822 --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_useDefaultDateFormatsOnly_Test.java @@ -0,0 +1,45 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.BDDAssertions.then; + +import java.util.function.Consumer; +import java.util.stream.Stream; + +import org.apache.commons.lang3.tuple.Pair; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPoint assertions useDefaultDateFormatsOnly method") +class EntryPointAssertions_useDefaultDateFormatsOnly_Test extends EntryPointAssertionsBaseTest { + + @ParameterizedTest + @MethodSource("useDefaultDateFormatsOnlyFunctions") + void should_set_default_DefaultDateFormatsOnly(Pair, Runnable> params) { + // GIVEN + params.getLeft().accept("yyyyddMM"); + then(AbstractDateAssert.userDateFormats.get()).hasSize(1); + // WHEN + params.getRight().run(); + // THEN + then(AbstractDateAssert.userDateFormats.get()).isEmpty(); + } + + private static Stream, Runnable>> useDefaultDateFormatsOnlyFunctions() { + return Stream.of(Pair.of(Assertions::registerCustomDateFormat, () -> Assertions.useDefaultDateFormatsOnly()), + Pair.of(BDDAssertions::registerCustomDateFormat, () -> BDDAssertions.useDefaultDateFormatsOnly()), + Pair.of(withAssertions::registerCustomDateFormat, () -> withAssertions.useDefaultDateFormatsOnly())); + } +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_useDefaultRepresentation_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_useDefaultRepresentation_Test.java new file mode 100644 index 00000000000..98d21555a9d --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_useDefaultRepresentation_Test.java @@ -0,0 +1,58 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.configuration.ConfigurationProvider.CONFIGURATION_PROVIDER; +import static org.assertj.core.presentation.HexadecimalRepresentation.HEXA_REPRESENTATION; + +import java.util.function.Consumer; +import java.util.stream.Stream; + +import org.apache.commons.lang3.tuple.Pair; +import org.assertj.core.presentation.Representation; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPoint assertions useDefaultRepresentation method") +class EntryPointAssertions_useDefaultRepresentation_Test extends EntryPointAssertionsBaseTest { + + private static final Representation DEFAULT_CUSTOM_REPRESENTATION = AbstractAssert.customRepresentation; + + @AfterEach + void afterEachTest() { + // reset to the default value to avoid side effects on the other tests + AbstractAssert.customRepresentation = DEFAULT_CUSTOM_REPRESENTATION; + } + + @ParameterizedTest + @MethodSource("useRepresentationFunctions") + void should_set_default_Representation(Pair, Runnable> params) { + // GIVEN + params.getLeft().accept(HEXA_REPRESENTATION); + // WHEN + params.getRight().run(); + // THEN + // TODO we don't go back to null representation, but shoud we? + then(AbstractAssert.customRepresentation).isEqualTo(CONFIGURATION_PROVIDER.representation()); + } + + private static Stream, Runnable>> useRepresentationFunctions() { + return Stream.of(Pair.of(Assertions::useRepresentation, () -> Assertions.useDefaultRepresentation()), + Pair.of(BDDAssertions::useRepresentation, () -> BDDAssertions.useDefaultRepresentation()), + Pair.of(withAssertions::useRepresentation, () -> withAssertions.useDefaultRepresentation())); + } + +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_useRepresentation_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_useRepresentation_Test.java new file mode 100644 index 00000000000..7d186d4c8df --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_useRepresentation_Test.java @@ -0,0 +1,55 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.presentation.HexadecimalRepresentation.HEXA_REPRESENTATION; + +import java.util.function.Consumer; +import java.util.stream.Stream; + +import org.assertj.core.presentation.Representation; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPoint assertions useRepresentation method") +class EntryPointAssertions_useRepresentation_Test extends EntryPointAssertionsBaseTest { + + private static final Representation DEFAULT_CUSTOM_REPRESENTATION = AbstractAssert.customRepresentation; + + @AfterEach + void afterEachTest() { + // reset to the default value to avoid side effects on the other tests + AbstractAssert.customRepresentation = DEFAULT_CUSTOM_REPRESENTATION; + } + + @ParameterizedTest + @MethodSource("useRepresentationFunctions") + void should_set_customRepresentation_value(Consumer useRepresentationFunction) { + // GIVEN + Representation customRepresentation = HEXA_REPRESENTATION; + // WHEN + useRepresentationFunction.accept(customRepresentation); + // THEN + then(AbstractAssert.customRepresentation).isEqualTo(customRepresentation); + } + + private static Stream> useRepresentationFunctions() { + return Stream.of(Assertions::useRepresentation, + BDDAssertions::useRepresentation, + withAssertions::useRepresentation); + } + +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_withMarginOf_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_withMarginOf_Test.java new file mode 100644 index 00000000000..a682a3d6750 --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_withMarginOf_Test.java @@ -0,0 +1,43 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.BDDAssertions.then; + +import java.time.Duration; +import java.util.function.Function; +import java.util.stream.Stream; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPoint assertions withMarginOf method") +class EntryPointAssertions_withMarginOf_Test extends EntryPointAssertionsBaseTest { + + @ParameterizedTest + @MethodSource("durationProviders") + void should_return_same_Duration(Function durationFactory) { + // GIVEN + Duration duration = Duration.ofHours(1); + // WHEN + Duration result = durationFactory.apply(duration); + // THEN + then(result).isSameAs(duration); + } + + private static Stream> durationProviders() { + return Stream.of(Assertions::withMarginOf, BDDAssertions::withMarginOf, withAssertions::withMarginOf); + } + +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_withPrecision_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_withPrecision_Test.java new file mode 100644 index 00000000000..69b015d54a7 --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_withPrecision_Test.java @@ -0,0 +1,59 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.data.Offset.offset; + +import java.util.function.Function; +import java.util.stream.Stream; + +import org.assertj.core.data.Offset; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPoint assertions withPrecision method") +class EntryPointAssertions_withPrecision_Test extends EntryPointAssertionsBaseTest { + + @ParameterizedTest + @MethodSource("doubleOffsetFactories") + void should_create_Double_offset(Function> withinFactory) { + // GIVEN + Double offsetValue = Double.MAX_VALUE; + // WHEN + Offset index = withinFactory.apply(offsetValue); + // THEN + then(index).isEqualTo(offset(offsetValue)); + } + + private static Stream>> doubleOffsetFactories() { + return Stream.of(Assertions::withPrecision, BDDAssertions::withPrecision, withAssertions::withPrecision); + } + + @ParameterizedTest + @MethodSource("floatOffsetFactories") + void should_create_Float_offset(Function> withinFactory) { + // GIVEN + Float offsetValue = Float.MAX_VALUE; + // WHEN + Offset index = withinFactory.apply(offsetValue); + // THEN + then(index).isEqualTo(offset(offsetValue)); + } + + private static Stream>> floatOffsetFactories() { + return Stream.of(Assertions::withPrecision, BDDAssertions::withPrecision, withAssertions::withPrecision); + } + +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_withinPercentage_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_withinPercentage_Test.java new file mode 100644 index 00000000000..560bdef86f0 --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_withinPercentage_Test.java @@ -0,0 +1,74 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.data.Percentage.withPercentage; + +import java.util.function.Function; +import java.util.stream.Stream; + +import org.assertj.core.data.Percentage; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPoint assertions withinPercentage method") +class EntryPointAssertions_withinPercentage_Test extends EntryPointAssertionsBaseTest { + + @ParameterizedTest + @MethodSource("doublePercentageFactories") + void should_create_Double_offset(Function percentageFactory) { + // GIVEN + Double value = 90.0; + // WHEN + Percentage percentage = percentageFactory.apply(value); + // THEN + then(percentage).isEqualTo(withPercentage(value)); + } + + private static Stream> doublePercentageFactories() { + return Stream.of(Assertions::withinPercentage, BDDAssertions::withinPercentage, withAssertions::withinPercentage); + } + + @ParameterizedTest + @MethodSource("integerPercentageFactories") + void should_create_Integer_offset(Function percentageFactory) { + // GIVEN + Integer value = 90; + // WHEN + Percentage percentage = percentageFactory.apply(value); + // THEN + then(percentage).isEqualTo(withPercentage(value)); + } + + private static Stream> integerPercentageFactories() { + return Stream.of(Assertions::withinPercentage, BDDAssertions::withinPercentage, withAssertions::withinPercentage); + } + + @ParameterizedTest + @MethodSource("longPercentageFactories") + void should_create_Long_offset(Function percentageFactory) { + // GIVEN + Long value = 90L; + // WHEN + Percentage percentage = percentageFactory.apply(value); + // THEN + then(percentage).isEqualTo(withPercentage(value)); + } + + private static Stream> longPercentageFactories() { + return Stream.of(Assertions::withinPercentage, BDDAssertions::withinPercentage, withAssertions::withinPercentage); + } + +} diff --git a/src/test/java/org/assertj/core/api/EntryPointAssertions_within_Test.java b/src/test/java/org/assertj/core/api/EntryPointAssertions_within_Test.java new file mode 100644 index 00000000000..bce5a699d9a --- /dev/null +++ b/src/test/java/org/assertj/core/api/EntryPointAssertions_within_Test.java @@ -0,0 +1,171 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.data.Offset.offset; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.time.temporal.ChronoUnit; +import java.time.temporal.TemporalUnit; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.stream.Stream; + +import org.assertj.core.data.Offset; +import org.assertj.core.data.TemporalUnitOffset; +import org.assertj.core.data.TemporalUnitWithinOffset; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@DisplayName("EntryPoint assertions within method") +class EntryPointAssertions_within_Test extends EntryPointAssertionsBaseTest { + + @ParameterizedTest + @MethodSource("bigDecimalOffsetFactories") + void should_create_BigDecimal_offset(Function> offsetFactory) { + // GIVEN + BigDecimal offsetValue = BigDecimal.ONE; + // WHEN + Offset index = offsetFactory.apply(offsetValue); + // THEN + then(index).isEqualTo(offset(offsetValue)); + } + + private static Stream>> bigDecimalOffsetFactories() { + return Stream.of(Assertions::within, BDDAssertions::within, withAssertions::within); + } + + @ParameterizedTest + @MethodSource("bigIntegerOffsetFactories") + void should_create_BigInteger_offset(Function> offsetFactory) { + // GIVEN + BigInteger offsetValue = BigInteger.ONE; + // WHEN + Offset index = offsetFactory.apply(offsetValue); + // THEN + then(index).isEqualTo(offset(offsetValue)); + } + + private static Stream>> bigIntegerOffsetFactories() { + return Stream.of(Assertions::within, BDDAssertions::within, withAssertions::within); + } + + @ParameterizedTest + @MethodSource("byteOffsetFactories") + void should_create_Byte_offset(Function> offsetFactory) { + // GIVEN + Byte offsetValue = Byte.MAX_VALUE; + // WHEN + Offset index = offsetFactory.apply(offsetValue); + // THEN + then(index).isEqualTo(offset(offsetValue)); + } + + private static Stream>> byteOffsetFactories() { + return Stream.of(Assertions::within, BDDAssertions::within, withAssertions::within); + } + + @ParameterizedTest + @MethodSource("doubleOffsetFactories") + void should_create_Double_offset(Function> offsetFactory) { + // GIVEN + Double offsetValue = Double.MAX_VALUE; + // WHEN + Offset index = offsetFactory.apply(offsetValue); + // THEN + then(index).isEqualTo(offset(offsetValue)); + } + + private static Stream>> doubleOffsetFactories() { + return Stream.of(Assertions::within, BDDAssertions::within, withAssertions::within); + } + + @ParameterizedTest + @MethodSource("floatOffsetFactories") + void should_create_Float_offset(Function> offsetFactory) { + // GIVEN + Float offsetValue = Float.MAX_VALUE; + // WHEN + Offset index = offsetFactory.apply(offsetValue); + // THEN + then(index).isEqualTo(offset(offsetValue)); + } + + private static Stream>> floatOffsetFactories() { + return Stream.of(Assertions::within, BDDAssertions::within, withAssertions::within); + } + + @ParameterizedTest + @MethodSource("integerOffsetFactories") + void should_create_Integer_offset(Function> offsetFactory) { + // GIVEN + Integer offsetValue = Integer.MAX_VALUE; + // WHEN + Offset index = offsetFactory.apply(offsetValue); + // THEN + then(index).isEqualTo(offset(offsetValue)); + } + + private static Stream>> integerOffsetFactories() { + return Stream.of(Assertions::within, BDDAssertions::within, withAssertions::within); + } + + @ParameterizedTest + @MethodSource("longOffsetFactories") + void should_create_Long_offset(Function> offsetFactory) { + // GIVEN + Long offsetValue = Long.MAX_VALUE; + // WHEN + Offset index = offsetFactory.apply(offsetValue); + // THEN + then(index).isEqualTo(offset(offsetValue)); + } + + private static Stream>> longOffsetFactories() { + return Stream.of(Assertions::within, BDDAssertions::within, withAssertions::within); + } + + @ParameterizedTest + @MethodSource("temporalOffsetFactories") + void should_create_temporal_offset(BiFunction offsetFactory) { + // GIVEN + Long value = Long.MAX_VALUE; + TemporalUnit temporalUnit = ChronoUnit.MINUTES; + // WHEN + TemporalUnitOffset index = offsetFactory.apply(value, temporalUnit); + // THEN + then(index).isEqualTo(new TemporalUnitWithinOffset(value, temporalUnit)); + } + + private static Stream> temporalOffsetFactories() { + return Stream.of(Assertions::within, BDDAssertions::within, withAssertions::within); + } + + @ParameterizedTest + @MethodSource("shortOffsetFactories") + void should_create_Short_offset(Function> offsetFactory) { + // GIVEN + Short offsetValue = Short.MAX_VALUE; + // WHEN + Offset index = offsetFactory.apply(offsetValue); + // THEN + then(index).isEqualTo(offset(offsetValue)); + } + + private static Stream>> shortOffsetFactories() { + return Stream.of(Assertions::within, BDDAssertions::within, withAssertions::within); + } +} diff --git a/src/test/java/org/assertj/core/api/Java6Assertions_sync_assertThat_with_BDD_and_Soft_variants_Test.java b/src/test/java/org/assertj/core/api/Java6Assertions_sync_assertThat_with_BDD_and_Soft_variants_Test.java index 154c39e31f0..1e2effd65ed 100644 --- a/src/test/java/org/assertj/core/api/Java6Assertions_sync_assertThat_with_BDD_and_Soft_variants_Test.java +++ b/src/test/java/org/assertj/core/api/Java6Assertions_sync_assertThat_with_BDD_and_Soft_variants_Test.java @@ -41,7 +41,7 @@ void standard_assertions_and_soft_assertions_should_have_the_same_assertions_met Method[] assertThatSoftMethods = findMethodsWithName(Java6StandardSoftAssertionsProvider.class, "assertThat"); // ignore the return type of soft assertions until they have the same as the Assertions - assertThat(assertThatMethods).usingElementComparator(IGNORING_DECLARING_CLASS_AND_RETURN_TYPE) + assertThat(assertThatMethods).usingElementComparator(IGNORING_DECLARING_CLASS_ONLY) .containsExactlyInAnyOrder(assertThatSoftMethods); } @@ -54,7 +54,7 @@ void bdd_assertions_and_bdd_soft_assertions_should_have_the_same_assertions_meth Method[] thenSoftMethods = findMethodsWithName(Java6BDDSoftAssertionsProvider.class, "then"); // ignore the return type of soft assertions until they have the same as the Assertions - assertThat(thenMethods).usingElementComparator(IGNORING_DECLARING_CLASS_AND_RETURN_TYPE) + assertThat(thenMethods).usingElementComparator(IGNORING_DECLARING_CLASS_ONLY) .containsExactlyInAnyOrder(thenSoftMethods); } diff --git a/src/test/java/org/assertj/core/api/MapAssertBaseTest.java b/src/test/java/org/assertj/core/api/MapAssertBaseTest.java index 6c3db7a3fd4..d2d99246ddf 100644 --- a/src/test/java/org/assertj/core/api/MapAssertBaseTest.java +++ b/src/test/java/org/assertj/core/api/MapAssertBaseTest.java @@ -13,16 +13,15 @@ package org.assertj.core.api; import static java.util.Collections.emptyMap; +import static java.util.Collections.singletonMap; import static org.mockito.Mockito.mock; import java.util.AbstractMap.SimpleImmutableEntry; -import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import org.assertj.core.internal.Maps; - /** * Base class for {@link MapAssert} tests. * @@ -43,15 +42,15 @@ protected void inject_internal_objects() { assertions.maps = maps; } - protected Map.Entry javaMapEntry(K key, V value) { + protected static Map.Entry javaMapEntry(K key, V value) { return new SimpleImmutableEntry<>(key, value); } - protected Map map(K key, V value) { - return Collections.singletonMap(key, value); + protected static Map map(K key, V value) { + return singletonMap(key, value); } - protected Map map(K k1, V v1, K k2, V v2) { + protected static Map map(K k1, V v1, K k2, V v2) { Map map = new LinkedHashMap<>(); map.put(k1, v1); map.put(k2, v2); diff --git a/src/test/java/org/assertj/core/api/SoftAssertionsTest.java b/src/test/java/org/assertj/core/api/SoftAssertionsTest.java index b949156791b..5ca83dfbf24 100644 --- a/src/test/java/org/assertj/core/api/SoftAssertionsTest.java +++ b/src/test/java/org/assertj/core/api/SoftAssertionsTest.java @@ -165,7 +165,6 @@ void all_assertions_should_pass() { softly.assertAll(); } - @SuppressWarnings("unchecked") @Test void should_be_able_to_catch_exceptions_thrown_by_map_assertions() { // GIVEN @@ -184,7 +183,7 @@ void should_be_able_to_catch_exceptions_thrown_by_map_assertions() { assertThat(errors.get(1)).hasMessageStartingWith(format("%nExpecting empty but was: {\"54\"=\"55\"}")); } - @SuppressWarnings({ "unchecked", "deprecation" }) + @SuppressWarnings({ "deprecation" }) @Test void should_be_able_to_catch_exceptions_thrown_by_all_proxied_methods() throws MalformedURLException { try { @@ -382,17 +381,17 @@ public String toString() { assertThat(errors.get(45)).contains(shouldBeEqualMessage("OptionalLong[0]", "1L")); assertThat(errors.get(46)).contains("Expecting port of"); assertThat(errors.get(47)).contains("to have failed"); - assertThat(errors.get(48)).contains(format("%nExpecting:%n given predicate%n" + assertThat(errors.get(48)).contains(format("%nExpecting actual:%n given predicate%n" + "to accept \"something else\" but it did not.")); - assertThat(errors.get(49)).contains(format("%nExpecting:%n given predicate%n" + assertThat(errors.get(49)).contains(format("%nExpecting actual:%n given predicate%n" + "to accept 2 but it did not.")); - assertThat(errors.get(50)).contains(format("%nExpecting:%n given predicate%n" + assertThat(errors.get(50)).contains(format("%nExpecting actual:%n given predicate%n" + "to accept 2L but it did not.")); - assertThat(errors.get(51)).contains(format("%nExpecting:%n given predicate%n" + assertThat(errors.get(51)).contains(format("%nExpecting actual:%n given predicate%n" + "to accept 2.0 but it did not.")); - assertThat(errors.get(52)).contains(format("%nExpecting:%n" + assertThat(errors.get(52)).contains(format("%nExpecting actual:%n" + " %n" + "not to have a port but had:%n" + " <80>")); @@ -403,7 +402,6 @@ public String toString() { } } - @SuppressWarnings("unchecked") @Test void should_pass_when_using_extracting_with_object() { // GIVEN @@ -534,7 +532,6 @@ void should_pass_when_using_extracting_with_iterable() { } @Test - @SuppressWarnings("unchecked") void should_pass_when_using_extracting_with_map() { // GIVEN Map map = mapOf(entry("name", "kawhi"), entry("age", 25)); @@ -667,7 +664,6 @@ void should_collect_all_errors_when_using_extracting() { .containsExactly("error 1", "error 2", "error 3"); } - @SuppressWarnings("unchecked") @Test void should_collect_all_errors_when_using_extracting_on_object() { // GIVEN @@ -950,6 +946,10 @@ void should_propagate_AssertionError_from_nested_proxied_calls() { // the nested proxied call to isNotEmpty() throw an Assertion error that must be propagated to the caller. softly.assertThat(emptyList()).element(0, as(STRING)); // the nested proxied call to isNotEmpty() throw an Assertion error that must be propagated to the caller. + softly.assertThat(emptyList()).elements(0, 1, 2); + // the nested proxied call to checkIndexValidity throw an Assertion error that must be propagated to the caller. + softly.assertThat(list("a", "b")).elements(0, 5); + // the nested proxied call to isNotEmpty() throw an Assertion error that must be propagated to the caller. softly.assertThat(emptyList()).last(); // the nested proxied call to isNotEmpty() throw an Assertion error that must be propagated to the caller. softly.assertThat(emptyList()).last(as(STRING)); @@ -970,7 +970,7 @@ void should_propagate_AssertionError_from_nested_proxied_calls() { // nested proxied call to isGreaterThan softly.assertThat(Duration.ofDays(-1)).isPositive(); // it must be caught by softly.assertAll() - assertThat(softly.errorsCollected()).hasSize(14); + assertThat(softly.errorsCollected()).hasSize(16); } @Test @@ -1140,9 +1140,14 @@ void iterable_soft_assertions_should_work_with_navigation_methods() { .overridingErrorMessage("error message") .last(as(type(Name.class))) .isNull(); + softly.assertThat(names) + .as("elements(0, 1)") + .overridingErrorMessage("error message") + .elements(0, 1) + .isNull(); // THEN List errorsCollected = softly.errorsCollected(); - assertThat(errorsCollected).hasSize(9); + assertThat(errorsCollected).hasSize(10); assertThat(errorsCollected.get(0)).hasMessage("[size isGreaterThan(10)] error message"); assertThat(errorsCollected.get(1)).hasMessage("[size isGreaterThan(22)] error message"); assertThat(errorsCollected.get(2)).hasMessage("[should not be empty] error message 2"); @@ -1152,6 +1157,7 @@ void iterable_soft_assertions_should_work_with_navigation_methods() { assertThat(errorsCollected.get(6)).hasMessage("[element(0) as Name] error message"); assertThat(errorsCollected.get(7)).hasMessage("[last element] error message"); assertThat(errorsCollected.get(8)).hasMessage("[last element as Name] error message"); + assertThat(errorsCollected.get(9)).hasMessage("[elements(0, 1)] error message"); } @Test @@ -1203,9 +1209,14 @@ void list_soft_assertions_should_work_with_navigation_methods() { .overridingErrorMessage("error message") .last(as(type(Name.class))) .isNull(); + softly.assertThat(names) + .as("elements(0, 1)") + .overridingErrorMessage("error message") + .elements(0, 1) + .isNull(); // THEN List errorsCollected = softly.errorsCollected(); - assertThat(errorsCollected).hasSize(9); + assertThat(errorsCollected).hasSize(10); assertThat(errorsCollected.get(0)).hasMessage("[size isGreaterThan(10)] error message"); assertThat(errorsCollected.get(1)).hasMessage("[size isGreaterThan(22)] error message"); assertThat(errorsCollected.get(2)).hasMessage("[shoud not be empty] error message 2"); @@ -1215,6 +1226,7 @@ void list_soft_assertions_should_work_with_navigation_methods() { assertThat(errorsCollected.get(6)).hasMessage("[element(0) as Name] error message"); assertThat(errorsCollected.get(7)).hasMessage("[last element] error message"); assertThat(errorsCollected.get(8)).hasMessage("[last element as Name] error message"); + assertThat(errorsCollected.get(9)).hasMessage("[elements(0, 1)] error message"); } @Test @@ -1270,7 +1282,6 @@ void list_soft_assertions_should_work_with_singleElement_navigation() { } // the test would fail if any method was not proxyable as the assertion error would not be softly caught - @SuppressWarnings("unchecked") @Test void iterable_soft_assertions_should_report_errors_on_final_methods_and_methods_that_switch_the_object_under_test() { // GIVEN @@ -1507,7 +1518,6 @@ void iterable_soft_assertions_should_report_errors_on_final_methods_and_methods_ } // the test would fail if any method was not proxyable as the assertion error would not be softly caught - @SuppressWarnings("unchecked") @Test void list_soft_assertions_should_report_errors_on_final_methods_and_methods_that_switch_the_object_under_test() { // GIVEN @@ -1744,7 +1754,6 @@ void list_soft_assertions_should_report_errors_on_final_methods_and_methods_that } // the test would fail if any method was not proxyable as the assertion error would not be softly caught - @SuppressWarnings("unchecked") @Test void object_array_soft_assertions_should_report_errors_on_final_methods_and_methods_that_switch_the_object_under_test() { // GIVEN @@ -1907,7 +1916,6 @@ void object_array_soft_assertions_should_report_errors_on_final_methods_and_meth } // the test would fail if any method was not proxyable as the assertion error would not be softly caught - @SuppressWarnings("unchecked") @Test void class_soft_assertions_should_report_errors_on_final_methods() { // GIVEN @@ -1924,7 +1932,6 @@ void class_soft_assertions_should_report_errors_on_final_methods() { } // the test would fail if any method was not proxyable as the assertion error would not be softly caught - @SuppressWarnings("unchecked") @Test void object_soft_assertions_should_report_errors_on_final_methods_and_methods_that_switch_the_object_under_test() { // GIVEN @@ -1978,7 +1985,6 @@ void object_soft_assertions_should_report_errors_on_final_methods_and_methods_th } // the test would fail if any method was not proxyable as the assertion error would not be softly caught - @SuppressWarnings("unchecked") @Test void map_soft_assertions_should_report_errors_on_final_methods_and_methods_that_switch_the_object_under_test() { // GIVEN @@ -2077,7 +2083,6 @@ void map_soft_assertions_should_work_with_navigation_methods() { assertThat(errorsCollected.get(3)).hasMessageContaining("check size after navigating back"); } - @SuppressWarnings("unchecked") @Test void predicate_soft_assertions_should_report_errors_on_final_methods() { // GIVEN @@ -2402,7 +2407,6 @@ class ExtractingFromEntries { MapEntry.entry(david, list(new Animal("scoubi"), new Animal("peter")))); @Test - @SuppressWarnings("unchecked") void should_pass_when_using_extractingFromEntries_with_map() { // WHEN softly.assertThat(map) @@ -2418,7 +2422,6 @@ void should_pass_when_using_extractingFromEntries_with_map() { } @Test - @SuppressWarnings("unchecked") void should_collect_errors_when_using_extractingFromEntries_with_map() { // WHEN softly.assertThat(map) diff --git a/src/test/java/org/assertj/core/api/ThrowableAssertAlternative_extends_AbstractObjectAssert_Test.java b/src/test/java/org/assertj/core/api/ThrowableAssertAlternative_extends_AbstractObjectAssert_Test.java new file mode 100644 index 00000000000..428a8ae7e94 --- /dev/null +++ b/src/test/java/org/assertj/core/api/ThrowableAssertAlternative_extends_AbstractObjectAssert_Test.java @@ -0,0 +1,50 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api; + +import static org.assertj.core.api.BDDAssertions.from; +import static org.assertj.core.api.BDDAssertions.thenExceptionOfType; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +@DisplayName("ThrowableAssertAlternative") +class ThrowableAssertAlternative_extends_AbstractObjectAssert_Test { + + @Test + void should_allow_chaining_object_assertions() { + // GIVEN + Throwable authenticationException = new AuthenticationException(503); + // WHEN/THEN + thenExceptionOfType(AuthenticationException.class).isThrownBy(() -> throwing(authenticationException)) + .returns(503, from(AuthenticationException::getStatusCode)); + } + + static void throwing(Throwable t) throws Throwable { + throw t; + } + + private static class AuthenticationException extends Exception { + private static final long serialVersionUID = 1L; + private int statusCode = 1; + + public AuthenticationException(int statusCode) { + this.statusCode = statusCode; + } + + public int getStatusCode() { + return statusCode; + } + } + +} diff --git a/src/test/java/org/assertj/core/api/WithAssertions_delegation_Test.java b/src/test/java/org/assertj/core/api/WithAssertions_delegation_Test.java index 68be886aa34..efd800e0b37 100644 --- a/src/test/java/org/assertj/core/api/WithAssertions_delegation_Test.java +++ b/src/test/java/org/assertj/core/api/WithAssertions_delegation_Test.java @@ -820,6 +820,7 @@ void withAssertions_setAllowExtractingPrivateFields_Test() { void withAssertions_registerCustomDateFormat_Test() { registerCustomDateFormat("YYYY-MMMM-dddd"); registerCustomDateFormat(DateFormat.getInstance()); + useDefaultDateFormatsOnly(); } /** diff --git a/src/test/java/org/assertj/core/api/abstract_/AbstractAssert_equal_hashCode_Test.java b/src/test/java/org/assertj/core/api/abstract_/AbstractAssert_equal_hashCode_Test.java index ac8e3e062dd..c41f956eb1f 100644 --- a/src/test/java/org/assertj/core/api/abstract_/AbstractAssert_equal_hashCode_Test.java +++ b/src/test/java/org/assertj/core/api/abstract_/AbstractAssert_equal_hashCode_Test.java @@ -39,7 +39,11 @@ void should_fail_because_not_supported_operation() { @SuppressWarnings("deprecation") void should_not_fail_when_equals_exceptions_is_deactivated() { AbstractAssert.throwUnsupportedExceptionOnEquals = false; - assertions.equals("anotherString"); + try { + assertions.equals("anotherString"); + } finally { + AbstractAssert.throwUnsupportedExceptionOnEquals = true; + } } @Test diff --git a/src/test/java/org/assertj/core/api/abstract_/AbstractAssert_isInstanceOfSatisfying_Test.java b/src/test/java/org/assertj/core/api/abstract_/AbstractAssert_isInstanceOfSatisfying_Test.java index 9a9d4188070..1ebfed000f6 100644 --- a/src/test/java/org/assertj/core/api/abstract_/AbstractAssert_isInstanceOfSatisfying_Test.java +++ b/src/test/java/org/assertj/core/api/abstract_/AbstractAssert_isInstanceOfSatisfying_Test.java @@ -78,7 +78,7 @@ void should_fail_according_to_requirements() { // THEN then(assertionError).hasMessage(format("[check light saber] %n" + "expected: \"Green\"%n" + - "but was : \"Red\"")); + " but was: \"Red\"")); } @Test diff --git a/src/test/java/org/assertj/core/api/assumptions/Assumptions_assumeThat_involving_iterable_navigation_Test.java b/src/test/java/org/assertj/core/api/assumptions/Assumptions_assumeThat_involving_iterable_navigation_Test.java index 9b104c3c8ba..7a4abfc8d79 100644 --- a/src/test/java/org/assertj/core/api/assumptions/Assumptions_assumeThat_involving_iterable_navigation_Test.java +++ b/src/test/java/org/assertj/core/api/assumptions/Assumptions_assumeThat_involving_iterable_navigation_Test.java @@ -70,6 +70,7 @@ void should_run_test_when_assumption_after_navigating_to_elements_passes() { assumeThat(jedis).last(as(type(Jedi.class))).isEqualTo(luke); assumeThat(jedis).element(1).isEqualTo(luke); assumeThat(jedis).element(1, as(type(Jedi.class))).isEqualTo(luke); + assumeThat(jedis).elements(0, 1).containsExactly(yoda, luke); }).doesNotThrowAnyException(); } @@ -129,6 +130,13 @@ void should_ignore_test_when_assumption_after_navigating_to_singleElement_fails( .isEqualTo(luke)); } + @Test + void should_ignore_test_when_assumption_after_navigating_to_elements_fails() { + expectAssumptionNotMetException(() -> assumeThat(jedis).elements(0, 1) + .as("check elements at index 0 and 1") + .containsExactly(luke, yoda)); + } + @Test void should_ignore_test_when_assumption_after_navigating_to_singleElement_with_InstanceOfAssertFactory_fails() { expectAssumptionNotMetException(() -> assumeThat(list(yoda)).singleElement(as(type(Jedi.class))) diff --git a/src/test/java/org/assertj/core/api/assumptions/Class_final_method_assertions_in_assumptions_Test.java b/src/test/java/org/assertj/core/api/assumptions/Class_final_method_assertions_in_assumptions_Test.java index cf27ac86401..3e503b3d9e8 100644 --- a/src/test/java/org/assertj/core/api/assumptions/Class_final_method_assertions_in_assumptions_Test.java +++ b/src/test/java/org/assertj/core/api/assumptions/Class_final_method_assertions_in_assumptions_Test.java @@ -21,7 +21,6 @@ import org.assertj.core.api.ClassAssertBaseTest.AnnotatedClass; import org.assertj.core.api.ClassAssertBaseTest.AnotherAnnotation; import org.assertj.core.api.ClassAssertBaseTest.MyAnnotation; -import org.assertj.core.api.ProxyableClassAssert; import org.assertj.core.util.VisibleForTesting; /** @@ -29,7 +28,6 @@ */ class Class_final_method_assertions_in_assumptions_Test extends BaseAssumptionsRunnerTest { - @SuppressWarnings("unchecked") public static Stream> provideAssumptionsRunners() { return Stream.of(assumptionRunner(AnnotatedClass.class, value -> assumeThat(value).hasAnnotations(MyAnnotation.class, AnotherAnnotation.class), diff --git a/src/test/java/org/assertj/core/api/assumptions/Iterable_special_assertion_methods_in_assumptions_Test.java b/src/test/java/org/assertj/core/api/assumptions/Iterable_special_assertion_methods_in_assumptions_Test.java index d98ddb51f48..f67be5327d0 100644 --- a/src/test/java/org/assertj/core/api/assumptions/Iterable_special_assertion_methods_in_assumptions_Test.java +++ b/src/test/java/org/assertj/core/api/assumptions/Iterable_special_assertion_methods_in_assumptions_Test.java @@ -23,7 +23,6 @@ import org.assertj.core.api.Condition; import org.assertj.core.api.IterableAssert; -import org.assertj.core.api.ProxyableIterableAssert; import org.assertj.core.data.TolkienCharacter; import org.assertj.core.test.CartoonCharacter; @@ -33,7 +32,6 @@ */ class Iterable_special_assertion_methods_in_assumptions_Test extends BaseAssumptionsRunnerTest { - @SuppressWarnings("unchecked") public static Stream> provideAssumptionsRunners() { return Stream.of( // extracting methods diff --git a/src/test/java/org/assertj/core/api/assumptions/List_special_assertion_methods_in_assumptions_Test.java b/src/test/java/org/assertj/core/api/assumptions/List_special_assertion_methods_in_assumptions_Test.java index 38b793506cb..831cfdcf4f0 100644 --- a/src/test/java/org/assertj/core/api/assumptions/List_special_assertion_methods_in_assumptions_Test.java +++ b/src/test/java/org/assertj/core/api/assumptions/List_special_assertion_methods_in_assumptions_Test.java @@ -24,7 +24,6 @@ import org.assertj.core.api.Condition; import org.assertj.core.api.ListAssert; -import org.assertj.core.api.ProxyableListAssert; import org.assertj.core.data.TolkienCharacter; import org.assertj.core.test.CartoonCharacter; @@ -34,7 +33,6 @@ */ class List_special_assertion_methods_in_assumptions_Test extends BaseAssumptionsRunnerTest { - @SuppressWarnings("unchecked") public static Stream> provideAssumptionsRunners() { return Stream.of( // extracting methods diff --git a/src/test/java/org/assertj/core/api/assumptions/Map_special_assertion_methods_in_assumptions_Test.java b/src/test/java/org/assertj/core/api/assumptions/Map_special_assertion_methods_in_assumptions_Test.java index 05874b87ef6..3aa5b387dca 100644 --- a/src/test/java/org/assertj/core/api/assumptions/Map_special_assertion_methods_in_assumptions_Test.java +++ b/src/test/java/org/assertj/core/api/assumptions/Map_special_assertion_methods_in_assumptions_Test.java @@ -28,7 +28,6 @@ import java.util.stream.Stream; import org.assertj.core.api.MapAssert; -import org.assertj.core.api.ProxyableMapAssert; /** * Verify that assertions final methods or methods changing the object under test in {@link MapAssert} work with assumptions @@ -36,7 +35,6 @@ */ class Map_special_assertion_methods_in_assumptions_Test extends BaseAssumptionsRunnerTest { - @SuppressWarnings("unchecked") public static Stream> provideAssumptionsRunners() { List names = asList("Dave", "Jeff"); diff --git a/src/test/java/org/assertj/core/api/assumptions/ObjectArray_special_assertion_methods_in_assumptions_Test.java b/src/test/java/org/assertj/core/api/assumptions/ObjectArray_special_assertion_methods_in_assumptions_Test.java index cdafa02d21f..6656aba0d03 100644 --- a/src/test/java/org/assertj/core/api/assumptions/ObjectArray_special_assertion_methods_in_assumptions_Test.java +++ b/src/test/java/org/assertj/core/api/assumptions/ObjectArray_special_assertion_methods_in_assumptions_Test.java @@ -23,7 +23,6 @@ import org.assertj.core.api.Condition; import org.assertj.core.api.ObjectArrayAssert; -import org.assertj.core.api.ProxyableObjectArrayAssert; import org.assertj.core.data.TolkienCharacter; import org.assertj.core.test.CartoonCharacter; @@ -33,7 +32,6 @@ */ class ObjectArray_special_assertion_methods_in_assumptions_Test extends BaseAssumptionsRunnerTest { - @SuppressWarnings("unchecked") public static Stream> provideAssumptionsRunners() { return Stream.of( // extracting methods diff --git a/src/test/java/org/assertj/core/api/assumptions/Object_special_assertion_methods_in_assumptions_Test.java b/src/test/java/org/assertj/core/api/assumptions/Object_special_assertion_methods_in_assumptions_Test.java index 17e67db779e..8818037ad51 100644 --- a/src/test/java/org/assertj/core/api/assumptions/Object_special_assertion_methods_in_assumptions_Test.java +++ b/src/test/java/org/assertj/core/api/assumptions/Object_special_assertion_methods_in_assumptions_Test.java @@ -20,17 +20,14 @@ import java.util.stream.Stream; import org.assertj.core.api.ObjectAssert; -import org.assertj.core.api.ProxyableObjectAssert; import org.assertj.core.data.TolkienCharacter; import org.assertj.core.data.TolkienCharacter.Race; /** - * verify that assertions final methods or methods changing the object under test in {@link ObjectAssert} work with assumptions - * (i.e. that they are proxied correctly in {@link ProxyableObjectAssert}). + * Verify that assertions final methods or methods changing the object under test in {@link ObjectAssert} work with assumptions. */ class Object_special_assertion_methods_in_assumptions_Test extends BaseAssumptionsRunnerTest { - @SuppressWarnings("unchecked") public static Stream> provideAssumptionsRunners() { return Stream.of(assumptionRunner(TolkienCharacter.of("Frodo", 33, Race.HOBBIT), value -> assumeThat(value).extracting(TolkienCharacter::getName, TolkienCharacter::getAge) diff --git a/src/test/java/org/assertj/core/api/assumptions/Predicate_final_method_assertions_in_assumptions_Test.java b/src/test/java/org/assertj/core/api/assumptions/Predicate_final_method_assertions_in_assumptions_Test.java index 7a1e09ea4e4..d04e9ef17dd 100644 --- a/src/test/java/org/assertj/core/api/assumptions/Predicate_final_method_assertions_in_assumptions_Test.java +++ b/src/test/java/org/assertj/core/api/assumptions/Predicate_final_method_assertions_in_assumptions_Test.java @@ -20,7 +20,6 @@ import java.util.stream.Stream; import org.assertj.core.api.ClassAssert; -import org.assertj.core.api.ProxyableClassAssert; import org.assertj.core.data.MapEntry; /** @@ -28,7 +27,6 @@ */ class Predicate_final_method_assertions_in_assumptions_Test extends BaseAssumptionsRunnerTest { - @SuppressWarnings("unchecked") public static Stream> provideAssumptionsRunners() { Predicate> ballSportPredicate = sport -> sport.value.contains("ball"); return Stream.of(assumptionRunner(ballSportPredicate, diff --git a/src/test/java/org/assertj/core/api/atomic/reference/AtomicReferenceAssert_hasValueSatisfying_Test.java b/src/test/java/org/assertj/core/api/atomic/reference/AtomicReferenceAssert_hasValueSatisfying_Test.java index 37d8b82ca46..44dfe65aadb 100644 --- a/src/test/java/org/assertj/core/api/atomic/reference/AtomicReferenceAssert_hasValueSatisfying_Test.java +++ b/src/test/java/org/assertj/core/api/atomic/reference/AtomicReferenceAssert_hasValueSatisfying_Test.java @@ -44,7 +44,7 @@ void should_fail_when_actual_has_value_which_does_not_satisfy_given_requirements AssertionError error = expectAssertionError(() -> assertThat(actual).hasValueSatisfying(value -> assertThat(value).isEqualToIgnoringCase(expectedValue))); // THEN then(error).hasMessageContainingAll("expected: \"bar\"", - "but was : \"foo\""); + " but was: \"foo\""); } @Test diff --git a/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_hasExactlyElementsOfTypes_Test.java b/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_hasExactlyElementsOfTypes_Test.java new file mode 100644 index 00000000000..3f9b89d7f29 --- /dev/null +++ b/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_hasExactlyElementsOfTypes_Test.java @@ -0,0 +1,36 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api.atomic.referencearray; + +import static org.mockito.Mockito.verify; + +import org.assertj.core.api.AtomicReferenceArrayAssert; +import org.assertj.core.api.AtomicReferenceArrayAssertBaseTest; + +/** + * Tests for {@link AtomicReferenceArrayAssert#hasExactlyElementsOfTypes(Class...)} . + */ +class AtomicReferenceArrayAssert_hasExactlyElementsOfTypes_Test extends AtomicReferenceArrayAssertBaseTest { + + private final Class[] types = { Short.class }; + + @Override + protected AtomicReferenceArrayAssert invoke_api_method() { + return assertions.hasExactlyElementsOfTypes(types); + } + + @Override + protected void verify_internal_effects() { + verify(arrays).assertHasExactlyElementsOfTypes(getInfo(assertions), internalArray(), types); + } +} diff --git a/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_satisfiesExactlyInAnyOrder_Test.java b/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_satisfiesExactlyInAnyOrder_Test.java index 46510bd0dbb..52ff1ff067a 100644 --- a/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_satisfiesExactlyInAnyOrder_Test.java +++ b/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_satisfiesExactlyInAnyOrder_Test.java @@ -12,6 +12,7 @@ */ package org.assertj.core.api.atomic.referencearray; +import static org.assertj.core.util.Arrays.array; import static org.assertj.core.util.Lists.list; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -26,7 +27,6 @@ * * @author Michael Grafl */ -@SuppressWarnings("unchecked") class AtomicReferenceArrayAssert_satisfiesExactlyInAnyOrder_Test extends AtomicReferenceArrayAssertBaseTest { private Consumer consumer = mock(Consumer.class); @@ -43,6 +43,6 @@ protected AtomicReferenceArrayAssert invoke_api_method() { @Override protected void verify_internal_effects() { - verify(iterables).assertSatisfiesExactlyInAnyOrder(info(), list(internalArray()), consumer); + verify(iterables).assertSatisfiesExactlyInAnyOrder(info(), list(internalArray()), array(consumer)); } } diff --git a/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_usingComparatorForType_Test.java b/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_usingComparatorForType_Test.java index 156aa9d1e86..06b3b56c68c 100644 --- a/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_usingComparatorForType_Test.java +++ b/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_usingComparatorForType_Test.java @@ -35,6 +35,7 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +@SuppressWarnings("deprecation") @DisplayName("AtomicReferenceArrayAssert usingComparatorForType") class AtomicReferenceArrayAssert_usingComparatorForType_Test extends AtomicReferenceArrayAssertBaseTest { @@ -106,17 +107,6 @@ void should_use_comparator_for_type_when_using_field_by_field_element_comparator .contains(other, "any"); } - @Test - void should_use_comparator_for_type_when_using_recursive_field_by_field_element_comparator() { - // GIVEN - Object[] array = array(actual, "some"); - AtomicReferenceArray atomicArray = new AtomicReferenceArray<>(array); - // THEN - assertThat(atomicArray).usingComparatorForType(ALWAY_EQUALS_STRING, String.class) - .usingRecursiveFieldByFieldElementComparator() - .contains(other, "any"); - } - @Test void should_not_use_comparator_on_fields_level_for_elements() { // GIVEN @@ -137,8 +127,8 @@ void should_not_use_comparator_on_fields_level_for_elements() { + " [\"any\"]%n" + "when comparing values using field/property by field/property comparator on all fields/properties%n" + "Comparators used:%n" - + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], String -> AlwaysEqualComparator}%n" - + "- for elements (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}")); + + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], String -> AlwaysEqualComparator, Path -> lexicographic comparator (Path natural order)}%n" + + "- for elements (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], Path -> lexicographic comparator (Path natural order)}")); } @Test @@ -190,7 +180,7 @@ void should_fail_because_of_comparator_set_last() { + " [Luke the Jedi]%n" + "when comparing values using field/property by field/property comparator on all fields/properties%n" + "Comparators used:%n" - + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], String -> org.assertj.core.test.NeverEqualComparator}%n" - + "- for elements (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], String -> AlwaysEqualComparator}")); + + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], String -> org.assertj.core.test.NeverEqualComparator, Path -> lexicographic comparator (Path natural order)}%n" + + "- for elements (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], String -> AlwaysEqualComparator, Path -> lexicographic comparator (Path natural order)}")); } } diff --git a/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_usingElementComparatorIgnoringFields_Test.java b/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_usingElementComparatorIgnoringFields_Test.java index 1122e2d5f31..c0e96133de6 100644 --- a/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_usingElementComparatorIgnoringFields_Test.java +++ b/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_usingElementComparatorIgnoringFields_Test.java @@ -27,6 +27,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +@SuppressWarnings("deprecation") class AtomicReferenceArrayAssert_usingElementComparatorIgnoringFields_Test extends AtomicReferenceArrayAssertBaseTest { @@ -50,7 +51,7 @@ protected void verify_internal_effects() { ComparatorBasedComparisonStrategy strategy = (ComparatorBasedComparisonStrategy) iterables.getComparisonStrategy(); assertThat(strategy.getComparator()).isInstanceOf(ExtendedByTypesComparator.class); assertThat(((IgnoringFieldsComparator) ((ExtendedByTypesComparator) strategy.getComparator()) - .getComparator()).getFields()).containsOnly("field"); + .getComparator()).getFields()).containsOnly("field"); } @Test diff --git a/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_usingElementComparatorOnFields_Test.java b/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_usingElementComparatorOnFields_Test.java index 82ae63fcb0d..a19bed3aa17 100644 --- a/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_usingElementComparatorOnFields_Test.java +++ b/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_usingElementComparatorOnFields_Test.java @@ -27,6 +27,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +@SuppressWarnings("deprecation") class AtomicReferenceArrayAssert_usingElementComparatorOnFields_Test extends AtomicReferenceArrayAssertBaseTest { private ObjectArrays arraysBefore; @@ -49,7 +50,7 @@ protected void verify_internal_effects() { ComparatorBasedComparisonStrategy strategy = (ComparatorBasedComparisonStrategy) arrays.getComparisonStrategy(); assertThat(strategy.getComparator()).isInstanceOf(ExtendedByTypesComparator.class); assertThat(((OnFieldsComparator) ((ExtendedByTypesComparator) strategy.getComparator()) - .getComparator()).getFields()).containsOnly("field"); + .getComparator()).getFields()).containsOnly("field"); } @Test diff --git a/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_usingFieldByFieldElementComparator_Test.java b/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_usingFieldByFieldElementComparator_Test.java index a1f433bf904..b53cdc86159 100644 --- a/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_usingFieldByFieldElementComparator_Test.java +++ b/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_usingFieldByFieldElementComparator_Test.java @@ -33,6 +33,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +@SuppressWarnings("deprecation") class AtomicReferenceArrayAssert_usingFieldByFieldElementComparator_Test extends AtomicReferenceArrayAssertBaseTest { @@ -171,8 +172,8 @@ void failed_isEqualTo_assertion_using_field_by_field_element_comparator() { .hasMessage(format(shouldBeEqualMessage("[Foo(id=id, bar=1)]", "[Foo(id=id, bar=2)]") + "%n" + "when comparing elements using field/property by field/property comparator on all fields/properties%n" + "Comparators used:%n" - + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}%n" - + "- for elements (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}")); + + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], Path -> lexicographic comparator (Path natural order)}%n" + + "- for elements (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], Path -> lexicographic comparator (Path natural order)}")); } @Test @@ -186,14 +187,14 @@ void failed_isIn_assertion_using_field_by_field_element_comparator() { // THEN assertThat(error).isInstanceOf(AssertionError.class) - .hasMessage(format("%nExpecting:%n" + .hasMessage(format("%nExpecting actual:%n" + " [Foo(id=id, bar=1)]%n" + "to be in:%n" + " [[Foo(id=id, bar=2)], [Foo(id=id, bar=2)]]%n" + "when comparing elements using field/property by field/property comparator on all fields/properties%n" + "Comparators used:%n" - + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}%n" - + "- for elements (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}")); + + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], Path -> lexicographic comparator (Path natural order)}%n" + + "- for elements (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], Path -> lexicographic comparator (Path natural order)}")); } @Test diff --git a/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_usingRecursiveFieldByFieldElementComparatorIgnoringFields_Test.java b/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_usingRecursiveFieldByFieldElementComparatorIgnoringFields_Test.java new file mode 100644 index 00000000000..d7c98a49415 --- /dev/null +++ b/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_usingRecursiveFieldByFieldElementComparatorIgnoringFields_Test.java @@ -0,0 +1,70 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api.atomic.referencearray; + +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.util.Lists.list; + +import org.assertj.core.api.AtomicReferenceArrayAssert; +import org.assertj.core.api.AtomicReferenceArrayAssertBaseTest; +import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration; +import org.assertj.core.internal.AtomicReferenceArrayElementComparisonStrategy; +import org.assertj.core.internal.ComparatorBasedComparisonStrategy; +import org.assertj.core.internal.ConfigurableRecursiveFieldByFieldComparator; +import org.assertj.core.internal.ObjectArrays; +import org.assertj.core.test.Name; +import org.assertj.core.test.Player; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class AtomicReferenceArrayAssert_usingRecursiveFieldByFieldElementComparatorIgnoringFields_Test + extends AtomicReferenceArrayAssertBaseTest { + + private ObjectArrays arraysBefore; + + @BeforeEach + void before() { + arraysBefore = getArrays(assertions); + } + + @Override + protected AtomicReferenceArrayAssert invoke_api_method() { + return assertions.usingRecursiveFieldByFieldElementComparatorIgnoringFields("field"); + } + + @Override + protected void verify_internal_effects() { + then(arraysBefore).isNotSameAs(getArrays(assertions)); + then(getArrays(assertions).getComparisonStrategy()).isInstanceOf(ComparatorBasedComparisonStrategy.class); + then(getObjects(assertions).getComparisonStrategy()).isInstanceOf(AtomicReferenceArrayElementComparisonStrategy.class); + RecursiveComparisonConfiguration recursiveComparisonConfiguration = RecursiveComparisonConfiguration.builder() + .withIgnoredFields("field") + .build(); + ConfigurableRecursiveFieldByFieldComparator expectedComparator = new ConfigurableRecursiveFieldByFieldComparator(recursiveComparisonConfiguration); + then(getArrays(assertions).getComparator()).isEqualTo(expectedComparator); + then(getObjects(assertions).getComparisonStrategy()).extracting("elementComparator").isEqualTo(expectedComparator); + } + + @Test + void should_ignore_given_fields_recursively() { + // GIVEN + Player rose = new Player(new Name("Derrick", "Rose"), "Chicago Bulls"); + rose.nickname = new Name("Crazy", "Dunks"); + Player jalen = new Player(new Name("Jalen", "Rose"), "Chicago Bulls"); + jalen.nickname = new Name("Crazy", "Defense"); + // WHEN/THEN + then(list(rose)).usingRecursiveFieldByFieldElementComparatorIgnoringFields("name.first", "nickname.last") + .contains(jalen); + } + +} diff --git a/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_usingRecursiveFieldByFieldElementComparatorOnFields_Test.java b/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_usingRecursiveFieldByFieldElementComparatorOnFields_Test.java new file mode 100644 index 00000000000..57169aef1ef --- /dev/null +++ b/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_usingRecursiveFieldByFieldElementComparatorOnFields_Test.java @@ -0,0 +1,70 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api.atomic.referencearray; + +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.util.Arrays.array; + +import org.assertj.core.api.AtomicReferenceArrayAssert; +import org.assertj.core.api.AtomicReferenceArrayAssertBaseTest; +import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration; +import org.assertj.core.internal.AtomicReferenceArrayElementComparisonStrategy; +import org.assertj.core.internal.ComparatorBasedComparisonStrategy; +import org.assertj.core.internal.ConfigurableRecursiveFieldByFieldComparator; +import org.assertj.core.internal.ObjectArrays; +import org.assertj.core.test.Name; +import org.assertj.core.test.Player; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class AtomicReferenceArrayAssert_usingRecursiveFieldByFieldElementComparatorOnFields_Test + extends AtomicReferenceArrayAssertBaseTest { + + private ObjectArrays arraysBefore; + + @BeforeEach + void before() { + arraysBefore = getArrays(assertions); + } + + @Override + protected AtomicReferenceArrayAssert invoke_api_method() { + return assertions.usingRecursiveFieldByFieldElementComparatorOnFields("field"); + } + + @Override + protected void verify_internal_effects() { + then(arraysBefore).isNotSameAs(getArrays(assertions)); + then(getArrays(assertions).getComparisonStrategy()).isInstanceOf(ComparatorBasedComparisonStrategy.class); + then(getObjects(assertions).getComparisonStrategy()).isInstanceOf(AtomicReferenceArrayElementComparisonStrategy.class); + RecursiveComparisonConfiguration recursiveComparisonConfiguration = RecursiveComparisonConfiguration.builder() + .withComparedFields("field") + .build(); + ConfigurableRecursiveFieldByFieldComparator expectedComparator = new ConfigurableRecursiveFieldByFieldComparator(recursiveComparisonConfiguration); + then(getArrays(assertions).getComparator()).isEqualTo(expectedComparator); + then(getObjects(assertions).getComparisonStrategy()).extracting("elementComparator").isEqualTo(expectedComparator); + } + + @Test + void should_compare_given_fields_recursively_and_none_other() { + // GIVEN + Player rose = new Player(new Name("Derrick", "Rose"), "Chicago Bulls"); + rose.nickname = new Name("Crazy", "Dunks"); + Player jalen = new Player(new Name("Jalen", "Rose"), "Chicago Bulls"); + jalen.nickname = new Name("Crazy", "Defense"); + // WHEN/THEN + then(array(rose)).usingRecursiveFieldByFieldElementComparatorOnFields("name.last", "team", "nickname.first") + .contains(jalen); + } + +} diff --git a/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_usingRecursiveFieldByFieldElementComparator_Test.java b/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_usingRecursiveFieldByFieldElementComparator_Test.java index f7891322049..66d5786eecf 100644 --- a/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_usingRecursiveFieldByFieldElementComparator_Test.java +++ b/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_usingRecursiveFieldByFieldElementComparator_Test.java @@ -14,17 +14,19 @@ import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.catchThrowable; -import static org.assertj.core.test.AlwaysEqualComparator.ALWAY_EQUALS_STRING; +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.configuration.ConfigurationProvider.CONFIGURATION_PROVIDER; import static org.assertj.core.test.ErrorMessagesForTest.shouldBeEqualMessage; +import static org.assertj.core.util.AssertionsUtil.expectAssertionError; -import java.util.Comparator; import java.util.concurrent.atomic.AtomicReferenceArray; import org.assertj.core.api.AtomicReferenceArrayAssert; import org.assertj.core.api.AtomicReferenceArrayAssertBaseTest; +import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration; import org.assertj.core.internal.AtomicReferenceArrayElementComparisonStrategy; import org.assertj.core.internal.ComparatorBasedComparisonStrategy; +import org.assertj.core.internal.ConfigurableRecursiveFieldByFieldComparator; import org.assertj.core.internal.ObjectArrays; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -32,6 +34,8 @@ class AtomicReferenceArrayAssert_usingRecursiveFieldByFieldElementComparator_Test extends AtomicReferenceArrayAssertBaseTest { + private static final String DEFAULT_RECURSIVE_COMPARATOR_DESCRIPTION = CONFIGURATION_PROVIDER.representation() + .toStringOf(new ConfigurableRecursiveFieldByFieldComparator(new RecursiveComparisonConfiguration())); private ObjectArrays arraysBefore; @BeforeEach @@ -46,23 +50,27 @@ protected AtomicReferenceArrayAssert invoke_api_method() { @Override protected void verify_internal_effects() { - assertThat(arraysBefore).isNotSameAs(getArrays(assertions)); - assertThat(getArrays(assertions).getComparisonStrategy()).isInstanceOf(ComparatorBasedComparisonStrategy.class); - assertThat(getObjects(assertions).getComparisonStrategy()).isInstanceOf(AtomicReferenceArrayElementComparisonStrategy.class); + then(arraysBefore).isNotSameAs(getArrays(assertions)); + then(getArrays(assertions).getComparisonStrategy()).isInstanceOf(ComparatorBasedComparisonStrategy.class); + then(getObjects(assertions).getComparisonStrategy()).isInstanceOf(AtomicReferenceArrayElementComparisonStrategy.class); } @Test void successful_isEqualTo_assertion_using_recursive_field_by_field_element_comparator() { + // GIVEN AtomicReferenceArray array1 = atomicArrayOf(new Foo("id", new Bar(1))); Foo[] array2 = { new Foo("id", new Bar(1)) }; - assertThat(array1).usingRecursiveFieldByFieldElementComparator().isEqualTo(array2); + // WHEN/THEN + then(array1).usingRecursiveFieldByFieldElementComparator().isEqualTo(array2); } @Test void successful_isIn_assertion_using_recursive_field_by_field_element_comparator() { + // GIVEN AtomicReferenceArray array1 = atomicArrayOf(new Foo("id", new Bar(1))); Foo[] array2 = { new Foo("id", new Bar(1)) }; - assertThat(array1).usingRecursiveFieldByFieldElementComparator().isIn(new Object[] { (array2) }); + // WHEN/THEN + then(array1).usingRecursiveFieldByFieldElementComparator().isIn(new Object[] { (array2) }); } @Test @@ -71,14 +79,12 @@ void failed_isEqualTo_assertion_using_recursive_field_by_field_element_comparato AtomicReferenceArray array1 = atomicArrayOf(new Foo("id", new Bar(1))); Foo[] array2 = { new Foo("id", new Bar(2)) }; // WHEN - Throwable error = catchThrowable(() -> assertThat(array1).usingRecursiveFieldByFieldElementComparator().isEqualTo(array2)); + AssertionError assertionError = expectAssertionError(() -> assertThat(array1).usingRecursiveFieldByFieldElementComparator() + .isEqualTo(array2)); // THEN - assertThat(error).isInstanceOf(AssertionError.class) - .hasMessage(format(shouldBeEqualMessage("[Foo(id=id, bar=Bar(id=1))]", "[Foo(id=id, bar=Bar(id=2))]") + "%n" - + "when comparing elements using recursive field/property by field/property comparator on all fields/properties%n" - + "Comparators used:%n" - + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}%n" - + "- for elements (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}")); + then(assertionError).hasMessage(format(shouldBeEqualMessage("[Foo(id=id, bar=Bar(id=1))]", "[Foo(id=id, bar=Bar(id=2))]") + + "%n" + + "when comparing elements using %s", DEFAULT_RECURSIVE_COMPARATOR_DESCRIPTION)); } @Test @@ -87,57 +93,14 @@ void failed_isIn_assertion_using_recursive_field_by_field_element_comparator() { AtomicReferenceArray array1 = atomicArrayOf(new Foo("id", new Bar(1))); Foo[] array2 = { new Foo("id", new Bar(2)) }; // WHEN - Throwable error = catchThrowable(() -> assertThat(array1).usingRecursiveFieldByFieldElementComparator() - .isIn(new Object[] { array2 })); + AssertionError assertionError = expectAssertionError(() -> assertThat(array1).usingRecursiveFieldByFieldElementComparator() + .isIn(new Object[] { array2 })); // THEN - assertThat(error).isInstanceOf(AssertionError.class) - .hasMessage(format("%nExpecting:%n" - + " [Foo(id=id, bar=Bar(id=1))]%n" - + "to be in:%n" - + " [[Foo(id=id, bar=Bar(id=2))]]%n" - + "when comparing elements using recursive field/property by field/property comparator on all fields/properties%n" - + "Comparators used:%n" - + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}%n" - + "- for elements (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}")); - } - - @Test - void should_be_able_to_use_a_comparator_for_specified_fields_of_elements_when_using_recursive_field_by_field_element_comparator() { - Foo actual = new Foo("1", new Bar(1)); - Foo other = new Foo("1", new Bar(2)); - final class AlwaysEqualIntegerComparator implements Comparator { - @Override - public int compare(Integer o1, Integer o2) { - return 0; - } - } - - assertThat(atomicArrayOf(actual)).usingComparatorForElementFieldsWithNames(new AlwaysEqualIntegerComparator(), - "bar.id") - .usingRecursiveFieldByFieldElementComparator() - .contains(other); - } - - @Test - void comparators_for_element_field_names_should_have_precedence_over_comparators_for_element_field_types_when_using_recursive_field_by_field_element_comparator() { - Comparator comparator = (o1, o2) -> o1.compareTo(o2); - Foo actual = new Foo("1", new Bar(1)); - Foo other = new Foo("2", new Bar(1)); - - assertThat(atomicArrayOf(actual)).usingComparatorForElementFieldsWithNames(ALWAY_EQUALS_STRING, "id") - .usingComparatorForElementFieldsWithType(comparator, String.class) - .usingRecursiveFieldByFieldElementComparator() - .contains(other); - } - - @Test - void should_be_able_to_use_a_comparator_for_element_fields_with_specified_type_when_using_recursive_field_by_field_element_comparator() { - Foo actual = new Foo("1", new Bar(1)); - Foo other = new Foo("2", new Bar(1)); - - assertThat(atomicArrayOf(actual)).usingComparatorForElementFieldsWithType(ALWAY_EQUALS_STRING, String.class) - .usingRecursiveFieldByFieldElementComparator() - .contains(other); + then(assertionError).hasMessage(format("%nExpecting actual:%n" + + " [Foo(id=id, bar=Bar(id=1))]%n" + + "to be in:%n" + + " [[Foo(id=id, bar=Bar(id=2))]]%n" + + "when comparing elements using %s", DEFAULT_RECURSIVE_COMPARATOR_DESCRIPTION)); } public static class Foo { diff --git a/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_usingRecursiveFieldByFieldElementComparator_with_RecursiveComparisonConfiguration_Test.java b/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_usingRecursiveFieldByFieldElementComparator_with_RecursiveComparisonConfiguration_Test.java new file mode 100644 index 00000000000..114432a6e06 --- /dev/null +++ b/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_usingRecursiveFieldByFieldElementComparator_with_RecursiveComparisonConfiguration_Test.java @@ -0,0 +1,92 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api.atomic.referencearray; + +import static org.assertj.core.api.BDDAssertions.then; + +import org.assertj.core.api.AtomicReferenceArrayAssert; +import org.assertj.core.api.AtomicReferenceArrayAssertBaseTest; +import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration; +import org.assertj.core.internal.AtomicReferenceArrayElementComparisonStrategy; +import org.assertj.core.internal.ComparatorBasedComparisonStrategy; +import org.assertj.core.internal.ConfigurableRecursiveFieldByFieldComparator; +import org.assertj.core.internal.ObjectArrays; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class AtomicReferenceArrayAssert_usingRecursiveFieldByFieldElementComparator_with_RecursiveComparisonConfiguration_Test + extends AtomicReferenceArrayAssertBaseTest { + + private ObjectArrays arraysBefore; + private RecursiveComparisonConfiguration recursiveComparisonConfiguration = new RecursiveComparisonConfiguration(); + + @BeforeEach + void before() { + arraysBefore = getArrays(assertions); + } + + @Override + protected AtomicReferenceArrayAssert invoke_api_method() { + return assertions.usingRecursiveFieldByFieldElementComparator(recursiveComparisonConfiguration); + } + + @Override + protected void verify_internal_effects() { + then(arraysBefore).isNotSameAs(getArrays(assertions)); + then(getArrays(assertions).getComparisonStrategy()).isInstanceOf(ComparatorBasedComparisonStrategy.class); + then(getObjects(assertions).getComparisonStrategy()).isInstanceOf(AtomicReferenceArrayElementComparisonStrategy.class); + ConfigurableRecursiveFieldByFieldComparator expectedComparator = new ConfigurableRecursiveFieldByFieldComparator(recursiveComparisonConfiguration); + then(getArrays(assertions).getComparator()).isEqualTo(expectedComparator); + then(getObjects(assertions).getComparisonStrategy()).extracting("elementComparator").isEqualTo(expectedComparator); + } + + @Test + void should_be_able_to_use_specific_RecursiveComparisonConfiguration_when_using_recursive_field_by_field_element_comparator() { + // GIVEN + Foo actual = new Foo("1", new Bar(1)); + Foo other = new Foo("2", new Bar(1)); + RecursiveComparisonConfiguration configuration = new RecursiveComparisonConfiguration(); + configuration.ignoreFields("id"); + // WHEN/THEN + then(atomicArrayOf(actual)).usingRecursiveFieldByFieldElementComparator(configuration) + .contains(other); + } + + public static class Foo { + public String id; + public Bar bar; + + public Foo(String id, Bar bar) { + this.id = id; + this.bar = bar; + } + + @Override + public String toString() { + return "Foo(id=" + id + ", bar=" + bar + ")"; + } + } + + public static class Bar { + public int id; + + public Bar(int id) { + this.id = id; + } + + @Override + public String toString() { + return "Bar(id=" + id + ")"; + } + } +} diff --git a/src/test/java/org/assertj/core/api/charsequence/CharSequenceAssert_containsIgnoringWhitespaces_CharSequence_Test.java b/src/test/java/org/assertj/core/api/charsequence/CharSequenceAssert_containsIgnoringWhitespaces_CharSequence_Test.java new file mode 100644 index 00000000000..89baf54eea5 --- /dev/null +++ b/src/test/java/org/assertj/core/api/charsequence/CharSequenceAssert_containsIgnoringWhitespaces_CharSequence_Test.java @@ -0,0 +1,36 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api.charsequence; + +import static org.mockito.Mockito.verify; + +import org.assertj.core.api.CharSequenceAssert; +import org.assertj.core.api.CharSequenceAssertBaseTest; + +/** + * Tests for {@link CharSequenceAssert#containsIgnoringWhitespaces(CharSequence...)} (CharSequence...)}. + * + * @author Johannes Becker + */ +class CharSequenceAssert_containsIgnoringWhitespaces_CharSequence_Test extends CharSequenceAssertBaseTest { + + @Override + protected CharSequenceAssert invoke_api_method() { + return assertions.containsIgnoringWhitespaces("od", "da"); + } + + @Override + protected void verify_internal_effects() { + verify(strings).assertContainsIgnoringWhitespaces(getInfo(assertions), getActual(assertions), "od", "da"); + } +} diff --git a/src/test/java/org/assertj/core/api/classes/ClassAssert_hasAnnotation_Test.java b/src/test/java/org/assertj/core/api/classes/ClassAssert_hasAnnotation_Test.java index c35ba00adaa..ec143c1f685 100644 --- a/src/test/java/org/assertj/core/api/classes/ClassAssert_hasAnnotation_Test.java +++ b/src/test/java/org/assertj/core/api/classes/ClassAssert_hasAnnotation_Test.java @@ -12,6 +12,7 @@ */ package org.assertj.core.api.classes; +import static org.assertj.core.util.Arrays.array; import static org.mockito.Mockito.verify; import org.assertj.core.api.ClassAssert; @@ -19,7 +20,7 @@ /** * Tests for {@link org.assertj.core.api.ClassAssert#hasAnnotation(Class)}. - * + * * @author Joel Costigliola */ class ClassAssert_hasAnnotation_Test extends ClassAssertBaseTest { @@ -29,10 +30,9 @@ protected ClassAssert invoke_api_method() { return assertions.hasAnnotation(MyAnnotation.class); } - @SuppressWarnings("unchecked") @Override protected void verify_internal_effects() { - verify(classes).assertContainsAnnotations(getInfo(assertions), getActual(assertions), MyAnnotation.class); + verify(classes).assertContainsAnnotations(getInfo(assertions), getActual(assertions), array(MyAnnotation.class)); } } diff --git a/src/test/java/org/assertj/core/api/classes/ClassAssert_hasAnnotations_Test.java b/src/test/java/org/assertj/core/api/classes/ClassAssert_hasAnnotations_Test.java index d9813f3c68d..3eaf176dc3f 100644 --- a/src/test/java/org/assertj/core/api/classes/ClassAssert_hasAnnotations_Test.java +++ b/src/test/java/org/assertj/core/api/classes/ClassAssert_hasAnnotations_Test.java @@ -12,6 +12,7 @@ */ package org.assertj.core.api.classes; +import static org.assertj.core.util.Arrays.array; import static org.mockito.Mockito.verify; import org.assertj.core.api.ClassAssert; @@ -19,7 +20,7 @@ /** * Tests for {@link org.assertj.core.api.ClassAssert#hasAnnotations(Class[])}. - * + * * @author William Delanoue * @author Joel Costigliola */ @@ -30,13 +31,10 @@ protected ClassAssert invoke_api_method() { return assertions.hasAnnotations(MyAnnotation.class, AnotherAnnotation.class); } - @SuppressWarnings("unchecked") @Override protected void verify_internal_effects() { - verify(classes).assertContainsAnnotations(getInfo(assertions), - getActual(assertions), - MyAnnotation.class, - AnotherAnnotation.class); + verify(classes).assertContainsAnnotations(getInfo(assertions), getActual(assertions), + array(MyAnnotation.class, AnotherAnnotation.class)); } } diff --git a/src/test/java/org/assertj/core/api/classes/ClassAssert_hasOnlyFields_Test.java b/src/test/java/org/assertj/core/api/classes/ClassAssert_hasOnlyPublicFields_Test.java similarity index 94% rename from src/test/java/org/assertj/core/api/classes/ClassAssert_hasOnlyFields_Test.java rename to src/test/java/org/assertj/core/api/classes/ClassAssert_hasOnlyPublicFields_Test.java index f054aa6b747..6d7f137a710 100644 --- a/src/test/java/org/assertj/core/api/classes/ClassAssert_hasOnlyFields_Test.java +++ b/src/test/java/org/assertj/core/api/classes/ClassAssert_hasOnlyPublicFields_Test.java @@ -22,7 +22,7 @@ * * @author Filip Hrisafoc */ -class ClassAssert_hasOnlyFields_Test extends ClassAssertBaseTest { +class ClassAssert_hasOnlyPublicFields_Test extends ClassAssertBaseTest { @Override protected ClassAssert invoke_api_method() { diff --git a/src/test/java/org/assertj/core/api/double_/DoubleAssert_isEqualTo_double_Test.java b/src/test/java/org/assertj/core/api/double_/DoubleAssert_isEqualTo_double_Test.java index 175f6355bb3..ce5799825a9 100644 --- a/src/test/java/org/assertj/core/api/double_/DoubleAssert_isEqualTo_double_Test.java +++ b/src/test/java/org/assertj/core/api/double_/DoubleAssert_isEqualTo_double_Test.java @@ -15,6 +15,7 @@ import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.error.ShouldNotBeNull.shouldNotBeNull; import static org.assertj.core.test.ErrorMessagesForTest.shouldBeEqualMessage; import static org.assertj.core.util.AssertionsUtil.expectAssertionError; import static org.mockito.BDDMockito.given; @@ -90,4 +91,15 @@ void should_fail_with_clear_error_message_when_both_doubles_are_NaN() { // THEN then(assertionError).hasMessage(format("Actual and expected values were compared with == because expected was a primitive double, the assertion failed as both were Double.NaN and Double.NaN != Double.NaN (as per Double#equals javadoc)")); } + + @Test + void should_fail_when_actual_null_expected_primitive() { + // GIVEN + Double actual = null; + double expected = 1.0d; + // WHEN + AssertionError assertionError = expectAssertionError(() -> assertThat(actual).isEqualTo(expected)); + // THEN + then(assertionError).hasMessage(shouldNotBeNull().create()); + } } diff --git a/src/test/java/org/assertj/core/api/double_/DoubleAssert_isNotEqualTo_double_Test.java b/src/test/java/org/assertj/core/api/double_/DoubleAssert_isNotEqualTo_double_Test.java index 41da2892f81..09b653741df 100644 --- a/src/test/java/org/assertj/core/api/double_/DoubleAssert_isNotEqualTo_double_Test.java +++ b/src/test/java/org/assertj/core/api/double_/DoubleAssert_isNotEqualTo_double_Test.java @@ -15,6 +15,7 @@ import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.error.ShouldNotBeNull.shouldNotBeNull; import static org.assertj.core.test.AlwaysDifferentComparator.ALWAY_DIFFERENT; import static org.assertj.core.util.AssertionsUtil.expectAssertionError; import static org.mockito.BDDMockito.given; @@ -74,9 +75,20 @@ void should_fail_if_doubles_are_equal() { // WHEN AssertionError assertionError = expectAssertionError(() -> assertThat(actual).isNotEqualTo(expected)); // THEN - then(assertionError).hasMessage(format("%nExpecting:%n" + + then(assertionError).hasMessage(format("%nExpecting actual:%n" + " 0.0%n" + "not to be equal to:%n" + " -0.0%n")); } + + @Test + void should_fail_when_actual_null_expected_primitive() { + // GIVEN + Double actual = null; + double expected = 1.0d; + // WHEN + AssertionError assertionError = expectAssertionError(() -> assertThat(actual).isNotEqualTo(expected)); + // THEN + then(assertionError).hasMessageContaining(shouldNotBeNull().create()); + } } diff --git a/src/test/java/org/assertj/core/api/double_/DoubleAssert_isNotFinite_Test.java b/src/test/java/org/assertj/core/api/double_/DoubleAssert_isNotFinite_Test.java new file mode 100644 index 00000000000..93330347b39 --- /dev/null +++ b/src/test/java/org/assertj/core/api/double_/DoubleAssert_isNotFinite_Test.java @@ -0,0 +1,34 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api.double_; + +import static org.mockito.Mockito.verify; + +import org.assertj.core.api.DoubleAssert; +import org.assertj.core.api.DoubleAssertBaseTest; +import org.junit.jupiter.api.DisplayName; + +@DisplayName("DoubleAssert isNotFinite") +class DoubleAssert_isNotFinite_Test extends DoubleAssertBaseTest { + + @Override + protected DoubleAssert invoke_api_method() { + return assertions.isNotFinite(); + } + + @Override + protected void verify_internal_effects() { + verify(doubles).assertIsNotFinite(getInfo(assertions), getActual(assertions)); + } + +} diff --git a/src/test/java/org/assertj/core/api/double_/DoubleAssert_isNotInfinite_Test.java b/src/test/java/org/assertj/core/api/double_/DoubleAssert_isNotInfinite_Test.java new file mode 100644 index 00000000000..fad54858923 --- /dev/null +++ b/src/test/java/org/assertj/core/api/double_/DoubleAssert_isNotInfinite_Test.java @@ -0,0 +1,34 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api.double_; + +import static org.mockito.Mockito.verify; + +import org.assertj.core.api.DoubleAssert; +import org.assertj.core.api.DoubleAssertBaseTest; +import org.junit.jupiter.api.DisplayName; + +@DisplayName("DoubleAssert isNotInfinite") +class DoubleAssert_isNotInfinite_Test extends DoubleAssertBaseTest { + + @Override + protected DoubleAssert invoke_api_method() { + return assertions.isNotInfinite(); + } + + @Override + protected void verify_internal_effects() { + verify(doubles).assertIsNotInfinite(getInfo(assertions), getActual(assertions)); + } + +} diff --git a/src/test/java/org/assertj/core/api/double_/DoubleAssert_isNotZero_Test.java b/src/test/java/org/assertj/core/api/double_/DoubleAssert_isNotZero_Test.java index 44087eb55c6..cbf5dbaaba2 100644 --- a/src/test/java/org/assertj/core/api/double_/DoubleAssert_isNotZero_Test.java +++ b/src/test/java/org/assertj/core/api/double_/DoubleAssert_isNotZero_Test.java @@ -51,7 +51,7 @@ void should_fail_with_primitive_negative_zero() { // THEN assertThat(error).isInstanceOf(AssertionError.class) - .hasMessage(format("%nExpecting:%n -0.0%nnot to be equal to:%n 0.0%n")); + .hasMessage(format("%nExpecting actual:%n -0.0%nnot to be equal to:%n 0.0%n")); } @Test @@ -64,7 +64,7 @@ void should_fail_with_primitive_positive_zero() { // THEN assertThat(error).isInstanceOf(AssertionError.class) - .hasMessage(format("%nExpecting:%n 0.0%nnot to be equal to:%n 0.0%n")); + .hasMessage(format("%nExpecting actual:%n 0.0%nnot to be equal to:%n 0.0%n")); } @Test @@ -75,7 +75,7 @@ void should_fail_with_Double_positive_zero() { // WHEN Throwable error = catchThrowable(() -> assertThat(positiveZero).isNotZero()); assertThat(error).isInstanceOf(AssertionError.class) - .hasMessage(format("%nExpecting:%n 0.0%nnot to be equal to:%n 0.0%n")); + .hasMessage(format("%nExpecting actual:%n 0.0%nnot to be equal to:%n 0.0%n")); } } diff --git a/src/test/java/org/assertj/core/api/float_/FloatAssert_isNotEqualTo_float_Test.java b/src/test/java/org/assertj/core/api/float_/FloatAssert_isNotEqualTo_float_Test.java index ce1a7cab70a..4d414006455 100644 --- a/src/test/java/org/assertj/core/api/float_/FloatAssert_isNotEqualTo_float_Test.java +++ b/src/test/java/org/assertj/core/api/float_/FloatAssert_isNotEqualTo_float_Test.java @@ -74,7 +74,7 @@ void should_fail_if_floats_are_equal() { // WHEN AssertionError assertionError = expectAssertionError(() -> assertThat(actual).isNotEqualTo(expected)); // THEN - then(assertionError).hasMessage(format("%nExpecting:%n" + + then(assertionError).hasMessage(format("%nExpecting actual:%n" + " 0.0f%n" + "not to be equal to:%n" + " -0.0f%n")); diff --git a/src/test/java/org/assertj/core/api/float_/FloatAssert_isNotFinite_Test.java b/src/test/java/org/assertj/core/api/float_/FloatAssert_isNotFinite_Test.java new file mode 100644 index 00000000000..b5e2d399bef --- /dev/null +++ b/src/test/java/org/assertj/core/api/float_/FloatAssert_isNotFinite_Test.java @@ -0,0 +1,34 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api.float_; + +import static org.mockito.Mockito.verify; + +import org.assertj.core.api.FloatAssert; +import org.assertj.core.api.FloatAssertBaseTest; +import org.junit.jupiter.api.DisplayName; + +@DisplayName("FloatAssert isNotFinite") +class FloatAssert_isNotFinite_Test extends FloatAssertBaseTest { + + @Override + protected FloatAssert invoke_api_method() { + return assertions.isNotFinite(); + } + + @Override + protected void verify_internal_effects() { + verify(floats).assertIsNotFinite(getInfo(assertions), getActual(assertions)); + } + +} diff --git a/src/test/java/org/assertj/core/api/float_/FloatAssert_isNotInfinite_Test.java b/src/test/java/org/assertj/core/api/float_/FloatAssert_isNotInfinite_Test.java new file mode 100644 index 00000000000..d2f1ead8883 --- /dev/null +++ b/src/test/java/org/assertj/core/api/float_/FloatAssert_isNotInfinite_Test.java @@ -0,0 +1,34 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api.float_; + +import static org.mockito.Mockito.verify; + +import org.assertj.core.api.FloatAssert; +import org.assertj.core.api.FloatAssertBaseTest; +import org.junit.jupiter.api.DisplayName; + +@DisplayName("DoubleAssert isNotInfinite") +class FloatAssert_isNotInfinite_Test extends FloatAssertBaseTest { + + @Override + protected FloatAssert invoke_api_method() { + return assertions.isNotInfinite(); + } + + @Override + protected void verify_internal_effects() { + verify(floats).assertIsNotInfinite(getInfo(assertions), getActual(assertions)); + } + +} diff --git a/src/test/java/org/assertj/core/api/float_/FloatAssert_isNotZero_Test.java b/src/test/java/org/assertj/core/api/float_/FloatAssert_isNotZero_Test.java index 64b99b6b750..b7e6da33407 100644 --- a/src/test/java/org/assertj/core/api/float_/FloatAssert_isNotZero_Test.java +++ b/src/test/java/org/assertj/core/api/float_/FloatAssert_isNotZero_Test.java @@ -56,7 +56,7 @@ void should_fail_with_primitive_negative_zero() { // THEN assertThat(error).isInstanceOf(AssertionError.class) - .hasMessage(format("%nExpecting:%n -0.0f%nnot to be equal to:%n 0.0f%n")); + .hasMessage(format("%nExpecting actual:%n -0.0f%nnot to be equal to:%n 0.0f%n")); } @Test @@ -69,7 +69,7 @@ void should_fail_with_primitive_positive_zero() { // THEN assertThat(error).isInstanceOf(AssertionError.class) - .hasMessage(format("%nExpecting:%n 0.0f%nnot to be equal to:%n 0.0f%n")); + .hasMessage(format("%nExpecting actual:%n 0.0f%nnot to be equal to:%n 0.0f%n")); } @Test @@ -82,7 +82,7 @@ void should_fail_with_Float_positive_zero() { // THEN assertThat(error).isInstanceOf(AssertionError.class) - .hasMessage(format("%nExpecting:%n 0.0f%nnot to be equal to:%n 0.0f%n")); + .hasMessage(format("%nExpecting actual:%n 0.0f%nnot to be equal to:%n 0.0f%n")); } } diff --git a/src/test/java/org/assertj/core/api/inputstream/InputStreamAssert_asString_with_charset_Test.java b/src/test/java/org/assertj/core/api/inputstream/InputStreamAssert_asString_with_charset_Test.java new file mode 100644 index 00000000000..c48b3ae27ad --- /dev/null +++ b/src/test/java/org/assertj/core/api/inputstream/InputStreamAssert_asString_with_charset_Test.java @@ -0,0 +1,133 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api.inputstream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assumptions.assumeThat; +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.api.BDDAssertions.thenCode; +import static org.assertj.core.api.BDDAssertions.thenNullPointerException; +import static org.assertj.core.test.ErrorMessagesForTest.shouldBeEqualMessage; +import static org.assertj.core.util.AssertionsUtil.expectAssertionError; +import static org.assertj.core.util.AssertionsUtil.expectAssumptionNotMetException; +import static org.assertj.core.util.FailureMessages.actualIsNull; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.nio.charset.Charset; + +import org.assertj.core.api.SoftAssertions; +import org.assertj.core.error.AssertJMultipleFailuresError; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.opentest4j.AssertionFailedError; + +@DisplayName("InputStreamAssert asString(Charset)") +class InputStreamAssert_asString_with_charset_Test { + + private static final Charset TURKISH_CHARSET = Charset.forName("windows-1254"); + + @Test + void should_convert_inputStream_to_a_proper_string_with_specific_encoding() { + // GIVEN + String real = "Gerçek"; + InputStream inputStream = new ByteArrayInputStream(real.getBytes(TURKISH_CHARSET)); + // WHEN/THEN + then(inputStream).asString(TURKISH_CHARSET) + .isEqualTo(real); + } + + @Test + void should_fail_if_actual_is_null() { + // GIVEN + InputStream inputStream = null; + // WHEN + AssertionError error = expectAssertionError(() -> assertThat(inputStream).asString(TURKISH_CHARSET)); + // THEN + then(error).hasMessage(actualIsNull()); + } + + @Test + void should_fail_if_given_charset_is_null() { + // GIVEN + String real = "Gerçek"; + InputStream inputStream = new ByteArrayInputStream(real.getBytes(TURKISH_CHARSET)); + // WHEN/THEN + thenNullPointerException().isThrownBy(() -> assertThat(inputStream).asString(null)) + .withMessage("The charset for converting to a String must not be null"); + } + + @Test + void should_fail_if_actual_does_not_match() { + // GIVEN + String real = "Gerçek"; + InputStream inputStream = new ByteArrayInputStream(real.getBytes(TURKISH_CHARSET)); + // WHEN + AssertionError assertionError = expectAssertionError(() -> assertThat(inputStream).asString(TURKISH_CHARSET) + .isEqualTo("bar")); + // THEN + then(assertionError).hasMessage(shouldBeEqualMessage("\"Gerçek\"", "\"bar\"")) + .isExactlyInstanceOf(AssertionFailedError.class); + } + + @Test + void should_pass_with_soft_assertions() { + // GIVEN + SoftAssertions softly = new SoftAssertions(); + String real = "Gerçek"; + InputStream inputStream = new ByteArrayInputStream(real.getBytes(TURKISH_CHARSET)); + // WHEN/THEN + softly.assertThat(inputStream).asString(TURKISH_CHARSET).isEqualTo(real); + softly.assertAll(); + } + + @Test + void should_fail_with_soft_assertions_capturing_all_errors() { + // GIVEN + SoftAssertions softly = new SoftAssertions(); + String real = "Gerçek"; + InputStream inputStream = new ByteArrayInputStream(real.getBytes(TURKISH_CHARSET)); + // WHEN + softly.assertThat(inputStream) + .asString(TURKISH_CHARSET) + .isEqualTo("bar") + .isBlank(); + AssertionError assertionError = expectAssertionError(softly::assertAll); + // THEN + then(assertionError).hasMessageContainingAll("Multiple Failures (2 failures)", + "-- failure 1 --", + shouldBeEqualMessage("\"Gerçek\"", "\"bar\""), + "-- failure 2 --", + "Expecting blank but was: \"Gerçek\"") + .isExactlyInstanceOf(AssertJMultipleFailuresError.class); + } + + @Test + void should_ignore_test_when_assumption_for_internally_created_hex_string_assertion_fails() { + // GIVEN + String real = "Gerçek"; + InputStream inputStream = new ByteArrayInputStream(real.getBytes(TURKISH_CHARSET)); + // WHEN/THEN + expectAssumptionNotMetException(() -> assumeThat(inputStream).asString(TURKISH_CHARSET).isEqualTo("bar")); + } + + @Test + void should_run_test_when_assumption_for_internally_created_string_passes() { + // GIVEN + String real = "Gerçek"; + InputStream inputStream = new ByteArrayInputStream(real.getBytes(TURKISH_CHARSET)); + // WHEN/THEN + thenCode(() -> assumeThat(inputStream).asString(TURKISH_CHARSET).startsWith("Gerç")).doesNotThrowAnyException(); + } + +} diff --git a/src/test/java/org/assertj/core/api/iterable/IterableAssert_element_Test.java b/src/test/java/org/assertj/core/api/iterable/IterableAssert_element_Test.java index 3041bcd5993..0e86fdb838f 100644 --- a/src/test/java/org/assertj/core/api/iterable/IterableAssert_element_Test.java +++ b/src/test/java/org/assertj/core/api/iterable/IterableAssert_element_Test.java @@ -47,7 +47,7 @@ void should_fail_if_iterable_is_empty() { } @Test - void should_pass_allowing_object_assertions_if_iterable_contains_at_least_one_element() { + void should_pass_allowing_object_assertions_if_iterable_contains_enough_elements() { // WHEN ObjectAssert result = assertThat(iterable).element(1); // THEN diff --git a/src/test/java/org/assertj/core/api/iterable/IterableAssert_element_with_InstanceOfAssertFactory_Test.java b/src/test/java/org/assertj/core/api/iterable/IterableAssert_element_with_InstanceOfAssertFactory_Test.java index 0e106b34cf3..03d16252610 100644 --- a/src/test/java/org/assertj/core/api/iterable/IterableAssert_element_with_InstanceOfAssertFactory_Test.java +++ b/src/test/java/org/assertj/core/api/iterable/IterableAssert_element_with_InstanceOfAssertFactory_Test.java @@ -71,7 +71,7 @@ void should_fail_if_last_element_is_not_an_instance_of_the_factory_type() { // WHEN AssertionError assertionError = expectAssertionError(() -> assertThat(iterable).element(1, INTEGER)); // THEN - then(assertionError).hasMessageContainingAll("Expecting:", "to be an instance of:", "but was instance of:"); + then(assertionError).hasMessageContainingAll("Expecting actual:", "to be an instance of:", "but was instance of:"); } } diff --git a/src/test/java/org/assertj/core/api/iterable/IterableAssert_elements_Test.java b/src/test/java/org/assertj/core/api/iterable/IterableAssert_elements_Test.java new file mode 100644 index 00000000000..630fa483175 --- /dev/null +++ b/src/test/java/org/assertj/core/api/iterable/IterableAssert_elements_Test.java @@ -0,0 +1,112 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api.iterable; + +import static java.util.Collections.emptyList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.util.AssertionsUtil.expectAssertionError; +import static org.assertj.core.util.FailureMessages.actualIsEmpty; +import static org.assertj.core.util.Lists.list; + +import org.assertj.core.api.IterableAssert; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * Tests for {@link IterableAssert#elements(int...)}. + */ +@DisplayName("IterableAssert elements(int...)") +class IterableAssert_elements_Test { + + private final Iterable iterable = list("Homer", "Marge", "Lisa", "Bart", "Maggie"); + + @Test + void should_fail_if_iterable_is_empty() { + // GIVEN + Iterable iterable = emptyList(); + // WHEN + AssertionError assertionError = expectAssertionError(() -> assertThat(iterable).elements(1)); + // THEN + then(assertionError).hasMessage(actualIsEmpty()); + } + + @Test + void should_pass_allowing_object_assertions_if_iterable_contains_enough_elements() { + // WHEN + IterableAssert result = assertThat(iterable).elements(1); + // THEN + result.containsExactly("Marge"); + } + + @Test + void should_pass_allowing_assertions_for_several_elements() { + // WHEN + IterableAssert result = assertThat(iterable).elements(1, 2); + // THEN + result.containsExactly("Marge", "Lisa"); + } + + @Test + void should_pass_allowing_assertions_for_several_unordered_elements() { + // WHEN + IterableAssert result = assertThat(iterable).elements(2, 1); + // THEN + result.containsExactly("Lisa", "Marge"); + } + + @Test + void should_pass_allowing_assertions_for_repeating_elements() { + // WHEN + IterableAssert result = assertThat(iterable).elements(2, 1, 2); + // THEN + result.containsExactly("Lisa", "Marge", "Lisa"); + } + + @Test + void should_fail_if_index_out_of_range() { + // WHEN + AssertionError assertionError = expectAssertionError(() -> assertThat(iterable).elements(5)); + // THEN + then(assertionError).hasMessageContainingAll("check actual size is enough to get element[5]", + "Expecting size of:", + "to be greater than 5 but was 5"); + } + + @Test + void should_fail_if_indices_is_empty() { + assertThatIllegalArgumentException().isThrownBy(() -> assertThat(iterable).elements()) + .withMessageContaining("indices must not be empty"); + } + + @Test + void should_fail_if_indices_is_empty_2() { + assertThatIllegalArgumentException().isThrownBy(() -> assertThat(iterable).elements(new int[0])) + .withMessageContaining("indices must not be empty"); + } + + @Test + void should_fail_if_indices_is_null() { + assertThatIllegalArgumentException().isThrownBy(() -> assertThat(iterable).elements((int[]) null)) + .withMessageContaining("indices must not be null"); + } + + @Test + void should_fail_if_iterable_is_null() { + // WHEN + AssertionError assertionError = expectAssertionError(() -> assertThat((Iterable) null).elements(1)); + // THEN + then(assertionError).hasMessageContaining("Expecting actual not to be null"); + } +} diff --git a/src/test/java/org/assertj/core/api/iterable/IterableAssert_filteredOnNull_Test.java b/src/test/java/org/assertj/core/api/iterable/IterableAssert_filteredOnNull_Test.java index e6a37c24bba..b4698d0206c 100644 --- a/src/test/java/org/assertj/core/api/iterable/IterableAssert_filteredOnNull_Test.java +++ b/src/test/java/org/assertj/core/api/iterable/IterableAssert_filteredOnNull_Test.java @@ -61,6 +61,10 @@ void should_honor_AssertFactory_strongly_typed_navigation_assertions() { assertThat(hobbits, tolkienCharacterAssertFactory).filteredOnNull("name") .element(0) .hasAge(33); + assertThat(hobbits, tolkienCharacterAssertFactory).filteredOnNull("name") + .elements(0) + .first() + .hasAge(33); } @Test @@ -77,6 +81,10 @@ void should_honor_ClassBased_strongly_typed_navigation_assertions() { assertThat(hobbits, TolkienCharacterAssert.class).filteredOnNull("name") .element(0) .hasAge(33); + assertThat(hobbits, TolkienCharacterAssert.class).filteredOnNull("name") + .elements(0) + .first() + .hasAge(33); } @Test diff --git a/src/test/java/org/assertj/core/api/iterable/IterableAssert_filteredOn_Test.java b/src/test/java/org/assertj/core/api/iterable/IterableAssert_filteredOn_Test.java index bc6905eae59..2b91c74f7e9 100644 --- a/src/test/java/org/assertj/core/api/iterable/IterableAssert_filteredOn_Test.java +++ b/src/test/java/org/assertj/core/api/iterable/IterableAssert_filteredOn_Test.java @@ -144,6 +144,10 @@ void should_honor_AssertFactory_strongly_typed_navigation_assertions() { assertThat(hobbits, tolkienCharacterAssertFactory).filteredOn("name", "Frodo") .element(0) .hasAge(33); + assertThat(hobbits, tolkienCharacterAssertFactory).filteredOn("name", "Frodo") + .elements(0) + .first() + .hasAge(33); } @Test @@ -160,6 +164,10 @@ void should_honor_ClassBased_strongly_typed_navigation_assertions() { assertThat(hobbits, TolkienCharacterAssert.class).filteredOn("name", "Frodo") .element(0) .hasAge(33); + assertThat(hobbits, TolkienCharacterAssert.class).filteredOn("name", "Frodo") + .elements(0) + .first() + .hasAge(33); } @Test diff --git a/src/test/java/org/assertj/core/api/iterable/IterableAssert_filteredOn_condition_Test.java b/src/test/java/org/assertj/core/api/iterable/IterableAssert_filteredOn_condition_Test.java index a8e0cd663a6..31d4fd268c7 100644 --- a/src/test/java/org/assertj/core/api/iterable/IterableAssert_filteredOn_condition_Test.java +++ b/src/test/java/org/assertj/core/api/iterable/IterableAssert_filteredOn_condition_Test.java @@ -75,6 +75,10 @@ void should_honor_AssertFactory_strongly_typed_navigation_assertions() { assertThat(hobbits, tolkienCharacterAssertFactory).filteredOn(nameStartingWithFro) .element(0) .hasAge(33); + assertThat(hobbits, tolkienCharacterAssertFactory).filteredOn(nameStartingWithFro) + .elements(0) + .first() + .hasAge(33); } @Test @@ -91,6 +95,10 @@ void should_honor_ClassBased_strongly_typed_navigation_assertions() { assertThat(hobbits, TolkienCharacterAssert.class).filteredOn(nameStartingWithFro) .element(0) .hasAge(33); + assertThat(hobbits, TolkienCharacterAssert.class).filteredOn(nameStartingWithFro) + .elements(0) + .first() + .hasAge(33); } @Test diff --git a/src/test/java/org/assertj/core/api/iterable/IterableAssert_filteredOn_consumer_Test.java b/src/test/java/org/assertj/core/api/iterable/IterableAssert_filteredOn_consumer_Test.java index ee209b9d421..a9fe857104e 100644 --- a/src/test/java/org/assertj/core/api/iterable/IterableAssert_filteredOn_consumer_Test.java +++ b/src/test/java/org/assertj/core/api/iterable/IterableAssert_filteredOn_consumer_Test.java @@ -63,6 +63,10 @@ void should_honor_AssertFactory_strongly_typed_navigation_assertions() { assertThat(hobbits, tolkienCharacterAssertFactory).filteredOnAssertions(nameStartingWithFro) .element(0) .hasAge(33); + assertThat(hobbits, tolkienCharacterAssertFactory).filteredOnAssertions(nameStartingWithFro) + .elements(0) + .first() + .hasAge(33); } @Test @@ -76,6 +80,10 @@ void should_honor_ClassBased_strongly_typed_navigation_assertions() { assertThat(hobbits, TolkienCharacterAssert.class).filteredOnAssertions(nameStartingWithFro) .last() .hasAge(33); + assertThat(hobbits, TolkienCharacterAssert.class).filteredOnAssertions(nameStartingWithFro) + .elements(0) + .first() + .hasAge(33); assertThat(hobbits, TolkienCharacterAssert.class).filteredOnAssertions(nameStartingWithFro) .element(0) .hasAge(33); diff --git a/src/test/java/org/assertj/core/api/iterable/IterableAssert_filteredOn_in_Test.java b/src/test/java/org/assertj/core/api/iterable/IterableAssert_filteredOn_in_Test.java index aa5028bc3d2..b53eac7c096 100644 --- a/src/test/java/org/assertj/core/api/iterable/IterableAssert_filteredOn_in_Test.java +++ b/src/test/java/org/assertj/core/api/iterable/IterableAssert_filteredOn_in_Test.java @@ -114,6 +114,10 @@ void should_honor_AssertFactory_strongly_typed_navigation_assertions() { assertThat(hobbits, tolkienCharacterAssertFactory).filteredOn("name", in("Frodo")) .element(0) .hasAge(33); + assertThat(hobbits, tolkienCharacterAssertFactory).filteredOn("name", in("Frodo")) + .elements(0) + .first() + .hasAge(33); } @Test @@ -130,6 +134,10 @@ void should_honor_ClassBased_strongly_typed_navigation_assertions() { assertThat(hobbits, TolkienCharacterAssert.class).filteredOn("name", in("Frodo")) .element(0) .hasAge(33); + assertThat(hobbits, TolkienCharacterAssert.class).filteredOn("name", in("Frodo")) + .elements(0) + .first() + .hasAge(33); } } diff --git a/src/test/java/org/assertj/core/api/iterable/IterableAssert_filteredOn_predicate_Test.java b/src/test/java/org/assertj/core/api/iterable/IterableAssert_filteredOn_predicate_Test.java index 602c3558f46..a8a00a2dcac 100644 --- a/src/test/java/org/assertj/core/api/iterable/IterableAssert_filteredOn_predicate_Test.java +++ b/src/test/java/org/assertj/core/api/iterable/IterableAssert_filteredOn_predicate_Test.java @@ -61,6 +61,10 @@ void should_honor_AssertFactory_strongly_typed_navigation_assertions() { assertThat(hobbits, tolkienCharacterAssertFactory).filteredOn(nameStartingWithFro) .element(0) .hasAge(33); + assertThat(hobbits, tolkienCharacterAssertFactory).filteredOn(nameStartingWithFro) + .elements(0) + .first() + .hasAge(33); } @Test @@ -77,6 +81,10 @@ void should_honor_ClassBased_strongly_typed_navigation_assertions() { assertThat(hobbits, TolkienCharacterAssert.class).filteredOn(nameStartingWithFro) .element(0) .hasAge(33); + assertThat(hobbits, TolkienCharacterAssert.class).filteredOn(nameStartingWithFro) + .elements(0) + .first() + .hasAge(33); } @Test diff --git a/src/test/java/org/assertj/core/api/iterable/IterableAssert_first_with_InstanceOfAssertFactory_Test.java b/src/test/java/org/assertj/core/api/iterable/IterableAssert_first_with_InstanceOfAssertFactory_Test.java index f73445581e5..da77426778e 100644 --- a/src/test/java/org/assertj/core/api/iterable/IterableAssert_first_with_InstanceOfAssertFactory_Test.java +++ b/src/test/java/org/assertj/core/api/iterable/IterableAssert_first_with_InstanceOfAssertFactory_Test.java @@ -71,7 +71,7 @@ void should_fail_if_first_element_is_not_an_instance_of_the_factory_type() { // WHEN AssertionError assertionError = expectAssertionError(() -> assertThat(iterable).first(INTEGER)); // THEN - then(assertionError).hasMessageContainingAll("Expecting:", "to be an instance of:", "but was instance of:"); + then(assertionError).hasMessageContainingAll("Expecting actual:", "to be an instance of:", "but was instance of:"); } } diff --git a/src/test/java/org/assertj/core/api/iterable/IterableAssert_hasExactlyElementsOfTypes_Test.java b/src/test/java/org/assertj/core/api/iterable/IterableAssert_hasExactlyElementsOfTypes_Test.java new file mode 100644 index 00000000000..48d994415b6 --- /dev/null +++ b/src/test/java/org/assertj/core/api/iterable/IterableAssert_hasExactlyElementsOfTypes_Test.java @@ -0,0 +1,35 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api.iterable; + +import static org.mockito.Mockito.verify; + +import org.assertj.core.api.AbstractIterableAssert; +import org.assertj.core.api.ObjectArrayAssert; +import org.assertj.core.api.ObjectArrayAssertBaseTest; + +/** + * Tests for {@link AbstractIterableAssert#hasExactlyElementsOfTypes(Class...)}. + */ +class IterableAssert_hasExactlyElementsOfTypes_Test extends ObjectArrayAssertBaseTest { + + @Override + protected ObjectArrayAssert invoke_api_method() { + return assertions.hasExactlyElementsOfTypes(Integer.class, Double.class); + } + + @Override + protected void verify_internal_effects() { + verify(arrays).assertHasExactlyElementsOfTypes(getInfo(assertions), getActual(assertions), Integer.class, Double.class); + } +} diff --git a/src/test/java/org/assertj/core/api/iterable/IterableAssert_hasOnlyOneElementSatisfying_Test.java b/src/test/java/org/assertj/core/api/iterable/IterableAssert_hasOnlyOneElementSatisfying_Test.java index 7b7d66e5d60..371b0eccccf 100644 --- a/src/test/java/org/assertj/core/api/iterable/IterableAssert_hasOnlyOneElementSatisfying_Test.java +++ b/src/test/java/org/assertj/core/api/iterable/IterableAssert_hasOnlyOneElementSatisfying_Test.java @@ -46,7 +46,7 @@ void fails_if_iterable_has_only_one_element_and_that_element_does_not_satisfy_th assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> { List jedis = asList(new Jedi("Yoda", "red")); assertThat(jedis).hasOnlyOneElementSatisfying(yoda -> assertThat(yoda.getName()).startsWith("L")); - }).withMessage(format("%nExpecting:%n \"Yoda\"%nto start with:%n \"L\"%n")); + }).withMessage(format("%nExpecting actual:%n \"Yoda\"%nto start with:%n \"L\"%n")); } @Test @@ -57,7 +57,7 @@ void fails_if_iterable_has_only_one_element_and_that_element_does_not_satisfy_on assertThat(yoda.getName()).startsWith("Y"); assertThat(yoda.getName()).startsWith("L"); }); - }).withMessage(format("%nExpecting:%n \"Yoda\"%nto start with:%n \"L\"%n")); + }).withMessage(format("%nExpecting actual:%n \"Yoda\"%nto start with:%n \"L\"%n")); } @Test @@ -73,8 +73,8 @@ void fails_if_iterable_has_only_one_element_and_that_element_does_not_satisfy_th }); }); - assertThat(assertionError).hasMessageContaining(format("Expecting:%n \"Yoda\"%nto start with:%n \"L\"")) - .hasMessageContaining(format("Expecting:%n \"Yoda\"%nto start with:%n \"M\"")); + assertThat(assertionError).hasMessageContaining(format("Expecting actual:%n \"Yoda\"%nto start with:%n \"L\"")) + .hasMessageContaining(format("Expecting actual:%n \"Yoda\"%nto start with:%n \"M\"")); } @Test diff --git a/src/test/java/org/assertj/core/api/iterable/IterableAssert_last_with_InstanceOfAssertFactory_Test.java b/src/test/java/org/assertj/core/api/iterable/IterableAssert_last_with_InstanceOfAssertFactory_Test.java index 4ff77b76647..38033e507d1 100644 --- a/src/test/java/org/assertj/core/api/iterable/IterableAssert_last_with_InstanceOfAssertFactory_Test.java +++ b/src/test/java/org/assertj/core/api/iterable/IterableAssert_last_with_InstanceOfAssertFactory_Test.java @@ -71,7 +71,7 @@ void should_fail_if_last_element_is_not_an_instance_of_the_factory_type() { // WHEN AssertionError assertionError = expectAssertionError(() -> assertThat(iterable).last(INTEGER)); // THEN - then(assertionError).hasMessageContainingAll("Expecting:", "to be an instance of:", "but was instance of:"); + then(assertionError).hasMessageContainingAll("Expecting actual:", "to be an instance of:", "but was instance of:"); } } diff --git a/src/test/java/org/assertj/core/api/iterable/IterableAssert_satisfiesExactlyInAnyOrder_Test.java b/src/test/java/org/assertj/core/api/iterable/IterableAssert_satisfiesExactlyInAnyOrder_Test.java index 366cee301f3..0fb9abd666b 100644 --- a/src/test/java/org/assertj/core/api/iterable/IterableAssert_satisfiesExactlyInAnyOrder_Test.java +++ b/src/test/java/org/assertj/core/api/iterable/IterableAssert_satisfiesExactlyInAnyOrder_Test.java @@ -12,6 +12,7 @@ */ package org.assertj.core.api.iterable; +import static org.assertj.core.util.Arrays.array; import static org.assertj.core.util.Lists.list; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -26,7 +27,6 @@ * * @author Michael Grafl */ -@SuppressWarnings("unchecked") class IterableAssert_satisfiesExactlyInAnyOrder_Test extends IterableAssertBaseTest { private Consumer consumer = mock(Consumer.class); @@ -43,6 +43,6 @@ protected ConcreteIterableAssert invoke_api_method() { @Override protected void verify_internal_effects() { - verify(iterables).assertSatisfiesExactlyInAnyOrder(getInfo(assertions), getActual(assertions), consumer); + verify(iterables).assertSatisfiesExactlyInAnyOrder(getInfo(assertions), getActual(assertions), array(consumer)); } } diff --git a/src/test/java/org/assertj/core/api/iterable/IterableAssert_singleElement_with_InstanceOfAssertFactory_Test.java b/src/test/java/org/assertj/core/api/iterable/IterableAssert_singleElement_with_InstanceOfAssertFactory_Test.java index d33351cb88b..4c07ede2fdf 100644 --- a/src/test/java/org/assertj/core/api/iterable/IterableAssert_singleElement_with_InstanceOfAssertFactory_Test.java +++ b/src/test/java/org/assertj/core/api/iterable/IterableAssert_singleElement_with_InstanceOfAssertFactory_Test.java @@ -71,7 +71,7 @@ void should_fail_if_first_element_is_not_an_instance_of_the_factory_type() { // WHEN AssertionError assertionError = expectAssertionError(() -> assertThat(babySimpsons).singleElement(INTEGER)); // THEN - then(assertionError).hasMessageContainingAll("Expecting:", "to be an instance of:", "but was instance of:"); + then(assertionError).hasMessageContainingAll("Expecting actual:", "to be an instance of:", "but was instance of:"); } @Test diff --git a/src/test/java/org/assertj/core/api/iterable/IterableAssert_usingComparatorForType_Test.java b/src/test/java/org/assertj/core/api/iterable/IterableAssert_usingComparatorForType_Test.java index 39ec95e8b6d..f9a707977f8 100644 --- a/src/test/java/org/assertj/core/api/iterable/IterableAssert_usingComparatorForType_Test.java +++ b/src/test/java/org/assertj/core/api/iterable/IterableAssert_usingComparatorForType_Test.java @@ -35,6 +35,7 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +@SuppressWarnings("deprecation") @DisplayName("IterableAssert usingComparatorForType") class IterableAssert_usingComparatorForType_Test extends IterableAssertBaseTest { @@ -97,13 +98,6 @@ void should_use_comparator_for_type_when_using_field_by_field_element_comparator .contains(other, "any"); } - @Test - void should_use_comparator_for_type_when_using_recursive_field_by_field_element_comparator() { - assertThat(asList(actual, "some")).usingComparatorForType(ALWAY_EQUALS_STRING, String.class) - .usingRecursiveFieldByFieldElementComparator() - .contains(other, "any"); - } - @Test void should_only_use_comparator_on_fields_element_but_not_the_element_itself() { // GIVEN @@ -123,8 +117,8 @@ void should_only_use_comparator_on_fields_element_but_not_the_element_itself() { + " [\"any\"]%n" + "when comparing values using field/property by field/property comparator on all fields/properties except [\"name\"]%n" + "Comparators used:%n" - + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], String -> AlwaysEqualComparator}%n" - + "- for elements (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}")); + + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], String -> AlwaysEqualComparator, Path -> lexicographic comparator (Path natural order)}%n" + + "- for elements (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], Path -> lexicographic comparator (Path natural order)}")); } @Test @@ -137,10 +131,9 @@ void should_use_comparator_set_last_on_elements() { @Test void should_be_able_to_replace_a_registered_comparator_by_type() { - assertThat(asList(actual, actual)).usingComparatorForType(NEVER_EQUALS_STRING, String.class) - .usingComparatorForType(ALWAY_EQUALS_STRING, String.class) - .usingFieldByFieldElementComparator() - .contains(other, other); + assertThat(list("foo", "bar")).usingComparatorForType(NEVER_EQUALS_STRING, String.class) + .usingComparatorForType(ALWAY_EQUALS_STRING, String.class) + .contains("baz"); } @Test @@ -171,8 +164,8 @@ void should_fail_because_of_comparator_set_last() { + " [Luke the Jedi]%n" + "when comparing values using field/property by field/property comparator on all fields/properties%n" + "Comparators used:%n" - + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], String -> org.assertj.core.test.NeverEqualComparator}%n" - + "- for elements (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], String -> AlwaysEqualComparator}")); + + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], String -> org.assertj.core.test.NeverEqualComparator, Path -> lexicographic comparator (Path natural order)}%n" + + "- for elements (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], String -> AlwaysEqualComparator, Path -> lexicographic comparator (Path natural order)}")); } } diff --git a/src/test/java/org/assertj/core/api/iterable/IterableAssert_usingElementComparatorIgnoringFields_Test.java b/src/test/java/org/assertj/core/api/iterable/IterableAssert_usingElementComparatorIgnoringFields_Test.java index d9f318ef982..abbd7cc6746 100644 --- a/src/test/java/org/assertj/core/api/iterable/IterableAssert_usingElementComparatorIgnoringFields_Test.java +++ b/src/test/java/org/assertj/core/api/iterable/IterableAssert_usingElementComparatorIgnoringFields_Test.java @@ -12,9 +12,9 @@ */ package org.assertj.core.api.iterable; -import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.test.AlwaysEqualComparator.ALWAY_EQUALS_STRING; +import static org.assertj.core.util.Lists.list; import java.util.Comparator; @@ -28,6 +28,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +@SuppressWarnings("deprecation") class IterableAssert_usingElementComparatorIgnoringFields_Test extends IterableAssertBaseTest { private Iterables iterablesBefore; @@ -57,9 +58,9 @@ void should_be_able_to_use_a_comparator_for_specified_fields_of_elements_when_us Jedi actual = new Jedi("Yoda", "green"); Jedi other = new Jedi("Luke", "green"); - assertThat(singletonList(actual)).usingComparatorForElementFieldsWithNames(ALWAY_EQUALS_STRING, "name") - .usingElementComparatorIgnoringFields("lightSaberColor") - .contains(other); + assertThat(list(actual)).usingComparatorForElementFieldsWithNames(ALWAY_EQUALS_STRING, "name") + .usingElementComparatorIgnoringFields("lightSaberColor") + .contains(other); } @Test @@ -68,10 +69,10 @@ void comparators_for_element_field_names_should_have_precedence_over_comparators Jedi actual = new Jedi("Yoda", "green"); Jedi other = new Jedi("Luke", "green"); - assertThat(singletonList(actual)).usingComparatorForElementFieldsWithNames(ALWAY_EQUALS_STRING, "name") - .usingComparatorForElementFieldsWithType(comparator, String.class) - .usingElementComparatorIgnoringFields("lightSaberColor") - .contains(other); + assertThat(list(actual)).usingComparatorForElementFieldsWithNames(ALWAY_EQUALS_STRING, "name") + .usingComparatorForElementFieldsWithType(comparator, String.class) + .usingElementComparatorIgnoringFields("lightSaberColor") + .contains(other); } @Test @@ -79,9 +80,9 @@ void should_be_able_to_use_a_comparator_for_element_fields_with_specified_type_u Jedi actual = new Jedi("Yoda", "green"); Jedi other = new Jedi("Luke", "blue"); - assertThat(singletonList(actual)).usingComparatorForElementFieldsWithType(ALWAY_EQUALS_STRING, String.class) - .usingElementComparatorIgnoringFields("name") - .contains(other); + assertThat(list(actual)).usingComparatorForElementFieldsWithType(ALWAY_EQUALS_STRING, String.class) + .usingElementComparatorIgnoringFields("name") + .contains(other); } } diff --git a/src/test/java/org/assertj/core/api/iterable/IterableAssert_usingElementComparatorOnFields_Test.java b/src/test/java/org/assertj/core/api/iterable/IterableAssert_usingElementComparatorOnFields_Test.java index 08ca5404d39..b4498fd0e52 100644 --- a/src/test/java/org/assertj/core/api/iterable/IterableAssert_usingElementComparatorOnFields_Test.java +++ b/src/test/java/org/assertj/core/api/iterable/IterableAssert_usingElementComparatorOnFields_Test.java @@ -12,9 +12,9 @@ */ package org.assertj.core.api.iterable; -import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.test.AlwaysEqualComparator.ALWAY_EQUALS_STRING; +import static org.assertj.core.util.Lists.list; import java.util.Comparator; @@ -28,6 +28,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +@SuppressWarnings("deprecation") class IterableAssert_usingElementComparatorOnFields_Test extends IterableAssertBaseTest { private Iterables iterablesBefore; @@ -49,8 +50,7 @@ protected void verify_internal_effects() { assertThat(iterables.getComparisonStrategy()).isInstanceOf(ComparatorBasedComparisonStrategy.class); ComparatorBasedComparisonStrategy strategy = (ComparatorBasedComparisonStrategy) iterables.getComparisonStrategy(); assertThat(strategy.getComparator()).isInstanceOf(ExtendedByTypesComparator.class); - assertThat(((OnFieldsComparator) ((ExtendedByTypesComparator) strategy.getComparator()) - .getComparator()).getFields()).containsOnly("field"); + assertThat(((OnFieldsComparator) ((ExtendedByTypesComparator) strategy.getComparator()).getComparator()).getFields()).containsOnly("field"); } @Test @@ -58,9 +58,9 @@ void should_be_able_to_use_a_comparator_for_specified_fields_of_elements_when_us Jedi actual = new Jedi("Yoda", "green"); Jedi other = new Jedi("Luke", "green"); - assertThat(singletonList(actual)).usingComparatorForElementFieldsWithNames(ALWAY_EQUALS_STRING, "name") - .usingElementComparatorOnFields("name", "lightSaberColor") - .contains(other); + assertThat(list(actual)).usingComparatorForElementFieldsWithNames(ALWAY_EQUALS_STRING, "name") + .usingElementComparatorOnFields("name", "lightSaberColor") + .contains(other); } @Test @@ -69,10 +69,10 @@ void comparators_for_element_field_names_should_have_precedence_over_comparators Jedi actual = new Jedi("Yoda", "green"); Jedi other = new Jedi("Luke", "green"); - assertThat(singletonList(actual)).usingComparatorForElementFieldsWithNames(ALWAY_EQUALS_STRING, "name") - .usingComparatorForElementFieldsWithType(comparator, String.class) - .usingElementComparatorOnFields("name", "lightSaberColor") - .contains(other); + assertThat(list(actual)).usingComparatorForElementFieldsWithNames(ALWAY_EQUALS_STRING, "name") + .usingComparatorForElementFieldsWithType(comparator, String.class) + .usingElementComparatorOnFields("name", "lightSaberColor") + .contains(other); } @Test @@ -80,9 +80,9 @@ void should_be_able_to_use_a_comparator_for_element_fields_with_specified_type_u Jedi actual = new Jedi("Yoda", "green"); Jedi other = new Jedi("Luke", "blue"); - assertThat(singletonList(actual)).usingComparatorForElementFieldsWithType(ALWAY_EQUALS_STRING, String.class) - .usingElementComparatorOnFields("name", "lightSaberColor") - .contains(other); + assertThat(list(actual)).usingComparatorForElementFieldsWithType(ALWAY_EQUALS_STRING, String.class) + .usingElementComparatorOnFields("name", "lightSaberColor") + .contains(other); } } diff --git a/src/test/java/org/assertj/core/api/iterable/IterableAssert_usingFieldByFieldElementComparator_Test.java b/src/test/java/org/assertj/core/api/iterable/IterableAssert_usingFieldByFieldElementComparator_Test.java index cf7c080c775..07045f1b11a 100644 --- a/src/test/java/org/assertj/core/api/iterable/IterableAssert_usingFieldByFieldElementComparator_Test.java +++ b/src/test/java/org/assertj/core/api/iterable/IterableAssert_usingFieldByFieldElementComparator_Test.java @@ -34,6 +34,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +@SuppressWarnings("deprecation") class IterableAssert_usingFieldByFieldElementComparator_Test extends IterableAssertBaseTest { private Iterables iterablesBefore; @@ -142,8 +143,8 @@ void failed_isEqualTo_assertion_using_field_by_field_element_comparator() { + "%n" + "when comparing elements using field/property by field/property comparator on all fields/properties%n" + "Comparators used:%n" - + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}%n" - + "- for elements (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}")); + + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], Path -> lexicographic comparator (Path natural order)}%n" + + "- for elements (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], Path -> lexicographic comparator (Path natural order)}")); } @Test @@ -153,14 +154,14 @@ void failed_isIn_assertion_using_field_by_field_element_comparator() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(list1).usingFieldByFieldElementComparator() .isIn(singletonList(list2))) - .withMessage(format("%nExpecting:%n" + .withMessage(format("%nExpecting actual:%n" + " [Foo(id=id, bar=1)]%n" + "to be in:%n" + " [[Foo(id=id, bar=2)]]%n" + "when comparing elements using field/property by field/property comparator on all fields/properties%n" + "Comparators used:%n" - + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}%n" - + "- for elements (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}")); + + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], Path -> lexicographic comparator (Path natural order)}%n" + + "- for elements (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], Path -> lexicographic comparator (Path natural order)}")); } @Test diff --git a/src/test/java/org/assertj/core/api/iterable/IterableAssert_usingRecursiveFieldByFieldElementComparatorIgnoringFields_Test.java b/src/test/java/org/assertj/core/api/iterable/IterableAssert_usingRecursiveFieldByFieldElementComparatorIgnoringFields_Test.java new file mode 100644 index 00000000000..5065c17a418 --- /dev/null +++ b/src/test/java/org/assertj/core/api/iterable/IterableAssert_usingRecursiveFieldByFieldElementComparatorIgnoringFields_Test.java @@ -0,0 +1,69 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api.iterable; + +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.util.Lists.list; + +import org.assertj.core.api.ConcreteIterableAssert; +import org.assertj.core.api.IterableAssertBaseTest; +import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration; +import org.assertj.core.internal.ComparatorBasedComparisonStrategy; +import org.assertj.core.internal.ConfigurableRecursiveFieldByFieldComparator; +import org.assertj.core.internal.IterableElementComparisonStrategy; +import org.assertj.core.internal.Iterables; +import org.assertj.core.test.Name; +import org.assertj.core.test.Player; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class IterableAssert_usingRecursiveFieldByFieldElementComparatorIgnoringFields_Test extends IterableAssertBaseTest { + + private Iterables iterablesBefore; + + @BeforeEach + void before() { + iterablesBefore = getIterables(assertions); + } + + @Override + protected ConcreteIterableAssert invoke_api_method() { + return assertions.usingRecursiveFieldByFieldElementComparatorIgnoringFields("field"); + } + + @Override + protected void verify_internal_effects() { + then(iterablesBefore).isNotSameAs(getIterables(assertions)); + then(getIterables(assertions).getComparisonStrategy()).isInstanceOf(ComparatorBasedComparisonStrategy.class); + then(getObjects(assertions).getComparisonStrategy()).isInstanceOf(IterableElementComparisonStrategy.class); + RecursiveComparisonConfiguration recursiveComparisonConfiguration = RecursiveComparisonConfiguration.builder() + .withIgnoredFields("field") + .build(); + ConfigurableRecursiveFieldByFieldComparator expectedComparator = new ConfigurableRecursiveFieldByFieldComparator(recursiveComparisonConfiguration); + then(getIterables(assertions).getComparator()).isEqualTo(expectedComparator); + then(getObjects(assertions).getComparisonStrategy()).extracting("elementComparator").isEqualTo(expectedComparator); + } + + @Test + void should_ignore_given_fields_recursively() { + // GIVEN + Player rose = new Player(new Name("Derrick", "Rose"), "Chicago Bulls"); + rose.nickname = new Name("Crazy", "Dunks"); + Player jalen = new Player(new Name("Jalen", "Rose"), "Chicago Bulls"); + jalen.nickname = new Name("Crazy", "Defense"); + // WHEN/THEN + then(list(rose)).usingRecursiveFieldByFieldElementComparatorIgnoringFields("name.first", "nickname.last") + .contains(jalen); + } + +} diff --git a/src/test/java/org/assertj/core/api/iterable/IterableAssert_usingRecursiveFieldByFieldElementComparatorOnFields_Test.java b/src/test/java/org/assertj/core/api/iterable/IterableAssert_usingRecursiveFieldByFieldElementComparatorOnFields_Test.java new file mode 100644 index 00000000000..4b3a0b21df7 --- /dev/null +++ b/src/test/java/org/assertj/core/api/iterable/IterableAssert_usingRecursiveFieldByFieldElementComparatorOnFields_Test.java @@ -0,0 +1,70 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api.iterable; + +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.util.Lists.list; + +import org.assertj.core.api.ConcreteIterableAssert; +import org.assertj.core.api.IterableAssertBaseTest; +import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration; +import org.assertj.core.internal.ComparatorBasedComparisonStrategy; +import org.assertj.core.internal.ConfigurableRecursiveFieldByFieldComparator; +import org.assertj.core.internal.IterableElementComparisonStrategy; +import org.assertj.core.internal.Iterables; +import org.assertj.core.test.Name; +import org.assertj.core.test.Player; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class IterableAssert_usingRecursiveFieldByFieldElementComparatorOnFields_Test extends IterableAssertBaseTest { + + private Iterables iterablesBefore; + + @BeforeEach + void before() { + iterablesBefore = getIterables(assertions); + } + + @Override + protected ConcreteIterableAssert invoke_api_method() { + return assertions.usingRecursiveFieldByFieldElementComparatorOnFields("field"); + } + + @Override + protected void verify_internal_effects() { + Iterables iterables = getIterables(assertions); + then(iterablesBefore).isNotSameAs(iterables); + then(iterables.getComparisonStrategy()).isInstanceOf(ComparatorBasedComparisonStrategy.class); + then(getObjects(assertions).getComparisonStrategy()).isInstanceOf(IterableElementComparisonStrategy.class); + RecursiveComparisonConfiguration recursiveComparisonConfiguration = RecursiveComparisonConfiguration.builder() + .withComparedFields("field") + .build(); + ConfigurableRecursiveFieldByFieldComparator expectedComparator = new ConfigurableRecursiveFieldByFieldComparator(recursiveComparisonConfiguration); + then(iterables.getComparator()).isEqualTo(expectedComparator); + then(getObjects(assertions).getComparisonStrategy()).extracting("elementComparator").isEqualTo(expectedComparator); + } + + @Test + void should_compare_given_fields_recursively_and_none_other() { + // GIVEN + Player rose = new Player(new Name("Derrick", "Rose"), "Chicago Bulls"); + rose.nickname = new Name("Crazy", "Dunks"); + Player jalen = new Player(new Name("Jalen", "Rose"), "Chicago Bulls"); + jalen.nickname = new Name("Crazy", "Defense"); + // WHEN/THEN + then(list(rose)).usingRecursiveFieldByFieldElementComparatorOnFields("name.last", "team", "nickname.first") + .contains(jalen); + } + +} diff --git a/src/test/java/org/assertj/core/api/iterable/IterableAssert_usingRecursiveFieldByFieldElementComparator_Test.java b/src/test/java/org/assertj/core/api/iterable/IterableAssert_usingRecursiveFieldByFieldElementComparator_Test.java index 9b181ddb71c..03d4c71553f 100644 --- a/src/test/java/org/assertj/core/api/iterable/IterableAssert_usingRecursiveFieldByFieldElementComparator_Test.java +++ b/src/test/java/org/assertj/core/api/iterable/IterableAssert_usingRecursiveFieldByFieldElementComparator_Test.java @@ -15,16 +15,19 @@ import static java.lang.String.format; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.assertj.core.test.AlwaysEqualComparator.ALWAY_EQUALS_STRING; +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.configuration.ConfigurationProvider.CONFIGURATION_PROVIDER; import static org.assertj.core.test.ErrorMessagesForTest.shouldBeEqualMessage; +import static org.assertj.core.util.AssertionsUtil.expectAssertionError; +import static org.assertj.core.util.Lists.list; -import java.util.Comparator; import java.util.List; import org.assertj.core.api.ConcreteIterableAssert; import org.assertj.core.api.IterableAssertBaseTest; +import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration; import org.assertj.core.internal.ComparatorBasedComparisonStrategy; +import org.assertj.core.internal.ConfigurableRecursiveFieldByFieldComparator; import org.assertj.core.internal.IterableElementComparisonStrategy; import org.assertj.core.internal.Iterables; import org.junit.jupiter.api.BeforeEach; @@ -32,6 +35,8 @@ class IterableAssert_usingRecursiveFieldByFieldElementComparator_Test extends IterableAssertBaseTest { + private static final String DEFAULT_RECURSIVE_COMPARATOR_DESCRIPTION = CONFIGURATION_PROVIDER.representation() + .toStringOf(new ConfigurableRecursiveFieldByFieldComparator(new RecursiveComparisonConfiguration())); private Iterables iterablesBefore; @BeforeEach @@ -49,6 +54,10 @@ protected void verify_internal_effects() { assertThat(iterablesBefore).isNotSameAs(getIterables(assertions)); assertThat(getIterables(assertions).getComparisonStrategy()).isInstanceOf(ComparatorBasedComparisonStrategy.class); assertThat(getObjects(assertions).getComparisonStrategy()).isInstanceOf(IterableElementComparisonStrategy.class); + RecursiveComparisonConfiguration recursiveComparisonConfiguration = new RecursiveComparisonConfiguration(); + ConfigurableRecursiveFieldByFieldComparator expectedComparator = new ConfigurableRecursiveFieldByFieldComparator(recursiveComparisonConfiguration); + then(getIterables(assertions).getComparator()).isEqualTo(expectedComparator); + then(getObjects(assertions).getComparisonStrategy()).extracting("elementComparator").isEqualTo(expectedComparator); } @Test @@ -70,15 +79,12 @@ void failed_isEqualTo_assertion_using_recursive_field_by_field_element_comparato List list1 = singletonList(new Foo("id", new Bar(1))); List list2 = singletonList(new Foo("id", new Bar(2))); - assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(list1).usingRecursiveFieldByFieldElementComparator() - .isEqualTo(list2)) - .withMessage(format(shouldBeEqualMessage("[Foo(id=id, bar=Bar(id=1))]", - "[Foo(id=id, bar=Bar(id=2))]") - + "%n" - + "when comparing elements using recursive field/property by field/property comparator on all fields/properties%n" - + "Comparators used:%n" - + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}%n" - + "- for elements (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}")); + AssertionError assertionError = expectAssertionError(() -> assertThat(list1).usingRecursiveFieldByFieldElementComparator() + .isEqualTo(list2)); + + then(assertionError).hasMessage(format(shouldBeEqualMessage("[Foo(id=id, bar=Bar(id=1))]", "[Foo(id=id, bar=Bar(id=2))]") + + "%n" + + "when comparing elements using %s", DEFAULT_RECURSIVE_COMPARATOR_DESCRIPTION)); } @Test @@ -86,54 +92,14 @@ void failed_isIn_assertion_using_recursive_field_by_field_element_comparator() { List list1 = singletonList(new Foo("id", new Bar(1))); List list2 = singletonList(new Foo("id", new Bar(2))); - assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(list1).usingRecursiveFieldByFieldElementComparator() - .isIn(singletonList(list2))) - .withMessage(format("%nExpecting:%n" - + " [Foo(id=id, bar=Bar(id=1))]%n" - + "to be in:%n" - + " [[Foo(id=id, bar=Bar(id=2))]]%n" - + "when comparing elements using recursive field/property by field/property comparator on all fields/properties%n" - + "Comparators used:%n" - + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}%n" - + "- for elements (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}")); - } - - @Test - void should_be_able_to_use_a_comparator_for_specified_fields_of_elements_when_using_recursive_field_by_field_element_comparator() { - Foo actual = new Foo("1", new Bar(1)); - Foo other = new Foo("1", new Bar(2)); - final class AlwaysEqualIntegerComparator implements Comparator { - @Override - public int compare(Integer o1, Integer o2) { - return 0; - } - } - - assertThat(singletonList(actual)).usingComparatorForElementFieldsWithNames(new AlwaysEqualIntegerComparator(), - "bar.id") - .usingRecursiveFieldByFieldElementComparator().contains(other); - } - - @Test - void comparators_for_element_field_names_should_have_precedence_over_comparators_for_element_field_types_when_using_recursive_field_by_field_element_comparator() { - Comparator comparator = (o1, o2) -> o1.compareTo(o2); - Foo actual = new Foo("1", new Bar(1)); - Foo other = new Foo("2", new Bar(1)); - - assertThat(singletonList(actual)).usingComparatorForElementFieldsWithNames(ALWAY_EQUALS_STRING, "id") - .usingComparatorForElementFieldsWithType(comparator, String.class) - .usingRecursiveFieldByFieldElementComparator() - .contains(other); - } - - @Test - void should_be_able_to_use_a_comparator_for_element_fields_with_specified_type_when_using_recursive_field_by_field_element_comparator() { - Foo actual = new Foo("1", new Bar(1)); - Foo other = new Foo("2", new Bar(1)); + AssertionError assertionError = expectAssertionError(() -> assertThat(list1).usingRecursiveFieldByFieldElementComparator() + .isIn(list(list2))); - assertThat(singletonList(actual)).usingComparatorForElementFieldsWithType(ALWAY_EQUALS_STRING, String.class) - .usingRecursiveFieldByFieldElementComparator() - .contains(other); + then(assertionError).hasMessage(format("%nExpecting actual:%n" + + " [Foo(id=id, bar=Bar(id=1))]%n" + + "to be in:%n" + + " [[Foo(id=id, bar=Bar(id=2))]]%n" + + "when comparing elements using %s", DEFAULT_RECURSIVE_COMPARATOR_DESCRIPTION)); } public static class Foo { diff --git a/src/test/java/org/assertj/core/api/junit/jupiter/CustomSoftAssertions.java b/src/test/java/org/assertj/core/api/junit/jupiter/CustomSoftAssertions.java index baffd1fce16..f2a08688a62 100644 --- a/src/test/java/org/assertj/core/api/junit/jupiter/CustomSoftAssertions.java +++ b/src/test/java/org/assertj/core/api/junit/jupiter/CustomSoftAssertions.java @@ -16,7 +16,7 @@ import org.assertj.core.api.AbstractSoftAssertions; import org.assertj.core.api.IntegerAssert; -import org.assertj.core.api.ProxyableListAssert; +import org.assertj.core.api.ListAssert; class CustomSoftAssertions extends AbstractSoftAssertions { public IntegerAssert expectThat(int value) { @@ -24,7 +24,7 @@ public IntegerAssert expectThat(int value) { } @SuppressWarnings("unchecked") - public ProxyableListAssert expectThat(List actual) { - return proxy(ProxyableListAssert.class, List.class, actual); + public ListAssert expectThat(List actual) { + return proxy(ListAssert.class, List.class, actual); } } \ No newline at end of file diff --git a/src/test/java/org/assertj/core/api/junit/jupiter/SoftAssertionsExtensionAPIIntegrationTest.java b/src/test/java/org/assertj/core/api/junit/jupiter/SoftAssertionsExtensionAPIIntegrationTest.java index 5739886f0b7..170d13d5376 100644 --- a/src/test/java/org/assertj/core/api/junit/jupiter/SoftAssertionsExtensionAPIIntegrationTest.java +++ b/src/test/java/org/assertj/core/api/junit/jupiter/SoftAssertionsExtensionAPIIntegrationTest.java @@ -27,6 +27,7 @@ import org.assertj.core.api.AssertionErrorCollector; import org.assertj.core.api.AutoCloseableSoftAssertions; import org.assertj.core.api.BDDSoftAssertions; +import org.assertj.core.api.DefaultAssertionErrorCollector; import org.assertj.core.api.SoftAssertions; import org.assertj.core.error.AssertJMultipleFailuresError; import org.junit.jupiter.api.BeforeAll; @@ -64,6 +65,7 @@ void beforeEach(ExtensionContext context) { provider.assertThat("something").isEqualTo("nothing"); assertThat(provider.assertionErrorsCollected()).as("beforeEach:after assert").hasSize(1); AssertionErrorCollector collector = SoftAssertionsExtension.getAssertionErrorCollector(context); + assertThat(collector).isInstanceOf(DefaultAssertionErrorCollector.class); assertThat(provider.getDelegate()).contains(collector); map.put(context.getTestMethod().get().getName(), collector); } diff --git a/src/test/java/org/assertj/core/api/list/ListAssert_filteredOn_condition_with_navigation_Test.java b/src/test/java/org/assertj/core/api/list/ListAssert_filteredOn_condition_with_navigation_Test.java index 2aeab84a352..8012cbb2fa7 100644 --- a/src/test/java/org/assertj/core/api/list/ListAssert_filteredOn_condition_with_navigation_Test.java +++ b/src/test/java/org/assertj/core/api/list/ListAssert_filteredOn_condition_with_navigation_Test.java @@ -40,6 +40,10 @@ void should_honor_AssertFactory_strongly_typed_navigation_assertions() { assertThat(hobbits, tolkienCharacterAssertFactory).filteredOn(nameStartingWithFro) .element(0) .hasAge(33); + assertThat(hobbits, tolkienCharacterAssertFactory).filteredOn(nameStartingWithFro) + .elements(0) + .first() + .hasAge(33); } @Test @@ -56,6 +60,10 @@ void should_honor_ClassBased_strongly_typed_navigation_assertions() { assertThat(hobbits, TolkienCharacterAssert.class).filteredOn(nameStartingWithFro) .element(0) .hasAge(33); + assertThat(hobbits, TolkienCharacterAssert.class).filteredOn(nameStartingWithFro) + .elements(0) + .first() + .hasAge(33); } } diff --git a/src/test/java/org/assertj/core/api/list/ListAssert_filteredOn_consumer_with_navigation_Test.java b/src/test/java/org/assertj/core/api/list/ListAssert_filteredOn_consumer_with_navigation_Test.java index 05b38b0f9e2..98d824384f3 100644 --- a/src/test/java/org/assertj/core/api/list/ListAssert_filteredOn_consumer_with_navigation_Test.java +++ b/src/test/java/org/assertj/core/api/list/ListAssert_filteredOn_consumer_with_navigation_Test.java @@ -40,6 +40,10 @@ void should_honor_AssertFactory_strongly_typed_navigation_assertions() { assertThat(hobbits, tolkienCharacterAssertFactory).filteredOnAssertions(nameStartingWithFro) .element(0) .hasAge(33); + assertThat(hobbits, tolkienCharacterAssertFactory).filteredOnAssertions(nameStartingWithFro) + .elements(0) + .first() + .hasAge(33); } @Test @@ -56,6 +60,10 @@ void should_honor_ClassBased_strongly_typed_navigation_assertions() { assertThat(hobbits, TolkienCharacterAssert.class).filteredOnAssertions(nameStartingWithFro) .element(0) .hasAge(33); + assertThat(hobbits, TolkienCharacterAssert.class).filteredOnAssertions(nameStartingWithFro) + .elements(0) + .first() + .hasAge(33); } } diff --git a/src/test/java/org/assertj/core/api/list/ListAssert_filteredOn_function_with_navigation_Test.java b/src/test/java/org/assertj/core/api/list/ListAssert_filteredOn_function_with_navigation_Test.java index 776ddd620eb..242d48792a5 100644 --- a/src/test/java/org/assertj/core/api/list/ListAssert_filteredOn_function_with_navigation_Test.java +++ b/src/test/java/org/assertj/core/api/list/ListAssert_filteredOn_function_with_navigation_Test.java @@ -38,6 +38,10 @@ void should_honor_AssertFactory_strongly_typed_navigation_assertions() { assertThat(hobbits, tolkienCharacterAssertFactory).filteredOn(TolkienCharacter::getName, "Frodo") .element(0) .hasAge(33); + assertThat(hobbits, tolkienCharacterAssertFactory).filteredOn(TolkienCharacter::getName, "Frodo") + .elements(0) + .first() + .hasAge(33); } @Test @@ -54,6 +58,10 @@ void should_honor_class_based_strongly_typed_navigation_assertions() { assertThat(hobbits, TolkienCharacterAssert.class).filteredOn(TolkienCharacter::getName, "Frodo") .element(0) .hasAge(33); + assertThat(hobbits, TolkienCharacterAssert.class).filteredOn(TolkienCharacter::getName, "Frodo") + .elements(0) + .first() + .hasAge(33); } } diff --git a/src/test/java/org/assertj/core/api/list/ListAssert_filteredOn_null_with_navigation_Test.java b/src/test/java/org/assertj/core/api/list/ListAssert_filteredOn_null_with_navigation_Test.java index 4b13d70254c..e5b8d305481 100644 --- a/src/test/java/org/assertj/core/api/list/ListAssert_filteredOn_null_with_navigation_Test.java +++ b/src/test/java/org/assertj/core/api/list/ListAssert_filteredOn_null_with_navigation_Test.java @@ -40,6 +40,10 @@ void should_honor_AssertFactory_strongly_typed_navigation_assertions() { assertThat(hobbits, tolkienCharacterAssertFactory).filteredOnNull("name") .element(0) .hasAge(33); + assertThat(hobbits, tolkienCharacterAssertFactory).filteredOnNull("name") + .elements(0) + .first() + .hasAge(33); } @Test @@ -56,6 +60,10 @@ void should_honor_ClassBased_strongly_typed_navigation_assertions() { assertThat(hobbits, TolkienCharacterAssert.class).filteredOnNull("name") .element(0) .hasAge(33); + assertThat(hobbits, TolkienCharacterAssert.class).filteredOnNull("name") + .elements(0) + .first() + .hasAge(33); } protected static List hobbitsWithoutNames() { diff --git a/src/test/java/org/assertj/core/api/list/ListAssert_filteredOn_predicate_with_navigation_Test.java b/src/test/java/org/assertj/core/api/list/ListAssert_filteredOn_predicate_with_navigation_Test.java index 35f6c242015..40808c75404 100644 --- a/src/test/java/org/assertj/core/api/list/ListAssert_filteredOn_predicate_with_navigation_Test.java +++ b/src/test/java/org/assertj/core/api/list/ListAssert_filteredOn_predicate_with_navigation_Test.java @@ -40,6 +40,10 @@ void should_honor_AssertFactory_strongly_typed_navigation_assertions() { assertThat(hobbits, tolkienCharacterAssertFactory).filteredOn(nameStartingWithFro) .element(0) .hasAge(33); + assertThat(hobbits, tolkienCharacterAssertFactory).filteredOn(nameStartingWithFro) + .elements(0) + .first() + .hasAge(33); } @Test @@ -56,6 +60,10 @@ void should_honor_ClassBased_strongly_typed_navigation_assertions() { assertThat(hobbits, TolkienCharacterAssert.class).filteredOn(nameStartingWithFro) .element(0) .hasAge(33); + assertThat(hobbits, TolkienCharacterAssert.class).filteredOn(nameStartingWithFro) + .elements(0) + .first() + .hasAge(33); } } diff --git a/src/test/java/org/assertj/core/api/list/ListAssert_filteredOn_using_filterOperator_with_navigation_Test.java b/src/test/java/org/assertj/core/api/list/ListAssert_filteredOn_using_filterOperator_with_navigation_Test.java index e3a55a39e91..69724786c58 100644 --- a/src/test/java/org/assertj/core/api/list/ListAssert_filteredOn_using_filterOperator_with_navigation_Test.java +++ b/src/test/java/org/assertj/core/api/list/ListAssert_filteredOn_using_filterOperator_with_navigation_Test.java @@ -40,6 +40,10 @@ void should_honor_AssertFactory_strongly_typed_navigation_assertions() { assertThat(hobbits, tolkienCharacterAssertFactory).filteredOn("name", in("Frodo")) .element(0) .hasAge(33); + assertThat(hobbits, tolkienCharacterAssertFactory).filteredOn("name", in("Frodo")) + .elements(0) + .first() + .hasAge(33); } @Test @@ -56,6 +60,10 @@ void should_honor_ClassBased_strongly_typed_navigation_assertions() { assertThat(hobbits, TolkienCharacterAssert.class).filteredOn("name", in("Frodo")) .element(0) .hasAge(33); + assertThat(hobbits, TolkienCharacterAssert.class).filteredOn("name", in("Frodo")) + .elements(0) + .first() + .hasAge(33); } } diff --git a/src/test/java/org/assertj/core/api/list/ListAssert_filteredOn_with_navigation_Test.java b/src/test/java/org/assertj/core/api/list/ListAssert_filteredOn_with_navigation_Test.java index b411966567f..1884f7b0867 100644 --- a/src/test/java/org/assertj/core/api/list/ListAssert_filteredOn_with_navigation_Test.java +++ b/src/test/java/org/assertj/core/api/list/ListAssert_filteredOn_with_navigation_Test.java @@ -38,6 +38,10 @@ void should_honor_AssertFactory_strongly_typed_navigation_assertions() { assertThat(hobbits, tolkienCharacterAssertFactory).filteredOn("name", "Frodo") .element(0) .hasAge(33); + assertThat(hobbits, tolkienCharacterAssertFactory).filteredOn("name", "Frodo") + .elements(0) + .first() + .hasAge(33); } @Test @@ -54,5 +58,9 @@ void should_honor_ClassBased_strongly_typed_navigation_assertions() { assertThat(hobbits, TolkienCharacterAssert.class).filteredOn("name", "Frodo") .element(0) .hasAge(33); + assertThat(hobbits, TolkienCharacterAssert.class).filteredOn("name", "Frodo") + .elements(0) + .first() + .hasAge(33); } } diff --git a/src/test/java/org/assertj/core/api/list/ListAssert_usingElementComparatorIgnoringFields_Test.java b/src/test/java/org/assertj/core/api/list/ListAssert_usingElementComparatorIgnoringFields_Test.java index 1ebbdb099fe..365af1aae42 100644 --- a/src/test/java/org/assertj/core/api/list/ListAssert_usingElementComparatorIgnoringFields_Test.java +++ b/src/test/java/org/assertj/core/api/list/ListAssert_usingElementComparatorIgnoringFields_Test.java @@ -25,6 +25,7 @@ import org.assertj.core.internal.Lists; import org.junit.jupiter.api.BeforeEach; +@SuppressWarnings("deprecation") class ListAssert_usingElementComparatorIgnoringFields_Test extends ListAssertBaseTest { private Lists listsBefore; @@ -51,12 +52,10 @@ protected void verify_internal_effects() { assertThat(lists.getComparisonStrategy()).isInstanceOf(ComparatorBasedComparisonStrategy.class); Comparator listsElementComparator = ((ComparatorBasedComparisonStrategy) lists.getComparisonStrategy()).getComparator(); assertThat(listsElementComparator).isInstanceOf(ExtendedByTypesComparator.class); - assertThat(((IgnoringFieldsComparator) ((ExtendedByTypesComparator) listsElementComparator) - .getComparator()).getFields()).containsOnly("field"); + assertThat(((IgnoringFieldsComparator) ((ExtendedByTypesComparator) listsElementComparator).getComparator()).getFields()).containsOnly("field"); Comparator iterablesElementComparator = ((ComparatorBasedComparisonStrategy) iterables.getComparisonStrategy()).getComparator(); assertThat(iterablesElementComparator).isInstanceOf(ExtendedByTypesComparator.class); - assertThat(((IgnoringFieldsComparator) ((ExtendedByTypesComparator) iterablesElementComparator) - .getComparator()).getFields()).containsOnly("field"); + assertThat(((IgnoringFieldsComparator) ((ExtendedByTypesComparator) iterablesElementComparator).getComparator()).getFields()).containsOnly("field"); } } diff --git a/src/test/java/org/assertj/core/api/list/ListAssert_usingElementComparatorOnFields_Test.java b/src/test/java/org/assertj/core/api/list/ListAssert_usingElementComparatorOnFields_Test.java index 8e6c9ca4504..01fcb939287 100644 --- a/src/test/java/org/assertj/core/api/list/ListAssert_usingElementComparatorOnFields_Test.java +++ b/src/test/java/org/assertj/core/api/list/ListAssert_usingElementComparatorOnFields_Test.java @@ -25,6 +25,7 @@ import org.assertj.core.internal.OnFieldsComparator; import org.junit.jupiter.api.BeforeEach; +@SuppressWarnings("deprecation") class ListAssert_usingElementComparatorOnFields_Test extends ListAssertBaseTest { private Lists listsBefore; @@ -49,12 +50,10 @@ protected void verify_internal_effects() { assertThat(iterables).isNotSameAs(iterablesBefore); assertThat(iterables.getComparisonStrategy()).isInstanceOf(ComparatorBasedComparisonStrategy.class); assertThat(lists.getComparisonStrategy()).isInstanceOf(ComparatorBasedComparisonStrategy.class); - Comparator listsElementComparator = ((ExtendedByTypesComparator) ((ComparatorBasedComparisonStrategy) - lists.getComparisonStrategy()).getComparator()).getComparator(); + Comparator listsElementComparator = ((ExtendedByTypesComparator) ((ComparatorBasedComparisonStrategy) lists.getComparisonStrategy()).getComparator()).getComparator(); assertThat(listsElementComparator).isInstanceOf(OnFieldsComparator.class); assertThat(((OnFieldsComparator) listsElementComparator).getFields()).containsOnly("field"); - Comparator iterablesElementComparator = ((ExtendedByTypesComparator) ((ComparatorBasedComparisonStrategy) - iterables.getComparisonStrategy()).getComparator()).getComparator(); + Comparator iterablesElementComparator = ((ExtendedByTypesComparator) ((ComparatorBasedComparisonStrategy) iterables.getComparisonStrategy()).getComparator()).getComparator(); assertThat(iterablesElementComparator).isInstanceOf(OnFieldsComparator.class); assertThat(((OnFieldsComparator) iterablesElementComparator).getFields()).containsOnly("field"); } diff --git a/src/test/java/org/assertj/core/api/list/ListAssert_usingFieldByFieldElementComparator_Test.java b/src/test/java/org/assertj/core/api/list/ListAssert_usingFieldByFieldElementComparator_Test.java index 5dec60816d7..7a69a53b3e0 100644 --- a/src/test/java/org/assertj/core/api/list/ListAssert_usingFieldByFieldElementComparator_Test.java +++ b/src/test/java/org/assertj/core/api/list/ListAssert_usingFieldByFieldElementComparator_Test.java @@ -25,6 +25,7 @@ import org.assertj.core.internal.Lists; import org.junit.jupiter.api.BeforeEach; +@SuppressWarnings("deprecation") class ListAssert_usingFieldByFieldElementComparator_Test extends ListAssertBaseTest { private Lists listsBefore; @@ -49,11 +50,9 @@ protected void verify_internal_effects() { assertThat(iterables).isNotSameAs(iterablesBefore); assertThat(iterables.getComparisonStrategy()).isInstanceOf(ComparatorBasedComparisonStrategy.class); assertThat(lists.getComparisonStrategy()).isInstanceOf(ComparatorBasedComparisonStrategy.class); - Comparator listsElementComparator = ((ExtendedByTypesComparator) ((ComparatorBasedComparisonStrategy) lists - .getComparisonStrategy()).getComparator()).getComparator(); + Comparator listsElementComparator = ((ExtendedByTypesComparator) ((ComparatorBasedComparisonStrategy) lists.getComparisonStrategy()).getComparator()).getComparator(); assertThat(listsElementComparator).isInstanceOf(FieldByFieldComparator.class); - Comparator iterablesElementComparator = ((ExtendedByTypesComparator) ((ComparatorBasedComparisonStrategy) - iterables.getComparisonStrategy()).getComparator()).getComparator(); + Comparator iterablesElementComparator = ((ExtendedByTypesComparator) ((ComparatorBasedComparisonStrategy) iterables.getComparisonStrategy()).getComparator()).getComparator(); assertThat(iterablesElementComparator).isInstanceOf(FieldByFieldComparator.class); } diff --git a/src/test/java/org/assertj/core/api/localdatetime/LocalDateTimeAssert_isEqualToIgnoringHours_Test.java b/src/test/java/org/assertj/core/api/localdatetime/LocalDateTimeAssert_isEqualToIgnoringHours_Test.java index 11648cf27d9..d63729c4bfe 100644 --- a/src/test/java/org/assertj/core/api/localdatetime/LocalDateTimeAssert_isEqualToIgnoringHours_Test.java +++ b/src/test/java/org/assertj/core/api/localdatetime/LocalDateTimeAssert_isEqualToIgnoringHours_Test.java @@ -38,7 +38,7 @@ void should_fail_if_actual_is_not_equal_to_given_localdatetime_with_hour_ignored // WHEN AssertionError assertionError = expectAssertionError(() -> assertThat(refLocalDateTime).isEqualToIgnoringHours(refLocalDateTime.minusHours(1))); // THEN - then(assertionError).hasMessage(format("%nExpecting:%n 2000-01-02T00:00 (java.time.LocalDateTime)%nto have same year, month and day as:%n 2000-01-01T23:00 (java.time.LocalDateTime)%nbut had not.")); + then(assertionError).hasMessage(format("%nExpecting actual:%n 2000-01-02T00:00 (java.time.LocalDateTime)%nto have same year, month and day as:%n 2000-01-01T23:00 (java.time.LocalDateTime)%nbut had not.")); } @Test @@ -46,7 +46,7 @@ void should_fail_as_hours_fields_are_different_even_if_time_difference_is_less_t // WHEN AssertionError assertionError = expectAssertionError(() -> assertThat(refLocalDateTime).isEqualToIgnoringHours(refLocalDateTime.minusNanos(1))); // THEN - then(assertionError).hasMessage(format("%nExpecting:%n 2000-01-02T00:00 (java.time.LocalDateTime)%nto have same year, month and day as:%n 2000-01-01T23:59:59.999999999 (java.time.LocalDateTime)%nbut had not.")); + then(assertionError).hasMessage(format("%nExpecting actual:%n 2000-01-02T00:00 (java.time.LocalDateTime)%nto have same year, month and day as:%n 2000-01-01T23:59:59.999999999 (java.time.LocalDateTime)%nbut had not.")); } @Test diff --git a/src/test/java/org/assertj/core/api/localdatetime/LocalDateTimeAssert_isEqualToIgnoringMinutes_Test.java b/src/test/java/org/assertj/core/api/localdatetime/LocalDateTimeAssert_isEqualToIgnoringMinutes_Test.java index befcb4057e0..6bcd2eb8565 100644 --- a/src/test/java/org/assertj/core/api/localdatetime/LocalDateTimeAssert_isEqualToIgnoringMinutes_Test.java +++ b/src/test/java/org/assertj/core/api/localdatetime/LocalDateTimeAssert_isEqualToIgnoringMinutes_Test.java @@ -38,7 +38,7 @@ void should_fail_if_actual_is_not_equal_to_given_localdatetime_with_minute_ignor // WHEN AssertionError assertionError = expectAssertionError(() -> assertThat(refLocalDateTime).isEqualToIgnoringMinutes(refLocalDateTime.minusMinutes(1))); // THEN - then(assertionError).hasMessage(format("%nExpecting:%n 2000-01-01T23:00 (java.time.LocalDateTime)%nto have same year, month, day and hour as:%n 2000-01-01T22:59 (java.time.LocalDateTime)%nbut had not.")); + then(assertionError).hasMessage(format("%nExpecting actual:%n 2000-01-01T23:00 (java.time.LocalDateTime)%nto have same year, month, day and hour as:%n 2000-01-01T22:59 (java.time.LocalDateTime)%nbut had not.")); } @Test @@ -46,7 +46,7 @@ void should_fail_as_minutes_fields_are_different_even_if_time_difference_is_less // WHEN AssertionError assertionError = expectAssertionError(() -> assertThat(refLocalDateTime).isEqualToIgnoringMinutes(refLocalDateTime.minusNanos(1))); // THEN - then(assertionError).hasMessage(format("%nExpecting:%n 2000-01-01T23:00 (java.time.LocalDateTime)%nto have same year, month, day and hour as:%n 2000-01-01T22:59:59.999999999 (java.time.LocalDateTime)%nbut had not.")); + then(assertionError).hasMessage(format("%nExpecting actual:%n 2000-01-01T23:00 (java.time.LocalDateTime)%nto have same year, month, day and hour as:%n 2000-01-01T22:59:59.999999999 (java.time.LocalDateTime)%nbut had not.")); } @Test diff --git a/src/test/java/org/assertj/core/api/localdatetime/LocalDateTimeAssert_isEqualToIgnoringNanoseconds_Test.java b/src/test/java/org/assertj/core/api/localdatetime/LocalDateTimeAssert_isEqualToIgnoringNanoseconds_Test.java index ef3b154e7dd..73d058ab0bb 100644 --- a/src/test/java/org/assertj/core/api/localdatetime/LocalDateTimeAssert_isEqualToIgnoringNanoseconds_Test.java +++ b/src/test/java/org/assertj/core/api/localdatetime/LocalDateTimeAssert_isEqualToIgnoringNanoseconds_Test.java @@ -39,7 +39,7 @@ void should_fail_if_actual_is_not_equal_to_given_localdatetime_with_nanoseconds_ // WHEN AssertionError assertionError = expectAssertionError(() -> assertThat(refLocalDateTime).isEqualToIgnoringNanos(refLocalDateTime.plusSeconds(1))); // THEN - then(assertionError).hasMessage(format("%nExpecting:%n 2000-01-01T00:00:01 (java.time.LocalDateTime)%nto have same year, month, day, hour, minute and second as:%n 2000-01-01T00:00:02 (java.time.LocalDateTime)%nbut had not.")); + then(assertionError).hasMessage(format("%nExpecting actual:%n 2000-01-01T00:00:01 (java.time.LocalDateTime)%nto have same year, month, day, hour, minute and second as:%n 2000-01-01T00:00:02 (java.time.LocalDateTime)%nbut had not.")); } @Test @@ -47,7 +47,7 @@ void should_fail_as_seconds_fields_are_different_even_if_time_difference_is_less // WHEN AssertionError assertionError = expectAssertionError(() -> assertThat(refLocalDateTime).isEqualToIgnoringNanos(refLocalDateTime.minusNanos(1))); // THEN - then(assertionError).hasMessage(format("%nExpecting:%n 2000-01-01T00:00:01 (java.time.LocalDateTime)%nto have same year, month, day, hour, minute and second as:%n 2000-01-01T00:00:00.999999999 (java.time.LocalDateTime)%nbut had not.")); + then(assertionError).hasMessage(format("%nExpecting actual:%n 2000-01-01T00:00:01 (java.time.LocalDateTime)%nto have same year, month, day, hour, minute and second as:%n 2000-01-01T00:00:00.999999999 (java.time.LocalDateTime)%nbut had not.")); } @Test diff --git a/src/test/java/org/assertj/core/api/localdatetime/LocalDateTimeAssert_isEqualToIgnoringSeconds_Test.java b/src/test/java/org/assertj/core/api/localdatetime/LocalDateTimeAssert_isEqualToIgnoringSeconds_Test.java index 5d14301345d..6a016360572 100644 --- a/src/test/java/org/assertj/core/api/localdatetime/LocalDateTimeAssert_isEqualToIgnoringSeconds_Test.java +++ b/src/test/java/org/assertj/core/api/localdatetime/LocalDateTimeAssert_isEqualToIgnoringSeconds_Test.java @@ -39,7 +39,7 @@ void should_fail_if_actual_is_not_equal_to_given_localdatetime_with_second_ignor // WHEN AssertionError assertionError = expectAssertionError(() -> assertThat(refLocalDateTime).isEqualToIgnoringSeconds(refLocalDateTime.plusMinutes(1))); // THEN - then(assertionError).hasMessage(format("%nExpecting:%n 2000-01-01T23:51 (java.time.LocalDateTime)%nto have same year, month, day, hour and minute as:%n 2000-01-01T23:52 (java.time.LocalDateTime)%nbut had not.")); + then(assertionError).hasMessage(format("%nExpecting actual:%n 2000-01-01T23:51 (java.time.LocalDateTime)%nto have same year, month, day, hour and minute as:%n 2000-01-01T23:52 (java.time.LocalDateTime)%nbut had not.")); } @Test @@ -47,7 +47,7 @@ void should_fail_as_seconds_fields_are_different_even_if_time_difference_is_less // WHEN AssertionError assertionError = expectAssertionError(() -> assertThat(refLocalDateTime).isEqualToIgnoringSeconds(refLocalDateTime.minusNanos(1))); // THEN - then(assertionError).hasMessage(format("%nExpecting:%n 2000-01-01T23:51 (java.time.LocalDateTime)%nto have same year, month, day, hour and minute as:%n 2000-01-01T23:50:59.999999999 (java.time.LocalDateTime)%nbut had not.")); + then(assertionError).hasMessage(format("%nExpecting actual:%n 2000-01-01T23:51 (java.time.LocalDateTime)%nto have same year, month, day, hour and minute as:%n 2000-01-01T23:50:59.999999999 (java.time.LocalDateTime)%nbut had not.")); } @Test diff --git a/src/test/java/org/assertj/core/api/localtime/LocalTimeAssert_hasSameHourAs_Test.java b/src/test/java/org/assertj/core/api/localtime/LocalTimeAssert_hasSameHourAs_Test.java index 7ce7fcc8d2b..f278d011915 100644 --- a/src/test/java/org/assertj/core/api/localtime/LocalTimeAssert_hasSameHourAs_Test.java +++ b/src/test/java/org/assertj/core/api/localtime/LocalTimeAssert_hasSameHourAs_Test.java @@ -36,7 +36,7 @@ void should_pass_if_actual_andexpected_have_same_hour() { void should_fail_if_actual_is_not_equal_to_given_localtimetime_with_minute_ignored() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(refLocalTime).hasSameHourAs(refLocalTime.minusMinutes(1))) .withMessage(format("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " 23:00%n" + "to have same hour as:%n" + " 22:59%n" + @@ -47,7 +47,7 @@ void should_fail_if_actual_is_not_equal_to_given_localtimetime_with_minute_ignor void should_fail_as_minutes_fields_are_different_even_if_time_difference_is_less_than_a_minute() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(refLocalTime).hasSameHourAs(refLocalTime.minusNanos(1))) .withMessage(format("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " 23:00%n" + "to have same hour as:%n" + " 22:59:59.999999999%n" + diff --git a/src/test/java/org/assertj/core/api/localtime/LocalTimeAssert_isEqualToIgnoringNanoseconds_Test.java b/src/test/java/org/assertj/core/api/localtime/LocalTimeAssert_isEqualToIgnoringNanoseconds_Test.java index 956373f8abd..be7cb6f7c60 100644 --- a/src/test/java/org/assertj/core/api/localtime/LocalTimeAssert_isEqualToIgnoringNanoseconds_Test.java +++ b/src/test/java/org/assertj/core/api/localtime/LocalTimeAssert_isEqualToIgnoringNanoseconds_Test.java @@ -36,7 +36,7 @@ void should_pass_if_actual_is_equal_to_other_ignoring_nanosecond_fields() { @Test void should_fail_if_actual_is_not_equal_to_given_localtimetime_with_nanoseconds_ignored() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(refLocalTime).isEqualToIgnoringNanos(refLocalTime.plusSeconds(1))) - .withMessage(format("%nExpecting:%n" + + .withMessage(format("%nExpecting actual:%n" + " 00:00:01%n" + "to have same hour, minute and second as:%n" + " 00:00:02%n" + @@ -46,7 +46,7 @@ void should_fail_if_actual_is_not_equal_to_given_localtimetime_with_nanoseconds_ @Test void should_fail_as_seconds_fields_are_different_even_if_time_difference_is_less_than_a_second() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(refLocalTime).isEqualToIgnoringNanos(refLocalTime.minusNanos(1))) - .withMessage(format("%nExpecting:%n" + + .withMessage(format("%nExpecting actual:%n" + " 00:00:01%n" + "to have same hour, minute and second as:%n" + " 00:00:00.999999999%n" + diff --git a/src/test/java/org/assertj/core/api/localtime/LocalTimeAssert_isEqualToIgnoringSeconds_Test.java b/src/test/java/org/assertj/core/api/localtime/LocalTimeAssert_isEqualToIgnoringSeconds_Test.java index 975e893ef45..ec0532d6ee2 100644 --- a/src/test/java/org/assertj/core/api/localtime/LocalTimeAssert_isEqualToIgnoringSeconds_Test.java +++ b/src/test/java/org/assertj/core/api/localtime/LocalTimeAssert_isEqualToIgnoringSeconds_Test.java @@ -35,7 +35,7 @@ void should_pass_if_actual_is_equal_to_other_ignoring_second_fields() { @Test void should_fail_if_actual_is_not_equal_to_given_localtimetime_with_second_ignored() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(refLocalTime).isEqualToIgnoringSeconds(refLocalTime.plusMinutes(1))) - .withMessage(format("%nExpecting:%n" + + .withMessage(format("%nExpecting actual:%n" + " 23:51%n" + "to have same hour and minute as:%n" + " 23:52%n" + @@ -45,7 +45,7 @@ void should_fail_if_actual_is_not_equal_to_given_localtimetime_with_second_ignor @Test void should_fail_as_seconds_fields_are_different_even_if_time_difference_is_less_than_a_second() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(refLocalTime).isEqualToIgnoringSeconds(refLocalTime.minusNanos(1))) - .withMessage(format("%nExpecting:%n" + + .withMessage(format("%nExpecting actual:%n" + " 23:51%n" + "to have same hour and minute as:%n" + " 23:50:59.999999999%n" + diff --git a/src/test/java/org/assertj/core/api/map/MapAssert_containsAllEntries_Test.java b/src/test/java/org/assertj/core/api/map/MapAssert_containsAllEntriesOf_Test.java similarity index 68% rename from src/test/java/org/assertj/core/api/map/MapAssert_containsAllEntries_Test.java rename to src/test/java/org/assertj/core/api/map/MapAssert_containsAllEntriesOf_Test.java index 7faac823389..de4da58ea1e 100644 --- a/src/test/java/org/assertj/core/api/map/MapAssert_containsAllEntries_Test.java +++ b/src/test/java/org/assertj/core/api/map/MapAssert_containsAllEntriesOf_Test.java @@ -12,8 +12,7 @@ */ package org.assertj.core.api.map; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.util.Arrays.array; +import static org.assertj.core.api.BDDAssertions.then; import static org.mockito.Mockito.verify; import java.util.Map; @@ -22,10 +21,7 @@ import org.assertj.core.api.MapAssertBaseTest; import org.junit.jupiter.api.Test; -class MapAssert_containsAllEntries_Test extends MapAssertBaseTest { - - final Map.Entry[] entries = array(javaMapEntry("firstKey", "firstValue"), - javaMapEntry("secondKey", "secondValue")); +class MapAssert_containsAllEntriesOf_Test extends MapAssertBaseTest { @Override protected MapAssert invoke_api_method() { @@ -34,12 +30,15 @@ protected MapAssert invoke_api_method() { @Override protected void verify_internal_effects() { - verify(maps).assertContains(getInfo(assertions), getActual(assertions), entries); + verify(maps).assertContainsAllEntriesOf(getInfo(assertions), getActual(assertions), + map("firstKey", "firstValue", "secondKey", "secondValue")); } @Test void invoke_api_like_user() { + // GIVEN Map actual = map("firstKey", "firstValue", "secondKey", "secondValue"); - assertThat(actual).containsAllEntriesOf(map("secondKey", "secondValue", "firstKey", "firstValue")); + // WHEN/THEN + then(actual).containsAllEntriesOf(map("secondKey", "secondValue", "firstKey", "firstValue")); } } diff --git a/src/test/java/org/assertj/core/api/map/MapAssert_containsKey_Test.java b/src/test/java/org/assertj/core/api/map/MapAssert_containsKey_Test.java index c91bb0ecfdb..e8c60ead19f 100644 --- a/src/test/java/org/assertj/core/api/map/MapAssert_containsKey_Test.java +++ b/src/test/java/org/assertj/core/api/map/MapAssert_containsKey_Test.java @@ -12,15 +12,16 @@ */ package org.assertj.core.api.map; +import static org.assertj.core.util.Arrays.array; +import static org.mockito.Mockito.verify; + import org.assertj.core.api.MapAssert; import org.assertj.core.api.MapAssertBaseTest; -import static org.mockito.Mockito.verify; - /** * Tests for {@link MapAssert#containsKey(Object)}. - * + * * @author Nicolas François */ class MapAssert_containsKey_Test extends MapAssertBaseTest { @@ -32,6 +33,6 @@ protected MapAssert invoke_api_method() { @Override protected void verify_internal_effects() { - verify(maps).assertContainsKeys(getInfo(assertions), getActual(assertions), "key1"); + verify(maps).assertContainsKeys(getInfo(assertions), getActual(assertions), array("key1")); } } diff --git a/src/test/java/org/assertj/core/api/map/MapAssert_containsOnlyKeys_with_Iterable_Test.java b/src/test/java/org/assertj/core/api/map/MapAssert_containsOnlyKeys_with_Iterable_Test.java index 3eccbc8bb29..67005b869a2 100644 --- a/src/test/java/org/assertj/core/api/map/MapAssert_containsOnlyKeys_with_Iterable_Test.java +++ b/src/test/java/org/assertj/core/api/map/MapAssert_containsOnlyKeys_with_Iterable_Test.java @@ -12,33 +12,35 @@ */ package org.assertj.core.api.map; +import static java.util.Collections.singleton; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; import static org.assertj.core.test.Maps.mapOf; -import static org.assertj.core.util.Arrays.array; import static org.assertj.core.util.Lists.list; -import static org.mockito.Mockito.doCallRealMethod; import static org.mockito.Mockito.verify; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.List; import java.util.Map; import org.assertj.core.api.MapAssert; import org.assertj.core.api.MapAssertBaseTest; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; +@DisplayName("MapAssert containsOnlyKeys(Iterable)") class MapAssert_containsOnlyKeys_with_Iterable_Test extends MapAssertBaseTest { @Override protected MapAssert invoke_api_method() { - doCallRealMethod().when(maps).assertContainsOnlyKeys(getInfo(assertions), getActual(assertions), list(1, 2)); return assertions.containsOnlyKeys(list(1, 2)); } @Override protected void verify_internal_effects() { verify(maps).assertContainsOnlyKeys(getInfo(assertions), getActual(assertions), list(1, 2)); - verify(maps).assertContainsOnlyKeys(getInfo(assertions), getActual(assertions), "keys iterable", array(1, 2)); } @Test @@ -49,4 +51,27 @@ void should_work_with_iterable_of_subclass_of_key_type() { List ints = list(1, 2); // not a List assertThat(map).containsOnlyKeys(ints); } + + @Nested + @DisplayName("given Path parameter") + class MapAssert_containsOnlyKeys_with_Path_Test extends MapAssertBaseTest { + + private final Path path = Paths.get("file"); + + @Override + protected MapAssert invoke_api_method() { + return assertions.containsOnlyKeys(path); + } + + @Override + protected void verify_internal_effects() { + // Path parameter should be treated as a single key and not as an Iterable, therefore the target for verification is + // assertContainsOnlyKeys(AssertionInfo, Map, K...) instead of + // assertContainsOnlyKeys(AssertionInfo, Map, Iterable). + // Casting the Path parameter to Object allows to invoke the overloaded method expecting vararg keys. + verify(maps).assertContainsOnlyKeys(getInfo(assertions), getActual(assertions), singleton(path)); + } + + } + } diff --git a/src/test/java/org/assertj/core/api/map/MapAssert_containsOnlyKeys_with_Path_Test.java b/src/test/java/org/assertj/core/api/map/MapAssert_containsOnlyKeys_with_Path_Test.java deleted file mode 100644 index c04a38f0d25..00000000000 --- a/src/test/java/org/assertj/core/api/map/MapAssert_containsOnlyKeys_with_Path_Test.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - * Copyright 2012-2021 the original author or authors. - */ -package org.assertj.core.api.map; - -import static org.mockito.Mockito.verify; - -import java.nio.file.Path; -import java.nio.file.Paths; - -import org.assertj.core.api.MapAssert; -import org.assertj.core.api.MapAssertBaseTest; -import org.junit.jupiter.api.DisplayName; - -/** - * Tests for {@link MapAssert#containsOnlyKeys(Iterable)} with {@link Path} parameter. - * - * @author Stefano Cordio - */ -@DisplayName("MapAssert containsOnlyKeys(Path)") -class MapAssert_containsOnlyKeys_with_Path_Test extends MapAssertBaseTest { - - private final Path path = Paths.get("file"); - - @Override - protected MapAssert invoke_api_method() { - return assertions.containsOnlyKeys(path); - } - - @Override - protected void verify_internal_effects() { - // Path parameter should be treated as a single key and not as an Iterable, therefore the target for verification is - // assertContainsOnlyKeys(AssertionInfo, Map, K...) instead of - // assertContainsOnlyKeys(AssertionInfo, Map, Iterable). - // Casting the Path parameter to Object allows to invoke the overloaded method expecting vararg keys. - verify(maps).assertContainsOnlyKeys(getInfo(assertions), getActual(assertions), (Object) path); - } - -} diff --git a/src/test/java/org/assertj/core/api/map/MapAssert_containsValues_Test.java b/src/test/java/org/assertj/core/api/map/MapAssert_containsValues_Test.java index 3b0cede6ac7..bf251d966c4 100644 --- a/src/test/java/org/assertj/core/api/map/MapAssert_containsValues_Test.java +++ b/src/test/java/org/assertj/core/api/map/MapAssert_containsValues_Test.java @@ -12,11 +12,12 @@ */ package org.assertj.core.api.map; +import static org.assertj.core.util.Arrays.array; +import static org.mockito.Mockito.verify; + import org.assertj.core.api.MapAssert; import org.assertj.core.api.MapAssertBaseTest; -import static org.mockito.Mockito.verify; - /** * Tests for {@link org.assertj.core.api.MapAssert#containsValue(Object)}. * @@ -31,6 +32,6 @@ protected MapAssert invoke_api_method() { @Override protected void verify_internal_effects() { - verify(maps).assertContainsValues(getInfo(assertions), getActual(assertions), "value1", "value2"); + verify(maps).assertContainsValues(getInfo(assertions), getActual(assertions), array("value1", "value2")); } } diff --git a/src/test/java/org/assertj/core/api/map/MapAssert_doesNotContainKey_Test.java b/src/test/java/org/assertj/core/api/map/MapAssert_doesNotContainKey_Test.java index 478c458e703..724897fadb3 100644 --- a/src/test/java/org/assertj/core/api/map/MapAssert_doesNotContainKey_Test.java +++ b/src/test/java/org/assertj/core/api/map/MapAssert_doesNotContainKey_Test.java @@ -12,15 +12,16 @@ */ package org.assertj.core.api.map; +import static org.assertj.core.util.Arrays.array; +import static org.mockito.Mockito.verify; + import org.assertj.core.api.MapAssert; import org.assertj.core.api.MapAssertBaseTest; -import static org.mockito.Mockito.verify; - /** * Tests for {@link MapAssert#doesNotContainKey(Object)}. - * + * * @author Nicolas François */ class MapAssert_doesNotContainKey_Test extends MapAssertBaseTest { @@ -32,6 +33,6 @@ protected MapAssert invoke_api_method() { @Override protected void verify_internal_effects() { - verify(maps).assertDoesNotContainKeys(getInfo(assertions), getActual(assertions), "key1"); + verify(maps).assertDoesNotContainKeys(getInfo(assertions), getActual(assertions), array("key1")); } } diff --git a/src/test/java/org/assertj/core/api/map/MapAssert_extractingByKey_with_Key_and_InstanceOfAssertFactory_Test.java b/src/test/java/org/assertj/core/api/map/MapAssert_extractingByKey_with_Key_and_InstanceOfAssertFactory_Test.java index f108929a7ec..1160fe1cedb 100644 --- a/src/test/java/org/assertj/core/api/map/MapAssert_extractingByKey_with_Key_and_InstanceOfAssertFactory_Test.java +++ b/src/test/java/org/assertj/core/api/map/MapAssert_extractingByKey_with_Key_and_InstanceOfAssertFactory_Test.java @@ -85,7 +85,7 @@ void should_fail_if_extracted_value_is_not_an_instance_of_the_assert_factory_typ // WHEN AssertionError error = expectAssertionError(() -> assertThat(map).extractingByKey(NAME, as(INTEGER))); // THEN - then(error).hasMessageContainingAll("Expecting:", "to be an instance of:", "but was instance of:"); + then(error).hasMessageContainingAll("Expecting actual:", "to be an instance of:", "but was instance of:"); } @Test diff --git a/src/test/java/org/assertj/core/api/map/MapAssert_extracting_Test.java b/src/test/java/org/assertj/core/api/map/MapAssert_extracting_Test.java index d970bc441f3..ea5786fb7b1 100644 --- a/src/test/java/org/assertj/core/api/map/MapAssert_extracting_Test.java +++ b/src/test/java/org/assertj/core/api/map/MapAssert_extracting_Test.java @@ -13,13 +13,15 @@ package org.assertj.core.api.map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.catchThrowable; +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.util.AssertionsUtil.expectAssertionError; import static org.assertj.core.util.FailureMessages.actualIsNull; import java.util.HashMap; import java.util.Map; +import org.assertj.core.util.introspection.IntrospectionError; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -34,68 +36,91 @@ void setup() { map = new HashMap<>(); map.put(NAME, "kawhi"); map.put("age", 25); + map.put("title", null); } @Test void should_allow_assertions_on_values_extracted_from_given_map_keys() { + // WHEN/THEN assertThat(map).extracting(NAME, "age") - .contains("kawhi", 25); + .containsExactly("kawhi", 25); } @Test void should_allow_object_assertions_on_value_extracted_from_given_map_key() { + // WHEN/THEN assertThat(map).extracting(NAME) .isEqualTo("kawhi"); } @Test void should_allow_assertions_on_values_extracted_from_given_extractors() { + // WHEN/THEN assertThat(map).extracting(m -> m.get(NAME), m -> m.get("age")) - .contains("kawhi", 25); + .containsExactly("kawhi", 25); } @Test void should_allow_object_assertions_on_value_extracted_from_given_extractor() { + // WHEN/THEN assertThat(map).extracting(m -> m.get(NAME)) .isEqualTo("kawhi"); } @Test void should_extract_null_element_from_unknown_key() { + // WHEN/THEN assertThat(map).extracting(NAME, "unknown") - .contains("kawhi", (Object) null); + .containsExactly("kawhi", null); } @Test - void should_extract_null_object_from_unknown_key() { - assertThat(map).extracting("unknown") + void should_extract_null_object_from_key_with_null_value() { + // WHEN/THEN + assertThat(map).extracting("title") .isNull(); } + @Test + void should_fail_with_unknown_key() { + // WHEN + Throwable thrown = catchThrowable(() -> assertThat(map).extracting("unknown")); + // THEN + then(thrown).isInstanceOf(IntrospectionError.class); + } + @Test void should_use_key_names_as_description() { - assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(map).extracting(NAME, "age").isEmpty()) - .withMessageContaining("[Extracted: name, age]"); + // WHEN + AssertionError error = expectAssertionError(() -> assertThat(map).extracting(NAME, "age").isEmpty()); + // THEN + then(error).hasMessageContaining("[Extracted: name, age]"); } @Test void should_use_key_name_as_description() { - assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(map).extracting(NAME).isNull()) - .withMessageContaining("[Extracted: name]"); + // WHEN + AssertionError error = expectAssertionError(() -> assertThat(map).extracting(NAME).isNull()); + // THEN + then(error).hasMessageContaining("[Extracted: name]"); } @Test void should_keep_existing_description_if_set_when_extracting_values_list() { - assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(map).as("check name and age") - .extracting(NAME, "age").isEmpty()) - .withMessageContaining("[check name and age]"); + // WHEN + AssertionError error = expectAssertionError(() -> assertThat(map).as("check name and age") + .extracting(NAME, "age").isEmpty()); + // THEN + then(error).hasMessageContaining("[check name and age]"); } @Test void should_keep_existing_description_if_set_when_extracting_value_object() { - assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(map).as("check name") - .extracting(NAME).isNull()) - .withMessageContaining("[check name]"); + // WHEN + AssertionError error = expectAssertionError(() -> assertThat(map).as("check name") + .extracting(NAME).isNull()); + // THEN + then(error).hasMessageContaining("[check name]"); } @Test @@ -103,9 +128,9 @@ void should_fail_with_key_list_if_actual_is_null() { // GIVEN map = null; // WHEN - Throwable error = catchThrowable(() -> assertThat(map).extracting(NAME, "age")); + AssertionError error = expectAssertionError(() -> assertThat(map).extracting(NAME, "age")); // THEN - assertThat(error).hasMessage(actualIsNull()); + then(error).hasMessage(actualIsNull()); } @Test @@ -113,9 +138,9 @@ void should_fail_with_single_key_if_actual_is_null() { // GIVEN map = null; // WHEN - Throwable error = catchThrowable(() -> assertThat(map).extracting(NAME)); + AssertionError error = expectAssertionError(() -> assertThat(map).extracting(NAME)); // THEN - assertThat(error).hasMessage(actualIsNull()); + then(error).hasMessage(actualIsNull()); } } diff --git a/src/test/java/org/assertj/core/api/map/MapAssert_flatExtracting_Test.java b/src/test/java/org/assertj/core/api/map/MapAssert_flatExtracting_Test.java index 564fe130592..a450036f865 100644 --- a/src/test/java/org/assertj/core/api/map/MapAssert_flatExtracting_Test.java +++ b/src/test/java/org/assertj/core/api/map/MapAssert_flatExtracting_Test.java @@ -14,7 +14,10 @@ import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.assertj.core.api.BDDAssertions.then; import static org.assertj.core.util.Arrays.array; +import static org.assertj.core.util.Lists.list; import static org.assertj.core.util.Sets.newLinkedHashSet; import java.util.LinkedHashMap; @@ -22,6 +25,7 @@ import java.util.Map; import org.assertj.core.api.MapAssert; +import org.assertj.core.util.introspection.IntrospectionError; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -45,6 +49,7 @@ void beforeEachTest() { map.put("job", jobs); map.put("city", cities); map.put("rank", ranks); + map.put("id", list(null, null)); } @Test @@ -57,16 +62,25 @@ void should_allow_assertions_on_flattened_values_extracted_from_given_map_keys() } @Test - void should_extract_null_from_unknown_key() { - assertThat(map).flatExtracting("name", "id", "city") - .containsExactly("Dave", "Jeff", null, "Dover", "Boston", "Paris"); - assertThat(map).flatExtracting("foo", "bar") - .containsOnlyNulls(); + void should_extract_null_from_key_with_flattened_null_values() { + // WHEN/THEN + assertThat(map).flatExtracting("name", "city", "id") + .containsExactly("Dave", "Jeff", "Dover", "Boston", "Paris", null, null); + } + + @Test + void should_fail_if_key_is_unknown() { + // WHEN + Throwable thrown = catchThrowable(() -> assertThat(map).flatExtracting("foo", "bar")); + // THEN + then(thrown).isInstanceOf(IntrospectionError.class); } @Test void should_extract_but_not_flatten_non_collection_values() { + // GIVEN map.put("year", 2017); + // WHEN/THEN assertThat(map).flatExtracting("name", "job", "year") .containsExactly("Dave", "Jeff", "Plumber", "Builder", 2017); } diff --git a/src/test/java/org/assertj/core/api/map/MapAssert_size_Test.java b/src/test/java/org/assertj/core/api/map/MapAssert_size_Test.java index c8e3e2317a4..e5aad578993 100644 --- a/src/test/java/org/assertj/core/api/map/MapAssert_size_Test.java +++ b/src/test/java/org/assertj/core/api/map/MapAssert_size_Test.java @@ -24,7 +24,6 @@ class MapAssert_size_Test { @Test - @SuppressWarnings("unchecked") void should_be_able_to_use_integer_assertions_on_size_the_map_size() { Map stringToString = mapOf(entry("a", "1"), entry("b", "2")); // @format:off diff --git a/src/test/java/org/assertj/core/api/object/ObjectAssert_extracting_with_Function_and_InstanceOfAssertFactory_Test.java b/src/test/java/org/assertj/core/api/object/ObjectAssert_extracting_with_Function_and_InstanceOfAssertFactory_Test.java index f57fc987a0d..5406a3435a0 100644 --- a/src/test/java/org/assertj/core/api/object/ObjectAssert_extracting_with_Function_and_InstanceOfAssertFactory_Test.java +++ b/src/test/java/org/assertj/core/api/object/ObjectAssert_extracting_with_Function_and_InstanceOfAssertFactory_Test.java @@ -112,7 +112,7 @@ void should_fail_if_the_extracted_value_is_not_an_instance_of_the_assert_factory // WHEN AssertionError error = expectAssertionError(() -> assertThat(luke).extracting(Employee::getAge, STRING)); // THEN - then(error).hasMessageContainingAll("Expecting:", "to be an instance of:", "but was instance of:"); + then(error).hasMessageContainingAll("Expecting actual:", "to be an instance of:", "but was instance of:"); } @Test diff --git a/src/test/java/org/assertj/core/api/object/ObjectAssert_extracting_with_String_Array_Test.java b/src/test/java/org/assertj/core/api/object/ObjectAssert_extracting_with_String_Array_Test.java new file mode 100644 index 00000000000..a13626746f8 --- /dev/null +++ b/src/test/java/org/assertj/core/api/object/ObjectAssert_extracting_with_String_Array_Test.java @@ -0,0 +1,133 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api.object; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.util.AssertionsUtil.expectAssertionError; +import static org.assertj.core.util.BigDecimalComparator.BIG_DECIMAL_COMPARATOR; + +import java.math.BigDecimal; + +import org.assertj.core.api.ObjectAssert; +import org.assertj.core.test.Employee; +import org.assertj.core.test.Name; +import org.assertj.core.util.introspection.IntrospectionError; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * Tests for {@link ObjectAssert#extracting(String[])}. + */ +@DisplayName("ObjectAssert extracting(String[])") +class ObjectAssert_extracting_with_String_Array_Test { + + private Employee luke; + private Employee leia; + + @BeforeEach + void setup() { + luke = new Employee(2L, new Name("Luke", "Skywalker"), 26); + luke.setAttribute("side", "light"); + leia = new Employee(2L, new Name("Leia", "Skywalker"), 26); + luke.setRelation("brother", null); + luke.setRelation("sister", leia); + leia.setRelation("brother", luke); + } + + @Test + void should_allow_assertions_on_array_of_properties_extracted_from_given_object_by_name() { + // WHEN/THEN + assertThat(luke).extracting("id", "name") + .hasSize(2) + .doesNotContainNull(); + } + + @Test + void should_allow_assertions_on_array_of_nested_properties_extracted_from_given_object_by_name() { + // WHEN/THEN + assertThat(luke).extracting("name.first", "name.last") + .hasSize(2) + .containsExactly("Luke", "Skywalker"); + } + + @Test + void should_allow_assertion_on_mixed_properties_or_fields_with_nested_map_values() { + // WHEN/THEN + assertThat(luke).extracting("id", "name.last", "attributes.side", "relations.sister", "relations.sister.relations.brother.id") + .containsExactly(2L, "Skywalker", "light", leia, 2L); + } + + @Test + void should_follow_map_get_behavior_for_key_with_null_value() { + // WHEN/THEN + assertThat(luke).extracting("relations.brother", "relations.sister", "relations.sister.name.first") + .containsExactly(null, leia, "Leia"); + } + + @Test + void should_throw_IntrospectionError_if_nested_map_key_does_not_exist() { + // WHEN + Throwable thrown = catchThrowable(() -> assertThat(luke).extracting("relations.unknown", "relations.sister")); + // THEN + then(thrown).isInstanceOf(IntrospectionError.class); + } + + @Test + void should_use_property_field_names_as_description_when_extracting_tuples_list() { + // WHEN + AssertionError error = expectAssertionError(() -> assertThat(luke).extracting("name.first", "name.last") + .isEmpty()); + // THEN + then(error).hasMessageContaining("[Extracted: name.first, name.last]"); + } + + @Test + void should_keep_existing_description_if_set_when_extracting_tuples_list() { + // WHEN + AssertionError error = expectAssertionError(() -> assertThat(luke).as("check luke first and last name") + .extracting("name.first", "name.last") + .isEmpty()); + // THEN + then(error).hasMessageContaining("[check luke first and last name]"); + } + + @Test + void should_allow_to_specify_type_comparator_after_using_extracting_with_multiple_parameters_on_object() { + // GIVEN + Person obiwan = new Person("Obi-Wan"); + obiwan.setHeight(new BigDecimal("1.820")); + // WHEN/THEN + assertThat(obiwan).extracting("name", "height") + .usingComparatorForType(BIG_DECIMAL_COMPARATOR, BigDecimal.class) + .containsExactly("Obi-Wan", new BigDecimal("1.82")); + } + + @SuppressWarnings("unused") + private static class Person { + + private final String name; + private BigDecimal height; + + public Person(String name) { + this.name = name; + } + + public void setHeight(BigDecimal height) { + this.height = height; + } + } + +} diff --git a/src/test/java/org/assertj/core/api/object/ObjectAssert_extracting_Test.java b/src/test/java/org/assertj/core/api/object/ObjectAssert_extracting_with_String_Test.java similarity index 60% rename from src/test/java/org/assertj/core/api/object/ObjectAssert_extracting_Test.java rename to src/test/java/org/assertj/core/api/object/ObjectAssert_extracting_with_String_Test.java index 65010c37b1e..71cab1a6015 100644 --- a/src/test/java/org/assertj/core/api/object/ObjectAssert_extracting_Test.java +++ b/src/test/java/org/assertj/core/api/object/ObjectAssert_extracting_with_String_Test.java @@ -30,10 +30,10 @@ import org.junit.jupiter.api.Test; /** - * Tests for {@link ObjectAssert#extracting(String)} and {@link ObjectAssert#extracting(String[])}. + * Tests for {@link ObjectAssert#extracting(String)}. */ -@DisplayName("ObjectAssert.extracting") -class ObjectAssert_extracting_Test { +@DisplayName("ObjectAssert extracting(String)") +class ObjectAssert_extracting_with_String_Test { private Employee luke; private Employee leia; @@ -43,42 +43,23 @@ void setup() { luke = new Employee(2L, new Name("Luke", "Skywalker"), 26); luke.setAttribute("side", "light"); leia = new Employee(2L, new Name("Leia", "Skywalker"), 26); + luke.setRelation("brother", null); luke.setRelation("sister", leia); leia.setRelation("brother", luke); } @Test void should_allow_assertions_on_property_extracted_from_given_object_by_name() { + // WHEN/THEN assertThat(luke).extracting("id") .isNotNull(); - assertThat(luke).extracting("name.first") - .isEqualTo("Luke"); - } - - @Test - void should_allow_assertions_on_array_of_properties_extracted_from_given_object_by_name() { - assertThat(luke).extracting("id", "name") - .hasSize(2) - .doesNotContainNull(); - assertThat(luke).extracting("name.first", "name.last") - .hasSize(2) - .containsExactly("Luke", "Skywalker"); - } - - @Test - void should_allow_assertion_on_mixed_properties_or_fields_with_nested_map_values() { - assertThat(luke).extracting("id", "name.last", "attributes.side", "relations.sister", "relations.sister.relations.brother.id") - .containsExactly(2L, "Skywalker", "light", leia, 2L); } @Test - void should_follow_map_get_behavior_for_unknown_key() { - assertThat(luke).extracting("attributes.unknown_key", - "relations.sister", - "relations.sista", - "relations.sister.name.first", - "relations.sista.name.first") - .containsExactly(null, leia, null, "Leia", null); + void should_allow_assertions_on_nested_property_extracted_from_given_object_by_name() { + // WHEN/THEN + assertThat(luke).extracting("name.first") + .isEqualTo("Luke"); } @Test @@ -89,15 +70,6 @@ void should_use_property_field_name_as_description_when_extracting_single_proper then(assertionError).hasMessageContaining("[Extracted: name.first]"); } - @Test - void should_use_property_field_names_as_description_when_extracting_tuples_list() { - // WHEN - AssertionError assertionError = expectAssertionError(() -> assertThat(luke).extracting("name.first", "name.last") - .isEmpty()); - // THEN - then(assertionError).hasMessageContaining("[Extracted: name.first, name.last]"); - } - @Test void should_keep_existing_description_if_set_when_extracting_single_property() { // WHEN @@ -108,16 +80,6 @@ void should_keep_existing_description_if_set_when_extracting_single_property() { then(assertionError).hasMessageContaining("[check luke first name]"); } - @Test - void should_keep_existing_description_if_set_when_extracting_tuples_list() { - // WHEN - AssertionError assertionError = expectAssertionError(() -> assertThat(luke).as("check luke first and last name") - .extracting("name.first", "name.last") - .isEmpty()); - // THEN - then(assertionError).hasMessageContaining("[check luke first and last name]"); - } - @Test void should_allow_to_specify_type_comparator_after_using_extracting_with_single_parameter_on_object() { // GIVEN @@ -127,23 +89,12 @@ void should_allow_to_specify_type_comparator_after_using_extracting_with_single_ if (o1 instanceof BigDecimal) return BIG_DECIMAL_COMPARATOR.compare((BigDecimal) o1, (BigDecimal) o2); throw new IllegalStateException("only supported for BigDecimal"); }; - // THEN + // WHEN/THEN assertThat(obiwan).extracting("height") .usingComparator(heightComparator) .isEqualTo(new BigDecimal("1.82")); } - @Test - void should_allow_to_specify_type_comparator_after_using_extracting_with_multiple_parameters_on_object() { - // GIVEN - Person obiwan = new Person("Obi-Wan"); - obiwan.setHeight(new BigDecimal("1.820")); - // THEN - assertThat(obiwan).extracting("name", "height") - .usingComparatorForType(BIG_DECIMAL_COMPARATOR, BigDecimal.class) - .containsExactly("Obi-Wan", new BigDecimal("1.82")); - } - @Test void should_throw_IntrospectionError_if_given_field_name_cannot_be_read() { // WHEN @@ -167,4 +118,5 @@ public void setHeight(BigDecimal height) { this.height = height; } } + } diff --git a/src/test/java/org/assertj/core/api/object/ObjectAssert_extracting_with_String_and_InstanceOfAssertFactory_Test.java b/src/test/java/org/assertj/core/api/object/ObjectAssert_extracting_with_String_and_InstanceOfAssertFactory_Test.java index 83fc0c4922a..858abc9d98f 100644 --- a/src/test/java/org/assertj/core/api/object/ObjectAssert_extracting_with_String_and_InstanceOfAssertFactory_Test.java +++ b/src/test/java/org/assertj/core/api/object/ObjectAssert_extracting_with_String_and_InstanceOfAssertFactory_Test.java @@ -94,7 +94,7 @@ void should_fail_if_the_extracted_value_is_not_an_instance_of_the_assert_factory // WHEN AssertionError error = expectAssertionError(() -> assertThat(luke).extracting("name.first", LONG)); // THEN - then(error).hasMessageContainingAll("Expecting:", "to be an instance of:", "but was instance of:"); + then(error).hasMessageContainingAll("Expecting actual:", "to be an instance of:", "but was instance of:"); } @Test diff --git a/src/test/java/org/assertj/core/api/object/ObjectAssert_flatExtracting_Test.java b/src/test/java/org/assertj/core/api/object/ObjectAssert_flatExtracting_Test.java deleted file mode 100644 index 1e746c8324f..00000000000 --- a/src/test/java/org/assertj/core/api/object/ObjectAssert_flatExtracting_Test.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - * Copyright 2012-2021 the original author or authors. - */ -package org.assertj.core.api.object; - -import static java.util.Arrays.asList; -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -class ObjectAssert_flatExtracting_Test { - - private Map> mapOfList; - - @BeforeEach - void beforeEachTest() { - mapOfList = new LinkedHashMap<>(); - mapOfList.put("name", asList("Dave", "Jeff")); - mapOfList.put("job", asList("Plumber", "Builder")); - mapOfList.put("city", asList("Dover", "Boston", "Paris")); - } - - @Test - void should_allow_assertions_on_flattened_values_extracted_from_given_map_keys() { - assertThat(mapOfList).flatExtracting("name", "job", "city") - .containsExactly("Dave", "Jeff", "Plumber", "Builder", "Dover", "Boston", "Paris"); - // order of values is the order of key then key values - assertThat(mapOfList).flatExtracting("city", "job", "name") - .containsExactly("Dover", "Boston", "Paris", "Plumber", "Builder", "Dave", "Jeff"); - } - - @Test - void should_extract_null_from_unknown_key() { - assertThat(mapOfList).flatExtracting("name", "id", "city") - .containsExactly("Dave", "Jeff", null, "Dover", "Boston", "Paris"); - assertThat(mapOfList).flatExtracting("foo", "bar") - .containsOnlyNulls(); - } - -} diff --git a/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_filteredOnAssertions_Test.java b/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_filteredOnAssertions_Test.java index 910dd90fcd7..71accbd6aea 100644 --- a/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_filteredOnAssertions_Test.java +++ b/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_filteredOnAssertions_Test.java @@ -13,7 +13,6 @@ package org.assertj.core.api.objectarray; import static java.util.Arrays.asList; - import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.presentation.UnicodeRepresentation.UNICODE_REPRESENTATION; @@ -64,6 +63,10 @@ void should_honor_AssertFactory_strongly_typed_navigation_assertions() { assertThat(hobbits, tolkienCharacterAssertFactory).filteredOnAssertions(nameStartingWithFro) .element(0) .hasAge(33); + assertThat(hobbits, tolkienCharacterAssertFactory).filteredOnAssertions(nameStartingWithFro) + .elements(0) + .first() + .hasAge(33); } @Test @@ -80,6 +83,10 @@ void should_honor_ClassBased_strongly_typed_navigation_assertions() { assertThat(hobbits, TolkienCharacterAssert.class).filteredOnAssertions(nameStartingWithFro) .element(0) .hasAge(33); + assertThat(hobbits, TolkienCharacterAssert.class).filteredOnAssertions(nameStartingWithFro) + .elements(0) + .first() + .hasAge(33); } @Test diff --git a/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_hasExactlyElementsOfTypes_Test.java b/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_hasExactlyElementsOfTypes_Test.java new file mode 100644 index 00000000000..aaa0a5c8c99 --- /dev/null +++ b/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_hasExactlyElementsOfTypes_Test.java @@ -0,0 +1,36 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api.objectarray; + +import static org.mockito.Mockito.verify; + +import org.assertj.core.api.ObjectArrayAssert; +import org.assertj.core.api.ObjectArrayAssertBaseTest; + +/** + * Tests for {@link ObjectArrayAssert#hasExactlyElementsOfTypes(Class...)} . + */ +class ObjectArrayAssert_hasExactlyElementsOfTypes_Test extends ObjectArrayAssertBaseTest { + + private final Class[] types = { Integer.class }; + + @Override + protected ObjectArrayAssert invoke_api_method() { + return assertions.hasExactlyElementsOfTypes(types); + } + + @Override + protected void verify_internal_effects() { + verify(arrays).assertHasExactlyElementsOfTypes(getInfo(assertions), getActual(assertions), types); + } +} diff --git a/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_hasOnlyOneElementSatisfying_Test.java b/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_hasOnlyOneElementSatisfying_Test.java index d271e6abd57..d1251746903 100644 --- a/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_hasOnlyOneElementSatisfying_Test.java +++ b/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_hasOnlyOneElementSatisfying_Test.java @@ -42,7 +42,7 @@ void fails_if_arry_has_only_one_element_and_that_element_does_not_satisfy_the_gi assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->{ Jedi[] jedis = { new Jedi("Yoda", "red") }; assertThat(jedis).hasOnlyOneElementSatisfying(yoda -> assertThat(yoda.getName()).startsWith("L")); - }).withMessage(format("%nExpecting:%n \"Yoda\"%nto start with:%n \"L\"%n")); + }).withMessage(format("%nExpecting actual:%n \"Yoda\"%nto start with:%n \"L\"%n")); } @Test @@ -51,7 +51,7 @@ void fails_if_iterable_has_only_one_element_and_that_element_does_not_satisfy_on assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(jedis).hasOnlyOneElementSatisfying(yoda -> { assertThat(yoda.getName()).startsWith("Y"); assertThat(yoda.getName()).startsWith("L"); - })).withMessage(String.format("%nExpecting:%n \"Yoda\"%nto start with:%n \"L\"%n")); + })).withMessage(String.format("%nExpecting actual:%n \"Yoda\"%nto start with:%n \"L\"%n")); } @Test @@ -67,8 +67,8 @@ void fails_if_iterable_has_only_one_element_and_that_element_does_not_satisfy_th }); }); - assertThat(assertionError).hasMessageContaining(format("Expecting:%n \"Yoda\"%nto start with:%n \"L\"")) - .hasMessageContaining(format("Expecting:%n \"Yoda\"%nto start with:%n \"M\"")); + assertThat(assertionError).hasMessageContaining(format("Expecting actual:%n \"Yoda\"%nto start with:%n \"L\"")) + .hasMessageContaining(format("Expecting actual:%n \"Yoda\"%nto start with:%n \"M\"")); } @Test diff --git a/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_satisfiesExactlyInAnyOrder_Test.java b/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_satisfiesExactlyInAnyOrder_Test.java index 610bf4e44ee..6c8cb27989a 100644 --- a/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_satisfiesExactlyInAnyOrder_Test.java +++ b/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_satisfiesExactlyInAnyOrder_Test.java @@ -13,6 +13,7 @@ package org.assertj.core.api.objectarray; import static org.assertj.core.test.ObjectArrays.arrayOf; +import static org.assertj.core.util.Arrays.array; import static org.assertj.core.util.Lists.list; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -43,6 +44,6 @@ protected ObjectArrayAssert invoke_api_method() { @Override protected void verify_internal_effects() { - verify(iterables).assertSatisfiesExactlyInAnyOrder(getInfo(assertions), list(getActual(assertions)), consumer); + verify(iterables).assertSatisfiesExactlyInAnyOrder(getInfo(assertions), list(getActual(assertions)), array(consumer)); } } diff --git a/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_usingComparatorForType_Test.java b/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_usingComparatorForType_Test.java index b1529718ce7..794296e2012 100644 --- a/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_usingComparatorForType_Test.java +++ b/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_usingComparatorForType_Test.java @@ -34,6 +34,7 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +@SuppressWarnings("deprecation") @DisplayName("ObjectArrayAssert usingComparatorForType") class ObjectArrayAssert_usingComparatorForType_Test extends ObjectArrayAssertBaseTest { @@ -103,16 +104,6 @@ void should_use_comparator_for_type_when_using_field_by_field_element_comparator .contains(other, "any"); } - @Test - void should_use_comparator_for_type_when_using_recursive_field_by_field_element_comparator() { - // GIVEN - Object[] array = array(actual, "some"); - // THEN - assertThat(array).usingComparatorForType(ALWAY_EQUALS_STRING, String.class) - .usingRecursiveFieldByFieldElementComparator() - .contains(other, "any"); - } - @Test void should_only_use_comparator_on_fields_element_but_not_the_element_itself() { // GIVEN @@ -131,8 +122,8 @@ void should_only_use_comparator_on_fields_element_but_not_the_element_itself() { + " [\"any\"]%n" + "when comparing values using field/property by field/property comparator on all fields/properties%n" + "Comparators used:%n" - + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], String -> AlwaysEqualComparator}%n" - + "- for elements (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}")); + + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], String -> AlwaysEqualComparator, Path -> lexicographic comparator (Path natural order)}%n" + + "- for elements (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], Path -> lexicographic comparator (Path natural order)}")); } @Test @@ -183,7 +174,7 @@ void should_fail_because_of_comparator_set_last() { + " [Luke the Jedi]%n" + "when comparing values using field/property by field/property comparator on all fields/properties%n" + "Comparators used:%n" - + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], String -> org.assertj.core.test.NeverEqualComparator}%n" - + "- for elements (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], String -> AlwaysEqualComparator}")); + + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], String -> org.assertj.core.test.NeverEqualComparator, Path -> lexicographic comparator (Path natural order)}%n" + + "- for elements (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], String -> AlwaysEqualComparator, Path -> lexicographic comparator (Path natural order)}")); } } diff --git a/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_usingElementComparatorIgnoringFields_Test.java b/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_usingElementComparatorIgnoringFields_Test.java index 1c2064a7164..3da74f57b41 100644 --- a/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_usingElementComparatorIgnoringFields_Test.java +++ b/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_usingElementComparatorIgnoringFields_Test.java @@ -28,6 +28,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +@SuppressWarnings("deprecation") class ObjectArrayAssert_usingElementComparatorIgnoringFields_Test extends ObjectArrayAssertBaseTest { private ObjectArrays arraysBefore; @@ -50,7 +51,7 @@ protected void verify_internal_effects() { ComparatorBasedComparisonStrategy strategy = (ComparatorBasedComparisonStrategy) iterables.getComparisonStrategy(); assertThat(strategy.getComparator()).isInstanceOf(ExtendedByTypesComparator.class); assertThat(((IgnoringFieldsComparator) ((ExtendedByTypesComparator) strategy.getComparator()) - .getComparator()).getFields()).containsOnly("field"); + .getComparator()).getFields()).containsOnly("field"); } @Test diff --git a/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_usingElementComparatorOnFields_Test.java b/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_usingElementComparatorOnFields_Test.java index 208b102cc93..692cc70a69c 100644 --- a/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_usingElementComparatorOnFields_Test.java +++ b/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_usingElementComparatorOnFields_Test.java @@ -28,6 +28,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +@SuppressWarnings("deprecation") class ObjectArrayAssert_usingElementComparatorOnFields_Test extends ObjectArrayAssertBaseTest { private ObjectArrays arraysBefore; @@ -50,7 +51,7 @@ protected void verify_internal_effects() { ComparatorBasedComparisonStrategy strategy = (ComparatorBasedComparisonStrategy) arrays.getComparisonStrategy(); assertThat(strategy.getComparator()).isInstanceOf(ExtendedByTypesComparator.class); assertThat(((OnFieldsComparator) ((ExtendedByTypesComparator) strategy.getComparator()) - .getComparator()).getFields()).containsOnly("field"); + .getComparator()).getFields()).containsOnly("field"); } @Test diff --git a/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_usingFieldByFieldElementComparator_Test.java b/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_usingFieldByFieldElementComparator_Test.java index 1ccfbb7ad8a..30186736576 100644 --- a/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_usingFieldByFieldElementComparator_Test.java +++ b/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_usingFieldByFieldElementComparator_Test.java @@ -32,6 +32,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +@SuppressWarnings("deprecation") class ObjectArrayAssert_usingFieldByFieldElementComparator_Test extends ObjectArrayAssertBaseTest { private ObjectArrays arraysBefore; @@ -166,8 +167,8 @@ void failed_isEqualTo_assertion_using_field_by_field_element_comparator() { + "%n" + "when comparing elements using field/property by field/property comparator on all fields/properties%n" + "Comparators used:%n" - + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}%n" - + "- for elements (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}")); + + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], Path -> lexicographic comparator (Path natural order)}%n" + + "- for elements (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], Path -> lexicographic comparator (Path natural order)}")); } @Test @@ -177,14 +178,14 @@ void failed_isIn_assertion_using_field_by_field_element_comparator() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(array1).usingFieldByFieldElementComparator() .isIn(array2, array2)) - .withMessage(format("%nExpecting:%n" + .withMessage(format("%nExpecting actual:%n" + " [Foo(id=id, bar=1)]%n" + "to be in:%n" + " [[Foo(id=id, bar=2)], [Foo(id=id, bar=2)]]%n" + "when comparing elements using field/property by field/property comparator on all fields/properties%n" + "Comparators used:%n" - + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}%n" - + "- for elements (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}")); + + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], Path -> lexicographic comparator (Path natural order)}%n" + + "- for elements (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], Path -> lexicographic comparator (Path natural order)}")); } @Test diff --git a/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_usingRecursiveFieldByFieldElementComparatorIgnoringFields_Test.java b/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_usingRecursiveFieldByFieldElementComparatorIgnoringFields_Test.java new file mode 100644 index 00000000000..e09f795bd58 --- /dev/null +++ b/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_usingRecursiveFieldByFieldElementComparatorIgnoringFields_Test.java @@ -0,0 +1,69 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api.objectarray; + +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.util.Lists.list; + +import org.assertj.core.api.ObjectArrayAssert; +import org.assertj.core.api.ObjectArrayAssertBaseTest; +import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration; +import org.assertj.core.internal.ComparatorBasedComparisonStrategy; +import org.assertj.core.internal.ConfigurableRecursiveFieldByFieldComparator; +import org.assertj.core.internal.ObjectArrayElementComparisonStrategy; +import org.assertj.core.internal.ObjectArrays; +import org.assertj.core.test.Name; +import org.assertj.core.test.Player; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class ObjectArrayAssert_usingRecursiveFieldByFieldElementComparatorIgnoringFields_Test extends ObjectArrayAssertBaseTest { + + private ObjectArrays arraysBefore; + + @BeforeEach + void before() { + arraysBefore = getArrays(assertions); + } + + @Override + protected ObjectArrayAssert invoke_api_method() { + return assertions.usingRecursiveFieldByFieldElementComparatorIgnoringFields("field"); + } + + @Override + protected void verify_internal_effects() { + then(arraysBefore).isNotSameAs(getArrays(assertions)); + then(getArrays(assertions).getComparisonStrategy()).isInstanceOf(ComparatorBasedComparisonStrategy.class); + then(getObjects(assertions).getComparisonStrategy()).isInstanceOf(ObjectArrayElementComparisonStrategy.class); + RecursiveComparisonConfiguration recursiveComparisonConfiguration = RecursiveComparisonConfiguration.builder() + .withIgnoredFields("field") + .build(); + ConfigurableRecursiveFieldByFieldComparator expectedComparator = new ConfigurableRecursiveFieldByFieldComparator(recursiveComparisonConfiguration); + then(getArrays(assertions).getComparator()).isEqualTo(expectedComparator); + then(getObjects(assertions).getComparisonStrategy()).extracting("elementComparator").isEqualTo(expectedComparator); + } + + @Test + void should_ignore_given_fields_recursively() { + // GIVEN + Player rose = new Player(new Name("Derrick", "Rose"), "Chicago Bulls"); + rose.nickname = new Name("Crazy", "Dunks"); + Player jalen = new Player(new Name("Jalen", "Rose"), "Chicago Bulls"); + jalen.nickname = new Name("Crazy", "Defense"); + // WHEN/THEN + then(list(rose)).usingRecursiveFieldByFieldElementComparatorIgnoringFields("name.first", "nickname.last") + .contains(jalen); + } + +} diff --git a/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_usingRecursiveFieldByFieldElementComparatorOnFields_Test.java b/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_usingRecursiveFieldByFieldElementComparatorOnFields_Test.java new file mode 100644 index 00000000000..1bd08ab8133 --- /dev/null +++ b/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_usingRecursiveFieldByFieldElementComparatorOnFields_Test.java @@ -0,0 +1,69 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api.objectarray; + +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.util.Arrays.array; + +import org.assertj.core.api.ObjectArrayAssert; +import org.assertj.core.api.ObjectArrayAssertBaseTest; +import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration; +import org.assertj.core.internal.ComparatorBasedComparisonStrategy; +import org.assertj.core.internal.ConfigurableRecursiveFieldByFieldComparator; +import org.assertj.core.internal.ObjectArrayElementComparisonStrategy; +import org.assertj.core.internal.ObjectArrays; +import org.assertj.core.test.Name; +import org.assertj.core.test.Player; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class ObjectArrayAssert_usingRecursiveFieldByFieldElementComparatorOnFields_Test extends ObjectArrayAssertBaseTest { + + private ObjectArrays arraysBefore; + + @BeforeEach + void before() { + arraysBefore = getArrays(assertions); + } + + @Override + protected ObjectArrayAssert invoke_api_method() { + return assertions.usingRecursiveFieldByFieldElementComparatorOnFields("field"); + } + + @Override + protected void verify_internal_effects() { + then(arraysBefore).isNotSameAs(getArrays(assertions)); + then(getArrays(assertions).getComparisonStrategy()).isInstanceOf(ComparatorBasedComparisonStrategy.class); + then(getObjects(assertions).getComparisonStrategy()).isInstanceOf(ObjectArrayElementComparisonStrategy.class); + RecursiveComparisonConfiguration recursiveComparisonConfiguration = RecursiveComparisonConfiguration.builder() + .withComparedFields("field") + .build(); + ConfigurableRecursiveFieldByFieldComparator expectedComparator = new ConfigurableRecursiveFieldByFieldComparator(recursiveComparisonConfiguration); + then(getArrays(assertions).getComparator()).isEqualTo(expectedComparator); + then(getObjects(assertions).getComparisonStrategy()).extracting("elementComparator").isEqualTo(expectedComparator); + } + + @Test + void should_compare_given_fields_recursively_and_none_other() { + // GIVEN + Player rose = new Player(new Name("Derrick", "Rose"), "Chicago Bulls"); + rose.nickname = new Name("Crazy", "Dunks"); + Player jalen = new Player(new Name("Jalen", "Rose"), "Chicago Bulls"); + jalen.nickname = new Name("Crazy", "Defense"); + // WHEN/THEN + then(array(rose)).usingRecursiveFieldByFieldElementComparatorOnFields("name.last", "team", "nickname.first") + .contains(jalen); + } + +} diff --git a/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_usingRecursiveFieldByFieldElementComparator_Test.java b/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_usingRecursiveFieldByFieldElementComparator_Test.java index 88410b45da8..60e82ed93f5 100644 --- a/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_usingRecursiveFieldByFieldElementComparator_Test.java +++ b/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_usingRecursiveFieldByFieldElementComparator_Test.java @@ -13,17 +13,18 @@ package org.assertj.core.api.objectarray; import static java.lang.String.format; +import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.assertj.core.test.AlwaysEqualComparator.ALWAY_EQUALS_STRING; +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.configuration.ConfigurationProvider.CONFIGURATION_PROVIDER; import static org.assertj.core.test.ErrorMessagesForTest.shouldBeEqualMessage; -import static org.assertj.core.util.Arrays.array; - -import java.util.Comparator; +import static org.assertj.core.util.AssertionsUtil.expectAssertionError; import org.assertj.core.api.ObjectArrayAssert; import org.assertj.core.api.ObjectArrayAssertBaseTest; +import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration; import org.assertj.core.internal.ComparatorBasedComparisonStrategy; +import org.assertj.core.internal.ConfigurableRecursiveFieldByFieldComparator; import org.assertj.core.internal.ObjectArrayElementComparisonStrategy; import org.assertj.core.internal.ObjectArrays; import org.junit.jupiter.api.BeforeEach; @@ -31,6 +32,8 @@ class ObjectArrayAssert_usingRecursiveFieldByFieldElementComparator_Test extends ObjectArrayAssertBaseTest { + private static final String DEFAULT_RECURSIVE_COMPARATOR_DESCRIPTION = CONFIGURATION_PROVIDER.representation() + .toStringOf(new ConfigurableRecursiveFieldByFieldComparator(new RecursiveComparisonConfiguration())); private ObjectArrays arraysBefore; @BeforeEach @@ -48,6 +51,10 @@ protected void verify_internal_effects() { assertThat(arraysBefore).isNotSameAs(getArrays(assertions)); assertThat(getArrays(assertions).getComparisonStrategy()).isInstanceOf(ComparatorBasedComparisonStrategy.class); assertThat(getObjects(assertions).getComparisonStrategy()).isInstanceOf(ObjectArrayElementComparisonStrategy.class); + RecursiveComparisonConfiguration recursiveComparisonConfiguration = new RecursiveComparisonConfiguration(); + ConfigurableRecursiveFieldByFieldComparator expectedComparator = new ConfigurableRecursiveFieldByFieldComparator(recursiveComparisonConfiguration); + then(getArrays(assertions).getComparator()).isEqualTo(expectedComparator); + then(getObjects(assertions).getComparisonStrategy()).extracting("elementComparator").isEqualTo(expectedComparator); } @Test @@ -69,15 +76,12 @@ void failed_isEqualTo_assertion_using_recursive_field_by_field_element_comparato Foo[] array1 = { new Foo("id", new Bar(1)) }; Foo[] array2 = { new Foo("id", new Bar(2)) }; - assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(array1).usingRecursiveFieldByFieldElementComparator() - .isEqualTo(array2)) - .withMessage(format(shouldBeEqualMessage("[Foo(id=id, bar=Bar(id=1))]", - "[Foo(id=id, bar=Bar(id=2))]") - + "%n" - + "when comparing elements using recursive field/property by field/property comparator on all fields/properties%n" - + "Comparators used:%n" - + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}%n" - + "- for elements (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}")); + AssertionError assertionError = expectAssertionError(() -> assertThat(array1).usingRecursiveFieldByFieldElementComparator() + .isEqualTo(array2)); + + then(assertionError).hasMessage(format(shouldBeEqualMessage("[Foo(id=id, bar=Bar(id=1))]", "[Foo(id=id, bar=Bar(id=2))]") + + "%n" + + "when comparing elements using %s", DEFAULT_RECURSIVE_COMPARATOR_DESCRIPTION)); } @Test @@ -85,54 +89,14 @@ void failed_isIn_assertion_using_recursive_field_by_field_element_comparator() { Foo[] array1 = { new Foo("id", new Bar(1)) }; Foo[] array2 = { new Foo("id", new Bar(2)) }; - assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(array1).usingRecursiveFieldByFieldElementComparator() - .isIn(new Object[] { array2 })) - .withMessage(format("%nExpecting:%n" - + " [Foo(id=id, bar=Bar(id=1))]%n" - + "to be in:%n" - + " [[Foo(id=id, bar=Bar(id=2))]]%n" - + "when comparing elements using recursive field/property by field/property comparator on all fields/properties%n" - + "Comparators used:%n" - + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}%n" - + "- for elements (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}")); - } - - @Test - void should_be_able_to_use_a_comparator_for_specified_fields_of_elements_when_using_recursive_field_by_field_element_comparator() { - Foo actual = new Foo("1", new Bar(1)); - Foo other = new Foo("1", new Bar(2)); - final class AlwaysEqualIntegerComparator implements Comparator { - @Override - public int compare(Integer o1, Integer o2) { - return 0; - } - } - - assertThat(array(actual)).usingComparatorForElementFieldsWithNames(new AlwaysEqualIntegerComparator(), "bar.id") - .usingRecursiveFieldByFieldElementComparator() - .contains(other); - } - - @Test - void comparators_for_element_field_names_should_have_precedence_over_comparators_for_element_field_types_when_using_recursive_field_by_field_element_comparator() { - Comparator comparator = (o1, o2) -> o1.compareTo(o2); - Foo actual = new Foo("1", new Bar(1)); - Foo other = new Foo("2", new Bar(1)); - - assertThat(array(actual)).usingComparatorForElementFieldsWithNames(ALWAY_EQUALS_STRING, "id") - .usingComparatorForElementFieldsWithType(comparator, String.class) - .usingRecursiveFieldByFieldElementComparator() - .contains(other); - } - - @Test - void should_be_able_to_use_a_comparator_for_element_fields_with_specified_type_when_using_recursive_field_by_field_element_comparator() { - Foo actual = new Foo("1", new Bar(1)); - Foo other = new Foo("2", new Bar(1)); + AssertionError assertionError = expectAssertionError(() -> assertThat(array1).usingRecursiveFieldByFieldElementComparator() + .isIn(singletonList(array2))); - assertThat(array(actual)).usingComparatorForElementFieldsWithType(ALWAY_EQUALS_STRING, String.class) - .usingRecursiveFieldByFieldElementComparator() - .contains(other); + then(assertionError).hasMessage(format("%nExpecting actual:%n" + + " [Foo(id=id, bar=Bar(id=1))]%n" + + "to be in:%n" + + " [[Foo(id=id, bar=Bar(id=2))]]%n" + + "when comparing elements using %s", DEFAULT_RECURSIVE_COMPARATOR_DESCRIPTION)); } public static class Foo { diff --git a/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_usingRecursiveFieldByFieldElementComparator_with_RecursiveComparisonConfiguration_Test.java b/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_usingRecursiveFieldByFieldElementComparator_with_RecursiveComparisonConfiguration_Test.java new file mode 100644 index 00000000000..c1e4e2f6b1b --- /dev/null +++ b/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_usingRecursiveFieldByFieldElementComparator_with_RecursiveComparisonConfiguration_Test.java @@ -0,0 +1,93 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api.objectarray; + +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.util.Arrays.array; + +import org.assertj.core.api.ObjectArrayAssert; +import org.assertj.core.api.ObjectArrayAssertBaseTest; +import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration; +import org.assertj.core.internal.ComparatorBasedComparisonStrategy; +import org.assertj.core.internal.ConfigurableRecursiveFieldByFieldComparator; +import org.assertj.core.internal.ObjectArrayElementComparisonStrategy; +import org.assertj.core.internal.ObjectArrays; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class ObjectArrayAssert_usingRecursiveFieldByFieldElementComparator_with_RecursiveComparisonConfiguration_Test + extends ObjectArrayAssertBaseTest { + + private ObjectArrays arraysBefore; + private RecursiveComparisonConfiguration recursiveComparisonConfiguration = new RecursiveComparisonConfiguration(); + + @BeforeEach + void before() { + arraysBefore = getArrays(assertions); + } + + @Override + protected ObjectArrayAssert invoke_api_method() { + return assertions.usingRecursiveFieldByFieldElementComparator(recursiveComparisonConfiguration); + } + + @Override + protected void verify_internal_effects() { + then(arraysBefore).isNotSameAs(getArrays(assertions)); + then(getArrays(assertions).getComparisonStrategy()).isInstanceOf(ComparatorBasedComparisonStrategy.class); + then(getObjects(assertions).getComparisonStrategy()).isInstanceOf(ObjectArrayElementComparisonStrategy.class); + ConfigurableRecursiveFieldByFieldComparator expectedComparator = new ConfigurableRecursiveFieldByFieldComparator(recursiveComparisonConfiguration); + then(getArrays(assertions).getComparator()).isEqualTo(expectedComparator); + then(getObjects(assertions).getComparisonStrategy()).extracting("elementComparator").isEqualTo(expectedComparator); + } + + @Test + void should_be_able_to_use_specific_RecursiveComparisonConfiguration_when_using_recursive_field_by_field_element_comparator() { + // GIVEN + Foo actual = new Foo("1", new Bar(1)); + Foo other = new Foo("2", new Bar(1)); + RecursiveComparisonConfiguration configuration = new RecursiveComparisonConfiguration(); + configuration.ignoreFields("id"); + // WHEN/THEN + then(array(actual)).usingRecursiveFieldByFieldElementComparator(configuration) + .contains(other); + } + + public static class Foo { + public String id; + public Bar bar; + + public Foo(String id, Bar bar) { + this.id = id; + this.bar = bar; + } + + @Override + public String toString() { + return "Foo(id=" + id + ", bar=" + bar + ")"; + } + } + + public static class Bar { + public int id; + + public Bar(int id) { + this.id = id; + } + + @Override + public String toString() { + return "Bar(id=" + id + ")"; + } + } +} diff --git a/src/test/java/org/assertj/core/api/offsetdatetime/OffsetDateTimeAssert_isEqualToIgnoringHours_Test.java b/src/test/java/org/assertj/core/api/offsetdatetime/OffsetDateTimeAssert_isEqualToIgnoringHours_Test.java index 7f34c642d19..8712a4dbaf1 100644 --- a/src/test/java/org/assertj/core/api/offsetdatetime/OffsetDateTimeAssert_isEqualToIgnoringHours_Test.java +++ b/src/test/java/org/assertj/core/api/offsetdatetime/OffsetDateTimeAssert_isEqualToIgnoringHours_Test.java @@ -41,7 +41,7 @@ void should_fail_if_actual_is_not_equal_to_given_offsetdatetime_with_hour_ignore AssertionError assertionError = expectAssertionError(() -> assertThat(refOffsetDateTime).isEqualToIgnoringHours(refOffsetDateTime.minusHours(1))); // THEN then(assertionError).hasMessage(format("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2000-01-02T00:00Z (java.time.OffsetDateTime)%n" + "to have same year, month and day as:%n" + " 2000-01-01T23:00Z (java.time.OffsetDateTime)%nbut had not.")); @@ -53,7 +53,7 @@ void should_fail_as_hours_fields_are_different_even_if_time_difference_is_less_t AssertionError assertionError = expectAssertionError(() -> assertThat(refOffsetDateTime).isEqualToIgnoringHours(refOffsetDateTime.minusNanos(1))); // THEN then(assertionError).hasMessage(format("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2000-01-02T00:00Z (java.time.OffsetDateTime)%n" + "to have same year, month and day as:%n" + " 2000-01-01T23:59:59.999999999Z (java.time.OffsetDateTime)%n" diff --git a/src/test/java/org/assertj/core/api/offsetdatetime/OffsetDateTimeAssert_isEqualToIgnoringMinutes_Test.java b/src/test/java/org/assertj/core/api/offsetdatetime/OffsetDateTimeAssert_isEqualToIgnoringMinutes_Test.java index 487d4841008..480c342bd04 100644 --- a/src/test/java/org/assertj/core/api/offsetdatetime/OffsetDateTimeAssert_isEqualToIgnoringMinutes_Test.java +++ b/src/test/java/org/assertj/core/api/offsetdatetime/OffsetDateTimeAssert_isEqualToIgnoringMinutes_Test.java @@ -41,7 +41,7 @@ void should_fail_if_actual_is_not_equal_to_given_offsetdatetime_with_minute_igno AssertionError assertionError = expectAssertionError(() -> assertThat(refOffsetDateTime).isEqualToIgnoringMinutes(refOffsetDateTime.minusMinutes(1))); // THEN then(assertionError).hasMessage(format("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2000-01-01T23:00Z (java.time.OffsetDateTime)%n" + "to have same year, month, day and hour as:%n" + " 2000-01-01T22:59Z (java.time.OffsetDateTime)%nbut had not.")); @@ -53,7 +53,7 @@ void should_fail_as_minutes_fields_are_different_even_if_time_difference_is_less AssertionError assertionError = expectAssertionError(() -> assertThat(refOffsetDateTime).isEqualToIgnoringMinutes(refOffsetDateTime.minusNanos(1))); // THEN then(assertionError).hasMessage(format("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2000-01-01T23:00Z (java.time.OffsetDateTime)%n" + "to have same year, month, day and hour as:%n" + " 2000-01-01T22:59:59.999999999Z (java.time.OffsetDateTime)%nbut had not.")); diff --git a/src/test/java/org/assertj/core/api/offsetdatetime/OffsetDateTimeAssert_isEqualToIgnoringNanoseconds_Test.java b/src/test/java/org/assertj/core/api/offsetdatetime/OffsetDateTimeAssert_isEqualToIgnoringNanoseconds_Test.java index 70ae9a30eec..c48c7067d7b 100644 --- a/src/test/java/org/assertj/core/api/offsetdatetime/OffsetDateTimeAssert_isEqualToIgnoringNanoseconds_Test.java +++ b/src/test/java/org/assertj/core/api/offsetdatetime/OffsetDateTimeAssert_isEqualToIgnoringNanoseconds_Test.java @@ -41,7 +41,7 @@ void should_fail_if_actual_is_not_equal_to_given_offsetdatetime_with_nanoseconds // WHEN AssertionError assertionError = expectAssertionError(() -> assertThat(refOffsetDateTime).isEqualToIgnoringNanos(refOffsetDateTime.plusSeconds(1))); // THEN - then(assertionError).hasMessage(format("%nExpecting:%n" + + then(assertionError).hasMessage(format("%nExpecting actual:%n" + " 2000-01-01T00:00:01Z (java.time.OffsetDateTime)%n" + "to have same year, month, day, hour, minute and second as:%n" + " 2000-01-01T00:00:02Z (java.time.OffsetDateTime)%n" + @@ -54,7 +54,7 @@ void should_fail_as_seconds_fields_are_different() { AssertionError assertionError = expectAssertionError(() -> assertThat(refOffsetDateTime).isEqualToIgnoringNanos(refOffsetDateTime.minusNanos(1))); // THEN then(assertionError).hasMessage(format("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2000-01-01T00:00:01Z (java.time.OffsetDateTime)%n" + "to have same year, month, day, hour, minute and second as:%n" + " 2000-01-01T00:00:00.999999999Z (java.time.OffsetDateTime)%n" + diff --git a/src/test/java/org/assertj/core/api/offsetdatetime/OffsetDateTimeAssert_isEqualToIgnoringSeconds_Test.java b/src/test/java/org/assertj/core/api/offsetdatetime/OffsetDateTimeAssert_isEqualToIgnoringSeconds_Test.java index 9b8d1859295..c312090b323 100644 --- a/src/test/java/org/assertj/core/api/offsetdatetime/OffsetDateTimeAssert_isEqualToIgnoringSeconds_Test.java +++ b/src/test/java/org/assertj/core/api/offsetdatetime/OffsetDateTimeAssert_isEqualToIgnoringSeconds_Test.java @@ -40,7 +40,7 @@ void should_fail_if_actual_is_not_equal_to_given_offsetdatetime_with_second_igno AssertionError assertionError = expectAssertionError(() -> assertThat(refOffsetDateTime).isEqualToIgnoringSeconds(refOffsetDateTime.plusMinutes(1))); // THEN then(assertionError).hasMessage(format("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2000-01-01T23:51Z (java.time.OffsetDateTime)%n" + "to have same year, month, day, hour and minute as:%n" + " 2000-01-01T23:52Z (java.time.OffsetDateTime)%n" + @@ -53,7 +53,7 @@ void should_fail_as_seconds_fields_are_different_even_if_time_difference_is_less AssertionError assertionError = expectAssertionError(() -> assertThat(refOffsetDateTime).isEqualToIgnoringSeconds(refOffsetDateTime.minusNanos(1))); // THEN then(assertionError).hasMessage(format("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2000-01-01T23:51Z (java.time.OffsetDateTime)%n" + "to have same year, month, day, hour and minute as:%n" + " 2000-01-01T23:50:59.999999999Z (java.time.OffsetDateTime)%n" + diff --git a/src/test/java/org/assertj/core/api/offsetdatetime/OffsetDateTimeAssert_isEqualToIgnoringTimezone_Test.java b/src/test/java/org/assertj/core/api/offsetdatetime/OffsetDateTimeAssert_isEqualToIgnoringTimezone_Test.java index e24090e314e..a4839cd66af 100644 --- a/src/test/java/org/assertj/core/api/offsetdatetime/OffsetDateTimeAssert_isEqualToIgnoringTimezone_Test.java +++ b/src/test/java/org/assertj/core/api/offsetdatetime/OffsetDateTimeAssert_isEqualToIgnoringTimezone_Test.java @@ -46,7 +46,7 @@ void should_fail_if_actual_is_not_equal_to_given_OffsetDateTime_with_timezone_ig // WHEN AssertionError assertionError = expectAssertionError(() -> assertThat(actual).isEqualToIgnoringTimezone(offsetDateTime)); // THEN - then(assertionError).hasMessage(format("%nExpecting:%n" + + then(assertionError).hasMessage(format("%nExpecting actual:%n" + " 2000-01-05T12:00+18:00 (java.time.OffsetDateTime)%n" + "to have same time fields except timezone as:%n" + " 2000-01-05T12:01Z (java.time.OffsetDateTime)%n" + diff --git a/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_hasSameHourAs_Test.java b/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_hasSameHourAs_Test.java index 7ab4480396d..7c9df874c0c 100644 --- a/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_hasSameHourAs_Test.java +++ b/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_hasSameHourAs_Test.java @@ -37,7 +37,7 @@ void should_pass_if_actual_andexpected_have_same_hour() { void should_fail_if_actual_is_not_equal_to_given_offsetTime_with_minute_ignored() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(refOffsetTime).hasSameHourAs(refOffsetTime.minusMinutes(1))) .withMessage(format("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " 23:00Z%n" + "to have same hour as:%n" + " 22:59Z%n" + @@ -48,7 +48,7 @@ void should_fail_if_actual_is_not_equal_to_given_offsetTime_with_minute_ignored( void should_fail_as_minutes_fields_are_different_even_if_time_difference_is_less_than_a_minute() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(refOffsetTime).hasSameHourAs(refOffsetTime.minusNanos(1))) .withMessage(format("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " 23:00Z%n" + "to have same hour as:%n" + " 22:59:59.999999999Z%n" + diff --git a/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isAfter_Test.java b/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isAfter_Test.java index 83e96589eb5..8fe7a842bf0 100644 --- a/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isAfter_Test.java +++ b/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isAfter_Test.java @@ -40,7 +40,7 @@ void test_isAfter_assertion() { void test_isAfter_assertion_error_message() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(parse("03:00:05.123Z")).isAfter(parse("03:00:05.123456789Z"))) .withMessage(format("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " 03:00:05.123Z%n" + "to be strictly after:%n" + " 03:00:05.123456789Z%n")); diff --git a/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isBefore_Test.java b/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isBefore_Test.java index fa3ef48dc61..051b44ceb30 100644 --- a/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isBefore_Test.java +++ b/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isBefore_Test.java @@ -50,7 +50,7 @@ void test_isBefore_assertion_error_message() { 0, ZoneOffset.UTC))) .withMessage(format("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " 03:00:05Z%n" + "to be strictly before:%n" + " 03:00:04Z%n")); diff --git a/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isEqualToIgnoringNanoseconds_Test.java b/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isEqualToIgnoringNanoseconds_Test.java index 32b2cce3bf8..ef8f747f35e 100644 --- a/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isEqualToIgnoringNanoseconds_Test.java +++ b/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isEqualToIgnoringNanoseconds_Test.java @@ -37,7 +37,7 @@ void should_pass_if_actual_is_equal_to_other_ignoring_nanosecond_fields() { @Test void should_fail_if_actual_is_not_equal_to_given_OffsetTime_with_nanoseconds_ignored() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(refOffsetTime).isEqualToIgnoringNanos(refOffsetTime.plusSeconds(1))) - .withMessage(format("%nExpecting:%n" + + .withMessage(format("%nExpecting actual:%n" + " 00:00:01Z%n" + "to have same hour, minute and second as:%n" + " 00:00:02Z%n" + @@ -47,7 +47,7 @@ void should_fail_if_actual_is_not_equal_to_given_OffsetTime_with_nanoseconds_ign @Test void should_fail_as_seconds_fields_are_different() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(refOffsetTime).isEqualToIgnoringNanos(refOffsetTime.minusNanos(1))) - .withMessage(format("%nExpecting:%n" + + .withMessage(format("%nExpecting actual:%n" + " 00:00:01Z%n" + "to have same hour, minute and second as:%n" + " 00:00:00.999999999Z%n" + diff --git a/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isEqualToIgnoringSeconds_Test.java b/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isEqualToIgnoringSeconds_Test.java index 7be527a6519..8c2c567985c 100644 --- a/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isEqualToIgnoringSeconds_Test.java +++ b/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isEqualToIgnoringSeconds_Test.java @@ -36,7 +36,7 @@ void should_pass_if_actual_is_equal_to_other_ignoring_second_fields() { @Test void should_fail_if_actual_is_not_equal_to_given_offsetTime_with_second_ignored() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(refOffsetTime).isEqualToIgnoringSeconds(refOffsetTime.plusMinutes(1))) - .withMessage(format("%nExpecting:%n" + + .withMessage(format("%nExpecting actual:%n" + " 23:51Z%n" + "to have same hour and minute as:%n" + " 23:52Z%n" + @@ -46,7 +46,7 @@ void should_fail_if_actual_is_not_equal_to_given_offsetTime_with_second_ignored( @Test void should_fail_as_seconds_fields_are_different_even_if_time_difference_is_less_than_a_second() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(refOffsetTime).isEqualToIgnoringSeconds(refOffsetTime.minusNanos(1))) - .withMessage(format("%nExpecting:%n" + + .withMessage(format("%nExpecting actual:%n" + " 23:51Z%n" + "to have same hour and minute as:%n" + " 23:50:59.999999999Z%n" + diff --git a/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isEqualToIgnoringTimezone_Test.java b/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isEqualToIgnoringTimezone_Test.java index 20abfdfa167..b5c19cdba26 100644 --- a/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isEqualToIgnoringTimezone_Test.java +++ b/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isEqualToIgnoringTimezone_Test.java @@ -40,7 +40,7 @@ void should_fail_if_actual_is_not_equal_to_given_OffsetTime_with_timezone_ignore 0, 0, ZoneOffset.UTC))) - .withMessage(format("%nExpecting:%n" + + .withMessage(format("%nExpecting actual:%n" + " 12:00+18:00%n" + "to have same time fields except timezone as:%n" + diff --git a/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isIn_Test.java b/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isIn_Test.java index 24a6672f2e6..33e982c60b7 100644 --- a/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isIn_Test.java +++ b/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isIn_Test.java @@ -45,7 +45,7 @@ void test_isIn_assertion_error_message() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(OffsetTime.of(3, 0, 5, 0, ZoneOffset.UTC)).isIn("03:03:03Z")) .withMessage(format("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " 03:00:05Z%n" + "to be in:%n" + " [03:03:03Z]%n")); diff --git a/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isNotEqualTo_Test.java b/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isNotEqualTo_Test.java index fac254dd580..783f5fc2a3d 100644 --- a/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isNotEqualTo_Test.java +++ b/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isNotEqualTo_Test.java @@ -44,7 +44,7 @@ void test_isNotEqualTo_assertion_error_message() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(OffsetTime.of(3, 0, 5, 0, ZoneOffset.UTC)).isNotEqualTo("03:00:05Z")) .withMessage(format("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " 03:00:05Z%n" + "not to be equal to:%n" + " 03:00:05Z%n")); diff --git a/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isNotIn_Test.java b/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isNotIn_Test.java index 244042f54c8..ec866c3f493 100644 --- a/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isNotIn_Test.java +++ b/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isNotIn_Test.java @@ -45,7 +45,7 @@ void test_isNotIn_assertion_error_message() { ZoneOffset.UTC)).isNotIn("03:00:05Z", "03:03:03Z")) .withMessage(format("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " 03:00:05Z%n" + "not to be in:%n" + " [03:00:05Z, 03:03:03Z]%n")); diff --git a/src/test/java/org/assertj/core/api/optional/OptionalAssert_get_with_InstanceOfAssertFactory_Test.java b/src/test/java/org/assertj/core/api/optional/OptionalAssert_get_with_InstanceOfAssertFactory_Test.java index e8fb2582fdf..8ee35418918 100644 --- a/src/test/java/org/assertj/core/api/optional/OptionalAssert_get_with_InstanceOfAssertFactory_Test.java +++ b/src/test/java/org/assertj/core/api/optional/OptionalAssert_get_with_InstanceOfAssertFactory_Test.java @@ -84,7 +84,7 @@ void should_fail_if_optional_does_not_contain_an_instance_of_the_factory_type() // WHEN AssertionError assertionError = expectAssertionError(() -> assertThat(optional).get(INTEGER)); // THEN - then(assertionError).hasMessageContainingAll("Expecting:", "to be an instance of:", "but was instance of:"); + then(assertionError).hasMessageContainingAll("Expecting actual:", "to be an instance of:", "but was instance of:"); } @Override diff --git a/src/test/java/org/assertj/core/api/recursive/comparison/ComparisonDifference_compareTo_Test.java b/src/test/java/org/assertj/core/api/recursive/comparison/ComparisonDifference_compareTo_Test.java index e6561652ea1..073a07fbeb0 100644 --- a/src/test/java/org/assertj/core/api/recursive/comparison/ComparisonDifference_compareTo_Test.java +++ b/src/test/java/org/assertj/core/api/recursive/comparison/ComparisonDifference_compareTo_Test.java @@ -35,7 +35,7 @@ void should_order_differences_by_alphabetical_path_ignoring_dot_separator() { // WHEN Set differences = newTreeSet(diff1, diff2, diff3, diff4, diff5, diff6); // THEN - assertThat(differences).extracting(input -> input.concatenatedPath) + assertThat(differences).extracting(diff -> diff.concatenatedPath) .containsExactly("aa", "aaa", "a.b", "a.b.c", "a.c", "b"); } diff --git a/src/test/java/org/assertj/core/api/recursive/comparison/ComparisonDifference_multiLineDescription_Test.java b/src/test/java/org/assertj/core/api/recursive/comparison/ComparisonDifference_multiLineDescription_Test.java index 2ef880ca646..8e9a61c64f3 100644 --- a/src/test/java/org/assertj/core/api/recursive/comparison/ComparisonDifference_multiLineDescription_Test.java +++ b/src/test/java/org/assertj/core/api/recursive/comparison/ComparisonDifference_multiLineDescription_Test.java @@ -43,8 +43,8 @@ void should_build_a_multiline_description() { String multiLineDescription = comparisonDifference.multiLineDescription(); // THEN assertThat(multiLineDescription).isEqualTo(format("field/property 'a.b' differ:%n" + - "- actual value : \"foo\"%n" + - "- expected value : \"bar\"")); + "- actual value : \"foo\"%n" + + "- expected value: \"bar\"")); } @Test @@ -55,8 +55,8 @@ void multiline_description_should_indicate_top_level_objects_difference() { String multiLineDescription = comparisonDifference.multiLineDescription(); // THEN assertThat(multiLineDescription).isEqualTo(format("Top level actual and expected objects differ:%n" + - "- actual value : \"foo\"%n" + - "- expected value : \"bar\"")); + "- actual value : \"foo\"%n" + + "- expected value: \"bar\"")); } @ParameterizedTest(name = "path {0}, index {1}") @@ -68,8 +68,8 @@ void multiline_description_should_indicate_top_level_objects_element_difference( String multiLineDescription = comparisonDifference.multiLineDescription(); // THEN assertThat(multiLineDescription).isEqualTo(format("Top level actual and expected objects element at index %s differ:%n" + - "- actual value : \"foo\"%n" + - "- expected value : \"bar\"", index)); + "- actual value : \"foo\"%n" + + "- expected value: \"bar\"", index)); } @ParameterizedTest(name = "path {0}, index {1}") @@ -81,8 +81,8 @@ void multiline_description_should_indicate_element_difference(List path, String multiLineDescription = comparisonDifference.multiLineDescription(); // THEN assertThat(multiLineDescription).isEqualTo(format("field/property %s differ:%n" + - "- actual value : \"foo\"%n" + - "- expected value : \"bar\"", index)); + "- actual value : \"foo\"%n" + + "- expected value: \"bar\"", index)); } private static Stream multiline_description_should_indicate_element_difference() { @@ -101,8 +101,8 @@ void multiline_description_should_show_sets_type_difference_when_their_content_i String multiLineDescription = comparisonDifference.multiLineDescription(); // THEN assertThat(multiLineDescription).contains("field/property 'a.b' differ:") - .contains("- actual value : [\"bar\", \"foo\"] (LinkedHashSet@") - .contains("- expected value : [\"bar\", \"foo\"] (TreeSet@"); + .contains("- actual value : [\"bar\", \"foo\"] (LinkedHashSet@") + .contains("- expected value: [\"bar\", \"foo\"] (TreeSet@"); } @Test @@ -115,8 +115,8 @@ void multiline_description_should_show_maps_type_difference_when_their_content_i String multiLineDescription = comparisonDifference.multiLineDescription(); // THEN assertThat(multiLineDescription).contains("field/property 'a.b' differ:") - .contains("- actual value : {1L=true, 2L=false} (LinkedHashMap@") - .contains("- expected value : {1L=true, 2L=false} (TreeMap@"); + .contains("- actual value : {1L=true, 2L=false} (LinkedHashMap@") + .contains("- expected value: {1L=true, 2L=false} (TreeMap@"); } @Test @@ -126,8 +126,8 @@ void should_build_comparison_difference_multiline_description_with_additional_in ComparisonDifference com = new ComparisonDifference(dualValue, "additional information"); // THEN assertThat(com.multiLineDescription()).isEqualTo(format("field/property 'a.b' differ:%n" + - "- actual value : \"foo\"%n" + - "- expected value : \"bar\"%n" + + "- actual value : \"foo\"%n" + + "- expected value: \"bar\"%n" + "additional information")); } @@ -138,8 +138,8 @@ void should_build_multiline_description_containing_percent() { ComparisonDifference com = new ComparisonDifference(dualValue, "%additional %information%"); // THEN assertThat(com.multiLineDescription()).isEqualTo(format("field/property 'a.b' differ:%n" + - "- actual value : \"foo%%\"%n" + - "- expected value : \"%%bar%%%%\"%n" + + "- actual value : \"foo%%\"%n" + + "- expected value: \"%%bar%%%%\"%n" + "%%additional %%information%%")); } } diff --git a/src/test/java/org/assertj/core/api/recursive/comparison/ComparisonDifference_rootComparisonDifference_Test.java b/src/test/java/org/assertj/core/api/recursive/comparison/ComparisonDifference_rootComparisonDifference_Test.java index 704cc6f0a67..01b37e7bc7d 100644 --- a/src/test/java/org/assertj/core/api/recursive/comparison/ComparisonDifference_rootComparisonDifference_Test.java +++ b/src/test/java/org/assertj/core/api/recursive/comparison/ComparisonDifference_rootComparisonDifference_Test.java @@ -28,8 +28,8 @@ void should_build_ComparisonDifference_for_root_dual_value() { String multiLineDescription = comparisonDifference.multiLineDescription(); // THEN assertThat(multiLineDescription).isEqualTo(format("Top level actual and expected objects differ:%n" + - "- actual value : \"foo\"%n" + - "- expected value : \"bar\"%n" + + "- actual value : \"foo\"%n" + + "- expected value: \"bar\"%n" + "info")); } diff --git a/src/test/java/org/assertj/core/api/recursive/comparison/ComparisonKeyDifference_multiLineDescription_Test.java b/src/test/java/org/assertj/core/api/recursive/comparison/ComparisonKeyDifference_multiLineDescription_Test.java new file mode 100644 index 00000000000..a39d323fcf6 --- /dev/null +++ b/src/test/java/org/assertj/core/api/recursive/comparison/ComparisonKeyDifference_multiLineDescription_Test.java @@ -0,0 +1,67 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api.recursive.comparison; + +import static java.lang.String.format; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.util.Lists.list; + +import org.junit.jupiter.api.Test; + +class ComparisonKeyDifference_multiLineDescription_Test { + + @Test + void should_build_a_multiline_description() { + // GIVEN + DualValue dualValue = new DualValue(list("a", "b"), "foo", "bar"); + ComparisonDifference comparisonDifference = new ComparisonKeyDifference(dualValue, "k1", "k2"); + // WHEN + String multiLineDescription = comparisonDifference.multiLineDescription(); + // THEN + assertThat(multiLineDescription).isEqualTo(format("field/property 'a.b' differ:%n" + + "- actual value : \"foo\"%n" + + "- expected value: \"bar\"%n" + + "map key difference:%n" + + "- actual key : \"k1\"%n" + + "- expected key: \"k2\"")); + } + + @Test + void multiline_description_should_indicate_top_level_objects_difference() { + // GIVEN + ComparisonDifference comparisonDifference = new ComparisonKeyDifference(new DualValue(list(), "foo", "bar"), "k1", "k2"); + // WHEN + String multiLineDescription = comparisonDifference.multiLineDescription(); + // THEN + assertThat(multiLineDescription).isEqualTo(format("Top level actual and expected objects differ:%n" + + "- actual value : \"foo\"%n" + + "- expected value: \"bar\"%n" + + "map key difference:%n" + + "- actual key : \"k1\"%n" + + "- expected key: \"k2\"")); + } + + @Test + void should_build_multiline_description_containing_percent() { + // GIVEN + DualValue dualValue = new DualValue(list("a", "b"), "foo%", "%bar%%"); + ComparisonDifference com = new ComparisonKeyDifference(dualValue, "%k1", "%k2%%"); + // THEN + assertThat(com.multiLineDescription()).isEqualTo(format("field/property 'a.b' differ:%n" + + "- actual value : \"foo%%\"%n" + + "- expected value: \"%%bar%%%%\"%n" + + "map key difference:%n" + + "- actual key : \"%%k1\"%n" + + "- expected key: \"%%k2%%%%\"")); + } +} diff --git a/src/test/java/org/assertj/core/api/recursive/comparison/FieldLocation_Test.java b/src/test/java/org/assertj/core/api/recursive/comparison/FieldLocation_Test.java index 107964fcc70..9fcccb64c2f 100644 --- a/src/test/java/org/assertj/core/api/recursive/comparison/FieldLocation_Test.java +++ b/src/test/java/org/assertj/core/api/recursive/comparison/FieldLocation_Test.java @@ -14,16 +14,11 @@ import static org.assertj.core.api.BDDAssertions.then; import static org.assertj.core.util.Lists.list; -import static org.junit.jupiter.params.provider.Arguments.arguments; import java.util.Collections; import java.util.List; -import java.util.stream.Stream; import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; import nl.jqno.equalsverifier.EqualsVerifier; @@ -51,27 +46,6 @@ void compareTo_should_order_field_location_by_alphabetical_path() { then(fieldLocations).containsExactly(fieldLocation1, fieldLocation2, fieldLocation3, fieldLocation4); } - @ParameterizedTest(name = "{0} matches {1}") - @MethodSource - void matches_should_match_fields(List fieldPath, String matchingFieldPath) { - // GIVEN - FieldLocation underTest = new FieldLocation(fieldPath); - // WHEN - boolean match = underTest.matches(matchingFieldPath); - // THEN - then(match).as("%s matches %s", underTest, matchingFieldPath).isTrue(); - } - - private static Stream matches_should_match_fields() { - return Stream.of(arguments(list("name"), "name"), - arguments(list("name", "first"), "name.first"), - arguments(list("name", "[2]", "first"), "name.first"), - arguments(list("[0]", "first"), "first"), - arguments(list("[1]", "first", "second"), "first.second"), - arguments(list("person", "[1]", "first", "second"), "person.first.second"), - arguments(list("father", "name", "first"), "father.name.first")); - } - @Test void toString_should_succeed() { // GIVEN diff --git a/src/test/java/org/assertj/core/api/recursive/comparison/FieldLocation_matches_Test.java b/src/test/java/org/assertj/core/api/recursive/comparison/FieldLocation_matches_Test.java new file mode 100644 index 00000000000..c4f28b32367 --- /dev/null +++ b/src/test/java/org/assertj/core/api/recursive/comparison/FieldLocation_matches_Test.java @@ -0,0 +1,49 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api.recursive.comparison; + +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.util.Lists.list; +import static org.junit.jupiter.params.provider.Arguments.arguments; + +import java.util.List; +import java.util.stream.Stream; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class FieldLocation_matches_Test { + + @ParameterizedTest(name = "{0} matches {1}") + @MethodSource + void matches_should_match_fields(List fieldPath, String matchingFieldPath) { + // GIVEN + FieldLocation underTest = new FieldLocation(fieldPath); + // WHEN + boolean match = underTest.matches(matchingFieldPath); + // THEN + then(match).as("%s matches %s", underTest, matchingFieldPath).isTrue(); + } + + private static Stream matches_should_match_fields() { + return Stream.of(arguments(list("name"), "name"), + arguments(list("name", "first"), "name.first"), + arguments(list("name", "[2]", "first"), "name.first"), + arguments(list("[0]", "first"), "first"), + arguments(list("[1]", "first", "second"), "first.second"), + arguments(list("person", "[1]", "first", "second"), "person.first.second"), + arguments(list("father", "name", "first"), "father.name.first")); + } + +} diff --git a/src/test/java/org/assertj/core/api/recursive/comparison/FieldLocation_startsWith_Test.java b/src/test/java/org/assertj/core/api/recursive/comparison/FieldLocation_startsWith_Test.java new file mode 100644 index 00000000000..cd12520644e --- /dev/null +++ b/src/test/java/org/assertj/core/api/recursive/comparison/FieldLocation_startsWith_Test.java @@ -0,0 +1,49 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api.recursive.comparison; + +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.util.Lists.list; +import static org.junit.jupiter.params.provider.Arguments.arguments; + +import java.util.List; +import java.util.stream.Stream; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class FieldLocation_startsWith_Test { + + @ParameterizedTest(name = "{0} matches {1}") + @MethodSource + void startsWith_should_match_fields_starting_with_given_field_path(List fieldPath, String startFieldPath) { + // GIVEN + FieldLocation underTest = new FieldLocation(fieldPath); + // WHEN + boolean match = underTest.startsWith(startFieldPath); + // THEN + then(match).as("%s starts with %s", underTest, startFieldPath).isTrue(); + } + + private static Stream startsWith_should_match_fields_starting_with_given_field_path() { + return Stream.of(arguments(list("name"), "name"), + arguments(list("name", "first"), "name"), + arguments(list("name", "first"), "name.first"), + arguments(list("name", "[2]", "first"), "name"), + arguments(list("name", "[2]", "first"), "name.first"), + arguments(list("person", "[1]", "first", "second"), "person.first"), + arguments(list("father", "name", "first"), "father")); + } + +} diff --git a/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonAssert_bddSoftAssertions_Test.java b/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonAssert_bddSoftAssertions_Test.java index 8b88b65eead..0f125dab884 100644 --- a/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonAssert_bddSoftAssertions_Test.java +++ b/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonAssert_bddSoftAssertions_Test.java @@ -61,11 +61,11 @@ void should_report_all_errors_with_bdd_soft_assertions() { List errorsCollected = softly.errorsCollected(); assertThat(errorsCollected).hasSize(2); assertThat(errorsCollected.get(0)).hasMessageContaining("field/property 'home.address.number' differ:") - .hasMessageContaining("- actual value : 1") - .hasMessageContaining("- expected value : 2"); + .hasMessageContaining("- actual value : 1") + .hasMessageContaining("- expected value: 2"); assertThat(errorsCollected.get(1)).hasMessageContaining("field/property 'home.address.number' differ:") - .hasMessageContaining("- actual value : 2") - .hasMessageContaining("- expected value : 1"); + .hasMessageContaining("- actual value : 2") + .hasMessageContaining("- expected value: 1"); } } diff --git a/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonAssert_for_maps_Test.java b/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonAssert_for_maps_Test.java index a9af0938b5b..a23081897d7 100644 --- a/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonAssert_for_maps_Test.java +++ b/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonAssert_for_maps_Test.java @@ -12,9 +12,12 @@ */ package org.assertj.core.api.recursive.comparison; +import static java.lang.String.format; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; import static org.assertj.core.api.BDDAssertions.then; import static org.assertj.core.test.Maps.mapOf; +import static org.assertj.core.util.AssertionsUtil.expectAssertionError; import java.util.Map; @@ -22,6 +25,9 @@ import org.assertj.core.test.Person; import org.junit.jupiter.api.Test; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSortedMap; + class RecursiveComparisonAssert_for_maps_Test { @Test @@ -48,4 +54,63 @@ void should_be_directly_usable_with_maps() { .isEqualTo(expected); } + @Test + public void should_honor_ignored_fields() { + // GIVEN + Map mapA = ImmutableMap.of("foo", "bar", "description", "foobar", "submap", + ImmutableMap.of("subFoo", "subBar", "description", "subFooBar")); + Map mapB = ImmutableMap.of("foo", "bar", "description", "barfoo", "submap", + ImmutableMap.of("subFoo", "subBar", "description", "subBarFoo")); + // THEN + assertThat(mapA).usingRecursiveComparison() + .ignoringFields("description", "submap.description") + .isEqualTo(mapB); + assertThat(mapA).usingRecursiveComparison() + .ignoringFieldsMatchingRegexes(".*description") + .isEqualTo(mapB); + } + + @Test + public void should_honor_ignored_fields_with_sorted_maps() { + // GIVEN + Map mapA = ImmutableSortedMap.of("foo", "bar", "description", "foobar", "submap", + ImmutableSortedMap.of("subFoo", "subBar", "description", "subFooBar")); + Map mapB = ImmutableSortedMap.of("foo", "bar", "description", "barfoo", "submap", + ImmutableSortedMap.of("subFoo", "subBar", "description", "subBarFoo")); + // THEN + assertThat(mapA).usingRecursiveComparison() + .ignoringFields("description", "submap.description") + .isEqualTo(mapB); + assertThat(mapA).usingRecursiveComparison() + .ignoringFieldsMatchingRegexes(".*description") + .isEqualTo(mapB); + } + + @Test + public void should_repor_missing_keys_as_missing_fields() { + // GIVEN + Map mapA = ImmutableSortedMap.of("foo", "bar", "desc", "foobar", "submap", + ImmutableSortedMap.of("subFoo", "subBar", "description", "subFooBar")); + Map mapB = ImmutableSortedMap.of("fu", "bar", "description", "foobar", "submap", + ImmutableSortedMap.of("subFu", "subBar", "description", "subFuBar")); + // WHEN + AssertionError assertionError = expectAssertionError(() -> assertThat(mapA).usingRecursiveComparison() + .isEqualTo(mapB)); + // THEN + then(assertionError).hasMessageContainingAll(format("map key difference:%n" + + "- actual key : \"foo\"%n" + + "- expected key: \"fu\""), + format("map key difference:%n" + + "- actual key : \"desc\"%n" + + "- expected key: \"description\""), + format("map key difference:%n" + + "- actual key : \"subFoo\"%n" + + "- expected key: \"subFu\""), + format("field/property 'submap.description' differ:%n" + + "- actual value : \"subFooBar\"%n" + + "- expected value: \"subFuBar\"") + + ); + } + } diff --git a/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonAssert_isEqualTo_Test.java b/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonAssert_isEqualTo_Test.java index bd6883adb33..0738f02e82c 100644 --- a/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonAssert_isEqualTo_Test.java +++ b/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonAssert_isEqualTo_Test.java @@ -359,7 +359,6 @@ public LightString(String value) { } @Test - @DisabledOnOs(WINDOWS) void should_not_treat_Path_as_Iterable_to_avoid_infinite_recursion() { final Container container1 = new Container("/tmp/example"); final Container container2 = new Container("/tmp/example"); diff --git a/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonAssert_isEqualTo_comparingOnlyFields_Test.java b/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonAssert_isEqualTo_comparingOnlyFields_Test.java new file mode 100644 index 00000000000..70eb249372c --- /dev/null +++ b/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonAssert_isEqualTo_comparingOnlyFields_Test.java @@ -0,0 +1,154 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.api.recursive.comparison; + +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.util.Lists.list; +import static org.junit.jupiter.params.provider.Arguments.arguments; + +import java.util.Date; +import java.util.List; +import java.util.stream.Stream; + +import org.assertj.core.api.RecursiveComparisonAssert_isEqualTo_BaseTest; +import org.assertj.core.internal.objects.data.Human; +import org.assertj.core.internal.objects.data.Person; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class RecursiveComparisonAssert_isEqualTo_comparingOnlyFields_Test extends RecursiveComparisonAssert_isEqualTo_BaseTest { + + @ParameterizedTest(name = "{2}: actual={0} / expected={1}") + @MethodSource + void should_only_compare_given_fields(Object actual, Object expected, List fieldNamesToCompare) { + + then(actual).usingRecursiveComparison() + .comparingOnlyFields(arrayOf(fieldNamesToCompare)) + .isEqualTo(expected); + } + + private static Stream should_only_compare_given_fields() { + Person person1 = new Person("John"); + person1.home.address.number = 1; + + Person person2 = new Person("John"); + person2.home.address.number = 2; + + Person john = new Person("John"); + john.home.address.number = 1; + john.dateOfBirth = new Date(123); + john.neighbour = new Person("Jim"); + john.neighbour.home.address.number = 123; + john.neighbour.neighbour = new Person("James"); + john.neighbour.neighbour.home.address.number = 124; + + Person jack = new Person("Jack"); + jack.home.address.number = 1; + jack.dateOfBirth = new Date(456); + jack.neighbour = new Person("Jack"); + jack.neighbour.home.address.number = 456; + jack.neighbour.neighbour = new Person("James"); + jack.neighbour.neighbour.home.address.number = 124; + + Human person4 = new Human(); + person4.name = "John"; + person4.home.address.number = 1; + + Human person5 = new Human(); + person5.home.address.number = 1; + + return Stream.of(arguments(person1, person2, list("name")), + arguments(person1, person4, list("name")), + arguments(person1, person5, list("home")), + arguments(person1, person5, list("home.address")), + arguments(person1, person5, list("home.address.number")), + arguments(john, jack, list("home", "neighbour.neighbour")), + arguments(john, jack, list("home.address", "neighbour.neighbour")), + arguments(john, jack, list("home.address.number", "neighbour.neighbour")), + arguments(john, jack, list("home", "neighbour.neighbour.home")), + arguments(john, jack, list("home.address", "neighbour.neighbour"))); + } + + @Test + void should_fail_when_actual_differs_from_expected_on_compared_fields() { + // GIVEN + Person actual = new Person("John"); + actual.home.address.number = 1; + actual.dateOfBirth = new Date(123); + actual.neighbour = new Person("Jim"); + actual.neighbour.home.address.number = 123; + actual.neighbour.neighbour = new Person("James"); + actual.neighbour.neighbour.home.address.number = 124; + + Person expected = new Person("John"); + expected.home.address.number = 1; + expected.dateOfBirth = new Date(456); + expected.neighbour = new Person("Jack"); + expected.neighbour.home.address.number = 123; + expected.neighbour.neighbour = new Person("James"); + expected.neighbour.neighbour.home.address.number = 125; + + recursiveComparisonConfiguration.compareOnlyFields("name", "home", "dateOfBirth", "neighbour"); + + // WHEN + compareRecursivelyFailsAsExpected(actual, expected); + + // THEN + ComparisonDifference dateOfBirthDifference = diff("dateOfBirth", actual.dateOfBirth, expected.dateOfBirth); + ComparisonDifference neighbourNameDifference = diff("neighbour.name", actual.neighbour.name, expected.neighbour.name); + ComparisonDifference numberDifference = diff("neighbour.neighbour.home.address.number", + actual.neighbour.neighbour.home.address.number, + expected.neighbour.neighbour.home.address.number); + verifyShouldBeEqualByComparingFieldByFieldRecursivelyCall(actual, expected, + dateOfBirthDifference, neighbourNameDifference, numberDifference); + } + + @Test + void can_be_combined_with_ignoringFields() { + // GIVEN + Person actual = new Person("John"); + actual.home.address.number = 1; + actual.dateOfBirth = new Date(123); + actual.neighbour = new Person("Jim"); + actual.neighbour.home.address.number = 123; + actual.neighbour.neighbour = new Person("James"); + actual.neighbour.neighbour.home.address.number = 124; + + Person expected = new Person(actual.name); + expected.home.address.number = 2; + expected.dateOfBirth = new Date(456); + expected.neighbour = new Person("Jack"); + expected.neighbour.home.address.number = actual.neighbour.home.address.number; + expected.neighbour.neighbour = new Person(actual.neighbour.neighbour.name); + expected.neighbour.neighbour.home.address.number = 125; + + // WHEN/THEN + then(actual).usingRecursiveComparison() + .comparingOnlyFields("name", "home", "neighbour") + // ignores all different fields from the compared fields + .ignoringFields("home.address.number", "neighbour.name", "neighbour.neighbour.home.address.number") + .isEqualTo(expected); + then(actual).usingRecursiveComparison() + // ignores all different fields from the compared fields + .ignoringFields("home.address.number", "neighbour.name", "neighbour.neighbour.home.address.number") + .comparingOnlyFields("name", "home", "neighbour") + .isEqualTo(expected); + } + + private static String[] arrayOf(List list) { + return list.toArray(new String[0]); + } + +} diff --git a/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonAssert_isEqualTo_ignoringCollectionOrder_Test.java b/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonAssert_isEqualTo_ignoringCollectionOrder_Test.java index 2ade10152ba..4d63779c83c 100644 --- a/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonAssert_isEqualTo_ignoringCollectionOrder_Test.java +++ b/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonAssert_isEqualTo_ignoringCollectionOrder_Test.java @@ -14,6 +14,8 @@ import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.recursive.comparison.RecursiveComparisonAssert_isEqualTo_ignoringCollectionOrder_Test.Type.FIRST; +import static org.assertj.core.api.recursive.comparison.RecursiveComparisonAssert_isEqualTo_ignoringCollectionOrder_Test.Type.SECOND; import static org.assertj.core.internal.objects.data.FriendlyPerson.friend; import static org.assertj.core.util.Arrays.array; import static org.assertj.core.util.Lists.list; @@ -358,4 +360,70 @@ void should_fix_1854_with_non_wrapped_basic_types() { } + enum Type { + FIRST, SECOND, + } + + static class PersonWithEnum { + String name; + Type type; + + PersonWithEnum(String name, Type type) { + this.name = name; + this.type = type; + } + + @Override + public String toString() { + return String.format("Person [name=%s, type=%s]", name, type); + } + + } + + @Test + public void should_not_remove_already_visited_enum_dual_values_as_they_cant_produce_cycles() { + // GIVEN + List persons = list(new PersonWithEnum("name-1", FIRST), + new PersonWithEnum("name-2", FIRST), + new PersonWithEnum("name-2", SECOND)); + + // WHEN/THEN + assertThat(persons).usingRecursiveComparison() + .ignoringCollectionOrder() + .isEqualTo(list(new PersonWithEnum("name-2", SECOND), + new PersonWithEnum("name-2", FIRST), + new PersonWithEnum("name-1", FIRST))); + } + + static class PersonWithInt { + String name; + int type; + + PersonWithInt(String name, int type) { + this.name = name; + this.type = type; + } + + @Override + public String toString() { + return String.format("Person [name=%s, type=%s]", name, type); + } + + } + + @Test + public void should_not_remove_already_visited_int_dual_values_as_they_cant_produce_cycles() { + // GIVEN + List persons = list(new PersonWithInt("name-1", 1), + new PersonWithInt("name-2", 1), + new PersonWithInt("name-2", 2)); + + // WHEN/THEN + assertThat(persons).usingRecursiveComparison() + .ignoringCollectionOrder() + .isEqualTo(list(new PersonWithInt("name-2", 2), + new PersonWithInt("name-2", 1), + new PersonWithInt("name-1", 1))); + } + } diff --git a/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonAssert_isEqualTo_with_iterables_Test.java b/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonAssert_isEqualTo_with_iterables_Test.java index 1472ad20d6e..d62a7220311 100644 --- a/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonAssert_isEqualTo_with_iterables_Test.java +++ b/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonAssert_isEqualTo_with_iterables_Test.java @@ -70,7 +70,7 @@ static Stream should_fail_as_Person_overridden_equals_should_be_honor + " [Person[name='Sheldon']]"))), Arguments.of(actualAsArray, expectedAsArray, diff("[0]", sheldon, sheldonDto)), Arguments.of(actualAsOptional, expectedAsOptional, diff("value", sheldon, sheldonDto)), - Arguments.of(actualAsMap, expectedAsMap, diff("", sheldon, sheldonDto))); + Arguments.of(actualAsMap, expectedAsMap, diff("sheldon", sheldon, sheldonDto))); } @ParameterizedTest(name = "author 1 {0} / author 2 {1}") diff --git a/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonAssert_isEqualTo_with_maps_Test.java b/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonAssert_isEqualTo_with_maps_Test.java index b53c79684df..c9e15b741f1 100644 --- a/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonAssert_isEqualTo_with_maps_Test.java +++ b/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonAssert_isEqualTo_with_maps_Test.java @@ -128,7 +128,7 @@ static Stream differentMaps() { Arguments.of(nonSortedPratchettAndMartin, sortedMartinAndPratchett, "group", nonSortedPratchettAndMartin, sortedMartinAndPratchett, "expected field is a sorted map but actual field is not (java.util.LinkedHashMap)"), - Arguments.of(singletonMap(pratchett.name, none), singletonPratchettMap, "group", + Arguments.of(singletonMap(pratchett.name, none), singletonPratchettMap, "group.Terry Pratchett", none, pratchett, null), Arguments.of(singletonPratchettMap, singletonMap(georgeMartin.name, pratchett), "group", singletonPratchettMap, singletonMap(georgeMartin.name, pratchett), diff --git a/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonAssert_softAssertions_Test.java b/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonAssert_softAssertions_Test.java index 494eb409a34..6bcc6e9fe33 100644 --- a/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonAssert_softAssertions_Test.java +++ b/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonAssert_softAssertions_Test.java @@ -61,11 +61,11 @@ void should_report_all_errors_with_soft_assertions() { List errorsCollected = softly.errorsCollected(); assertThat(errorsCollected).hasSize(2); assertThat(errorsCollected.get(0)).hasMessageContaining("field/property 'home.address.number' differ:") - .hasMessageContaining("- actual value : 1") - .hasMessageContaining("- expected value : 2"); + .hasMessageContaining("- actual value : 1") + .hasMessageContaining("- expected value: 2"); assertThat(errorsCollected.get(1)).hasMessageContaining("field/property 'home.address.number' differ:") - .hasMessageContaining("- actual value : 2") - .hasMessageContaining("- expected value : 1"); + .hasMessageContaining("- actual value : 2") + .hasMessageContaining("- expected value: 1"); } } diff --git a/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonConfiguration_builder_Test.java b/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonConfiguration_builder_Test.java index 06cf54ab763..cb8dfff878b 100644 --- a/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonConfiguration_builder_Test.java +++ b/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonConfiguration_builder_Test.java @@ -26,6 +26,15 @@ class RecursiveComparisonConfiguration_builder_Test { + @Test + void should_use_same_defaults_as_constructor() { + // GIVEN + RecursiveComparisonConfiguration configurationBuiltWithBuilder = RecursiveComparisonConfiguration.builder().build(); + RecursiveComparisonConfiguration configurationBuiltWithConstructor = new RecursiveComparisonConfiguration(); + // WHEN/THEN + then(configurationBuiltWithBuilder).isEqualTo(configurationBuiltWithConstructor); + } + @Test void should_set_ignoreAllActualNullFields() { // GIVEN @@ -111,6 +120,18 @@ void should_set_ignoreCollectionOrderInFieldsMatchingRegexes() { .containsExactly(values); } + @Test + void should_set_comparedFields() { + // GIVEN + String[] values = { "foo", "bar" }; + // WHEN + RecursiveComparisonConfiguration configuration = RecursiveComparisonConfiguration.builder() + .withComparedFields(values) + .build(); + // THEN + then(configuration.getComparedFields()).containsExactly(values); + } + @Test void should_set_ignoredFields() { // GIVEN diff --git a/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonConfiguration_multiLineDescription_Test.java b/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonConfiguration_multiLineDescription_Test.java index fd74869e60a..4ceb3e02b89 100644 --- a/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonConfiguration_multiLineDescription_Test.java +++ b/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonConfiguration_multiLineDescription_Test.java @@ -13,7 +13,7 @@ package org.assertj.core.api.recursive.comparison; import static java.lang.String.format; -import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.BDDAssertions.then; import static org.assertj.core.presentation.StandardRepresentation.STANDARD_REPRESENTATION; import static org.assertj.core.test.AlwaysDifferentComparator.alwaysDifferent; import static org.assertj.core.test.AlwaysEqualComparator.ALWAY_EQUALS_TUPLE; @@ -50,7 +50,7 @@ void should_show_that_actual_null_fields_are_ignored() { // WHEN String multiLineDescription = recursiveComparisonConfiguration.multiLineDescription(STANDARD_REPRESENTATION); // THEN - assertThat(multiLineDescription).contains(format("- all actual null fields were ignored in the comparison%n")); + then(multiLineDescription).contains(format("- all actual null fields were ignored in the comparison%n")); } @Test @@ -60,7 +60,7 @@ void should_show_that_actual_empty_optional_fields_are_ignored() { // WHEN String multiLineDescription = recursiveComparisonConfiguration.multiLineDescription(STANDARD_REPRESENTATION); // THEN - assertThat(multiLineDescription).contains("- all actual empty optional fields were ignored in the comparison (including Optional, OptionalInt, OptionalLong and OptionalDouble)"); + then(multiLineDescription).contains("- all actual empty optional fields were ignored in the comparison (including Optional, OptionalInt, OptionalLong and OptionalDouble)"); } @Test @@ -70,7 +70,7 @@ void should_show_that_expected_null_fields_are_ignored() { // WHEN String multiLineDescription = recursiveComparisonConfiguration.multiLineDescription(STANDARD_REPRESENTATION); // THEN - assertThat(multiLineDescription).contains(format("- all expected null fields were ignored in the comparison%n")); + then(multiLineDescription).contains(format("- all expected null fields were ignored in the comparison%n")); } @Test @@ -80,7 +80,7 @@ void should_show_that_some_given_fields_are_ignored() { // WHEN String multiLineDescription = recursiveComparisonConfiguration.multiLineDescription(STANDARD_REPRESENTATION); // THEN - assertThat(multiLineDescription).contains(format("- the following fields were ignored in the comparison: foo, bar, foo.bar%n")); + then(multiLineDescription).contains(format("- the following fields were ignored in the comparison: foo, bar, foo.bar%n")); } @Test @@ -90,7 +90,7 @@ void should_show_the_regexes_used_to_ignore_fields() { // WHEN String multiLineDescription = recursiveComparisonConfiguration.multiLineDescription(STANDARD_REPRESENTATION); // THEN - assertThat(multiLineDescription).contains(format("- the fields matching the following regexes were ignored in the comparison: foo, bar, foo.bar%n")); + then(multiLineDescription).contains(format("- the fields matching the following regexes were ignored in the comparison: foo, bar, foo.bar%n")); } @Test @@ -100,7 +100,7 @@ void should_show_that_some_given_types_are_ignored() { // WHEN String multiLineDescription = recursiveComparisonConfiguration.multiLineDescription(STANDARD_REPRESENTATION); // THEN - assertThat(multiLineDescription).contains(format("- the following types were ignored in the comparison: java.util.UUID, java.time.ZonedDateTime%n")); + then(multiLineDescription).contains(format("- the following types were ignored in the comparison: java.util.UUID, java.time.ZonedDateTime%n")); } @Test @@ -110,7 +110,7 @@ void should_show_the_ignored_all_overridden_equals_methods_flag() { // WHEN String multiLineDescription = recursiveComparisonConfiguration.multiLineDescription(STANDARD_REPRESENTATION); // THEN - assertThat(multiLineDescription).contains("- no overridden equals methods were used in the comparison (except for java types)"); + then(multiLineDescription).contains("- no overridden equals methods were used in the comparison (except for java types)"); } @Test @@ -124,7 +124,7 @@ void should_show_the_ignored_all_overridden_equals_methods_flag_and_additional_o String multiLineDescription = recursiveComparisonConfiguration.multiLineDescription(STANDARD_REPRESENTATION); // THEN // @format:off - assertThat(multiLineDescription).contains(format("- overridden equals methods were used in the comparison except for:%n" + + then(multiLineDescription).contains(format("- overridden equals methods were used in the comparison except for:%n" + " - the following fields: foo, bar, foo.bar%n" + " - the following types: java.lang.String, com.google.common.collect.Multimap%n" + " - the types matching the following regexes: .*oo, .*ar%n")); @@ -140,7 +140,7 @@ void should_show_the_ignored_overridden_equals_methods_regexes() { String multiLineDescription = recursiveComparisonConfiguration.multiLineDescription(STANDARD_REPRESENTATION); // THEN // @format:off - assertThat(multiLineDescription).contains(format("- overridden equals methods were used in the comparison except for:%n" + + then(multiLineDescription).contains(format("- overridden equals methods were used in the comparison except for:%n" + " - the types matching the following regexes: foo, bar, foo.bar%n")); // @format:on } @@ -154,7 +154,7 @@ void should_show_the_ignored_overridden_equals_methods_types() { String multiLineDescription = recursiveComparisonConfiguration.multiLineDescription(STANDARD_REPRESENTATION); // THEN // @format:off - assertThat(multiLineDescription).contains(format("- overridden equals methods were used in the comparison except for:%n" + + then(multiLineDescription).contains(format("- overridden equals methods were used in the comparison except for:%n" + " - the following types: java.lang.String, com.google.common.collect.Multimap%n")); // @format:on } @@ -167,8 +167,8 @@ void should_not_show_specific_ignored_overridden_equals_methods_when_all_are_ign // WHEN String multiLineDescription = recursiveComparisonConfiguration.multiLineDescription(STANDARD_REPRESENTATION); // THEN - assertThat(multiLineDescription).contains("- no overridden equals methods were used in the comparison (except for java types)") - .doesNotContain("java.lang.String", "com.google.common.collect.Multimap"); + then(multiLineDescription).contains("- no overridden equals methods were used in the comparison (except for java types)") + .doesNotContain("java.lang.String", "com.google.common.collect.Multimap"); } @Test @@ -180,7 +180,7 @@ void should_show_the_ignored_overridden_equals_methods_fields() { String multiLineDescription = recursiveComparisonConfiguration.multiLineDescription(STANDARD_REPRESENTATION); // THEN // @format:off - assertThat(multiLineDescription).contains(format( + then(multiLineDescription).contains(format( "- overridden equals methods were used in the comparison except for:%n" + " - the following fields: foo, baz, foo.baz%n")); // @format:on @@ -191,7 +191,7 @@ void should_show_all_overridden_equals_methods_are_ignored_by_default() { // WHEN String multiLineDescription = recursiveComparisonConfiguration.multiLineDescription(STANDARD_REPRESENTATION); // THEN - assertThat(multiLineDescription).contains("- no overridden equals methods were used in the comparison (except for java types)"); + then(multiLineDescription).contains("- no overridden equals methods were used in the comparison (except for java types)"); } @Test @@ -201,7 +201,7 @@ void should_show_the_ignored_collection_order() { // WHEN String multiLineDescription = recursiveComparisonConfiguration.multiLineDescription(STANDARD_REPRESENTATION); // THEN - assertThat(multiLineDescription).contains(format("- collection order was ignored in all fields in the comparison%n")); + then(multiLineDescription).contains(format("- collection order was ignored in all fields in the comparison%n")); } @Test @@ -211,7 +211,7 @@ void should_show_the_ignored_collection_order_in_fields() { // WHEN String multiLineDescription = recursiveComparisonConfiguration.multiLineDescription(STANDARD_REPRESENTATION); // THEN - assertThat(multiLineDescription).contains(format("- collection order was ignored in the following fields in the comparison: foo, bar, foo.bar%n")); + then(multiLineDescription).contains(format("- collection order was ignored in the following fields in the comparison: foo, bar, foo.bar%n")); } @Test @@ -221,7 +221,7 @@ void should_show_the_ignored_collection_order_in_fields_matching_regexes() { // WHEN String multiLineDescription = recursiveComparisonConfiguration.multiLineDescription(STANDARD_REPRESENTATION); // THEN - assertThat(multiLineDescription).contains(format("- collection order was ignored in the fields matching the following regexes in the comparison: f.*, ba., foo.*%n")); + then(multiLineDescription).contains(format("- collection order was ignored in the fields matching the following regexes in the comparison: f.*, ba., foo.*%n")); } @Test @@ -233,12 +233,12 @@ void should_show_the_registered_comparator_by_types_and_the_default_ones() { // WHEN String multiLineDescription = recursiveComparisonConfiguration.multiLineDescription(STANDARD_REPRESENTATION); // THEN - assertThat(multiLineDescription).contains(format("- these types were compared with the following comparators:%n" + - " - java.lang.Double -> DoubleComparator[precision=1.0E-15]%n" + - " - java.lang.Float -> FloatComparator[precision=1.0E-6]%n" + - " - java.lang.Integer -> AbsValueComparator%n"), - " - java.lang.String -> ", - " - org.assertj.core.groups.Tuple -> AlwaysEqualComparator"); + then(multiLineDescription).contains(format("- these types were compared with the following comparators:%n" + + " - java.lang.Double -> DoubleComparator[precision=1.0E-15]%n" + + " - java.lang.Float -> FloatComparator[precision=1.0E-6]%n" + + " - java.lang.Integer -> AbsValueComparator%n"), + " - java.lang.String -> ", + " - org.assertj.core.groups.Tuple -> AlwaysEqualComparator"); } @Test @@ -250,10 +250,10 @@ void should_show_the_registered_comparator_for_specific_fields_alphabetically() // WHEN String multiLineDescription = recursiveComparisonConfiguration.multiLineDescription(STANDARD_REPRESENTATION); // THEN - assertThat(multiLineDescription).contains(format("- these fields were compared with the following comparators:%n" + - " - bar -> AlwaysDifferentComparator%n" + - " - foo -> AlwaysEqualComparator%n" + - " - height -> %%s %% %%%% %%d%n")); + then(multiLineDescription).contains(format("- these fields were compared with the following comparators:%n" + + " - bar -> AlwaysDifferentComparator%n" + + " - foo -> AlwaysEqualComparator%n" + + " - height -> %%s %% %%%% %%d%n")); } @Test @@ -264,9 +264,9 @@ void should_show_the_registered_bipredicate_comparator_for_specific_fields_alpha // WHEN String multiLineDescription = recursiveComparisonConfiguration.multiLineDescription(STANDARD_REPRESENTATION); // THEN - assertThat(multiLineDescription).containsSubsequence(format("- these fields were compared with the following comparators:%n"), - " - bar -> ", - " - foo -> "); + then(multiLineDescription).containsSubsequence(format("- these fields were compared with the following comparators:%n"), + " - bar -> ", + " - foo -> "); } @Test @@ -276,7 +276,7 @@ void should_show_when_strict_type_checking_is_used() { // WHEN String multiLineDescription = recursiveComparisonConfiguration.multiLineDescription(STANDARD_REPRESENTATION); // THEN - assertThat(multiLineDescription).contains(format("- actual and expected objects and their fields were considered different when of incompatible types (i.e. expected type does not extend actual's type) even if all their fields match, for example a Person instance will never match a PersonDto (call strictTypeChecking(false) to change that behavior).%n")); + then(multiLineDescription).contains(format("- actual and expected objects and their fields were considered different when of incompatible types (i.e. expected type does not extend actual's type) even if all their fields match, for example a Person instance will never match a PersonDto (call strictTypeChecking(false) to change that behavior).%n")); } @Test @@ -286,7 +286,7 @@ void should_show_when_lenient_type_checking_is_used() { // WHEN String multiLineDescription = recursiveComparisonConfiguration.multiLineDescription(STANDARD_REPRESENTATION); // THEN - assertThat(multiLineDescription).contains(format("- 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).%n")); + then(multiLineDescription).contains(format("- 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).%n")); } @Test @@ -295,6 +295,7 @@ void should_show_a_complete_multiline_description() { recursiveComparisonConfiguration.setIgnoreAllActualNullFields(true); recursiveComparisonConfiguration.setIgnoreAllActualEmptyOptionalFields(true); recursiveComparisonConfiguration.setIgnoreAllExpectedNullFields(true); + recursiveComparisonConfiguration.compareOnlyFields("name", "address.number"); recursiveComparisonConfiguration.ignoreFields("foo", "bar", "foo.bar"); recursiveComparisonConfiguration.ignoreFieldsMatchingRegexes("f.*", ".ba.", "..b%sr.."); recursiveComparisonConfiguration.ignoreFieldsOfTypes(UUID.class, ZonedDateTime.class); @@ -313,10 +314,11 @@ void should_show_a_complete_multiline_description() { String multiLineDescription = recursiveComparisonConfiguration.multiLineDescription(STANDARD_REPRESENTATION); // THEN // @format:off - assertThat(multiLineDescription).isEqualTo(format( + then(multiLineDescription).isEqualTo(format( "- all actual null fields were ignored in the comparison%n" + "- all actual empty optional fields were ignored in the comparison (including Optional, OptionalInt, OptionalLong and OptionalDouble)%n" + "- all expected null fields were ignored in the comparison%n" + + "- the comparison was performed on the following fields: name, address.number%n" + "- the following fields were ignored in the comparison: foo, bar, foo.bar%n" + "- the fields matching the following regexes were ignored in the comparison: f.*, .ba., ..b%%sr..%n"+ "- the following types were ignored in the comparison: java.util.UUID, java.time.ZonedDateTime%n" + @@ -331,6 +333,7 @@ void should_show_a_complete_multiline_description() { " - java.lang.Double -> DoubleComparator[precision=1.0E-15]%n" + " - java.lang.Float -> FloatComparator[precision=1.0E-6]%n" + " - java.lang.Integer -> AbsValueComparator%n" + + " - java.nio.file.Path -> lexicographic comparator (Path natural order)%n" + " - org.assertj.core.groups.Tuple -> AlwaysEqualComparator%n" + "- these fields were compared with the following comparators:%n" + " - bar.baz -> AlwaysDifferentComparator%n" + @@ -340,6 +343,16 @@ void should_show_a_complete_multiline_description() { // @format:on } + @Test + void should_show_that_comparison_is_performed_on_given_fields() { + // GIVEN + recursiveComparisonConfiguration.compareOnlyFields("foo", "bar", "foo.bar"); + // WHEN + String multiLineDescription = recursiveComparisonConfiguration.multiLineDescription(STANDARD_REPRESENTATION); + // THEN + then(multiLineDescription).contains(format("- the comparison was performed on the following fields: foo, bar, foo.bar%n")); + } + // just to test the description does not fail when given a comparator with various String.format reserved flags private class PercentageComparator implements Comparator { diff --git a/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonConfiguration_shouldIgnoreFields_Test.java b/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonConfiguration_shouldIgnoreFields_Test.java index d02d02d7a3d..77ae47e34fd 100644 --- a/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonConfiguration_shouldIgnoreFields_Test.java +++ b/src/test/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonConfiguration_shouldIgnoreFields_Test.java @@ -13,7 +13,7 @@ package org.assertj.core.api.recursive.comparison; import static java.util.UUID.randomUUID; -import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.BDDAssertions.then; import static org.assertj.core.api.recursive.comparison.DualValueUtil.dualValueWithPath; import static org.assertj.core.api.recursive.comparison.DualValueUtil.randomPath; import static org.assertj.core.util.Lists.list; @@ -53,7 +53,7 @@ void should_register_fields_path_to_ignore_without_duplicates() { // WHEN Set fields = recursiveComparisonConfiguration.getIgnoredFields(); // THEN - assertThat(fields).containsExactlyInAnyOrder("foo", "bar", "foo.bar"); + then(fields).containsExactlyInAnyOrder("foo", "bar", "foo.bar"); } @ParameterizedTest(name = "{0} should be ignored") @@ -64,7 +64,7 @@ void should_ignore_actual_null_fields(DualValue dualValue) { // WHEN boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue); // THEN - assertThat(ignored).as("%s should be ignored", dualValue).isTrue(); + then(ignored).as("%s should be ignored", dualValue).isTrue(); } private static Stream should_ignore_actual_null_fields() { @@ -82,7 +82,7 @@ void should_ignore_actual_optional_empty_fields(DualValue dualValue) { // WHEN boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue); // THEN - assertThat(ignored).as("%s should be ignored", dualValue).isTrue(); + then(ignored).as("%s should be ignored", dualValue).isTrue(); } private static Stream should_ignore_actual_optional_empty_fields() { @@ -101,7 +101,7 @@ void should_ignore_expected_null_fields(DualValue dualValue) { // WHEN boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue); // THEN - assertThat(ignored).as("%s should be ignored", dualValue).isTrue(); + then(ignored).as("%s should be ignored", dualValue).isTrue(); } private static Stream should_ignore_expected_null_fields() { @@ -119,7 +119,7 @@ void should_ignore_specified_fields(DualValue dualValue, List ignoredFie // WHEN boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue); // THEN - assertThat(ignored).as("%s should be ignored with these ignored fields %s", dualValue, ignoredFields).isTrue(); + then(ignored).as("%s should be ignored with these ignored fields %s", dualValue, ignoredFields).isTrue(); } private static Stream should_ignore_specified_fields() { @@ -138,8 +138,8 @@ void ignoring_fields_with_regex_does_not_replace_previous_regexes() { recursiveComparisonConfiguration.ignoreFieldsMatchingRegexes("foo"); recursiveComparisonConfiguration.ignoreFieldsMatchingRegexes("bar", "baz"); // THEN - assertThat(recursiveComparisonConfiguration.getIgnoredFieldsRegexes()).extracting(Pattern::pattern) - .containsExactlyInAnyOrder("foo", "bar", "baz"); + then(recursiveComparisonConfiguration.getIgnoredFieldsRegexes()).extracting(Pattern::pattern) + .containsExactlyInAnyOrder("foo", "bar", "baz"); } @ParameterizedTest(name = "{0} should be ignored with these regexes {1}") @@ -150,7 +150,7 @@ void should_ignore_fields_matching_given_regexes(DualValue dualValue, List should_ignore_fields_matching_given_regexes() { @@ -176,7 +176,7 @@ void should_ignore_fields(DualValue dualValue) { // WHEN boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue); // THEN - assertThat(ignored).as("%s should be ignored", dualValue).isTrue(); + then(ignored).as("%s should be ignored", dualValue).isTrue(); } private static Stream should_ignore_fields() { @@ -193,8 +193,8 @@ void ignoring_fields_for_types_does_not_replace_previous_ignored_types() { recursiveComparisonConfiguration.ignoreFieldsOfTypes(UUID.class); recursiveComparisonConfiguration.ignoreFieldsOfTypes(ZonedDateTime.class, String.class); // THEN - assertThat(recursiveComparisonConfiguration.getIgnoredTypes()).containsExactlyInAnyOrder(UUID.class, ZonedDateTime.class, - String.class); + then(recursiveComparisonConfiguration.getIgnoredTypes()).containsExactlyInAnyOrder(UUID.class, ZonedDateTime.class, + String.class); } @ParameterizedTest(name = "{0} should be ignored with these ignored types {1}") @@ -205,8 +205,8 @@ void should_ignore_fields_for_specified_types(DualValue dualValue, List // WHEN boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue); // THEN - assertThat(ignored).as("%s should be ignored with these ignored types %s", dualValue, ignoredTypes) - .isTrue(); + then(ignored).as("%s should be ignored with these ignored types %s", dualValue, ignoredTypes) + .isTrue(); } private static Stream should_ignore_fields_for_specified_types() { @@ -222,7 +222,7 @@ void should_return_false_if_the_field_type_is_not_ignored() { // WHEN boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue); // THEN - assertThat(ignored).isFalse(); + then(ignored).isFalse(); } @Test @@ -233,7 +233,7 @@ void should_be_able_to_ignore_boolean() { // WHEN boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue); // THEN - assertThat(ignored).isTrue(); + then(ignored).isTrue(); } @Test @@ -244,7 +244,7 @@ void should_be_able_to_ignore_byte() { // WHEN boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue); // THEN - assertThat(ignored).isTrue(); + then(ignored).isTrue(); } @Test @@ -255,7 +255,7 @@ void should_be_able_to_ignore_char() { // WHEN boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue); // THEN - assertThat(ignored).isTrue(); + then(ignored).isTrue(); } @Test @@ -266,7 +266,7 @@ void should_be_able_to_ignore_short() { // WHEN boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue); // THEN - assertThat(ignored).isTrue(); + then(ignored).isTrue(); } @Test @@ -277,7 +277,7 @@ void should_be_able_to_ignore_int() { // WHEN boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue); // THEN - assertThat(ignored).isTrue(); + then(ignored).isTrue(); } @Test @@ -288,7 +288,7 @@ void should_be_able_to_ignore_float() { // WHEN boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue); // THEN - assertThat(ignored).isTrue(); + then(ignored).isTrue(); } @Test @@ -299,7 +299,7 @@ void should_be_able_to_ignore_double() { // WHEN boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue); // THEN - assertThat(ignored).isTrue(); + then(ignored).isTrue(); } @ParameterizedTest(name = "{0} should be ignored by specifying to ignore {1}") @@ -311,7 +311,7 @@ void should_be_able_to_ignore_primitive_field_by_specifying_their_wrapper_type(O // WHEN boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue); // THEN - assertThat(ignored).isTrue(); + then(ignored).isTrue(); } private static Stream should_be_able_to_ignore_primitive_field_by_specifying_their_wrapper_type() { @@ -332,7 +332,7 @@ void should_return_false_if_the_field_type_is_subtype_of_an_ignored_type() { // WHEN boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue); // THEN - assertThat(ignored).isFalse(); + then(ignored).isFalse(); } @Test @@ -344,7 +344,7 @@ void should_not_ignore_actual_null_fields_for_specified_types_if_strictTypeCheck // WHEN boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue); // THEN - assertThat(ignored).isFalse(); + then(ignored).isFalse(); } @Test @@ -356,7 +356,43 @@ void should_ignore_actual_null_fields_for_specified_types_if_strictTypeChecking_ // WHEN boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue); // THEN - assertThat(ignored).isTrue(); + then(ignored).isTrue(); + } + + @ParameterizedTest(name = "{0} should be compared: {1}") + @MethodSource + void should_honor_compared_fields(DualValue dualValue, boolean toCompare) { + // GIVEN + recursiveComparisonConfiguration.compareOnlyFields("number", "name", "address.street.geolocation", "person.children"); + // WHEN + boolean shoudlBeCompared = !recursiveComparisonConfiguration.shouldIgnore(dualValue); + // THEN + then(shoudlBeCompared).as("%s should be %s", dualValue, toCompare ? "compared" : "ignored").isEqualTo(toCompare); + } + + private static Stream should_honor_compared_fields() { + return Stream.of(arguments(dualValueWithPath("name"), true), + arguments(dualValueWithPath("number"), true), + arguments(dualValueWithPath("surname"), false), + arguments(dualValueWithPath("name", "first"), true), + arguments(dualValueWithPath("name", "last"), true), + arguments(dualValueWithPath("address"), true), + arguments(dualValueWithPath("address", "street"), true), + arguments(dualValueWithPath("address", "street", "geolocation"), true), + arguments(dualValueWithPath("street"), false), + arguments(dualValueWithPath("street", "geolocation"), false), + arguments(dualValueWithPath("person", "children", "[0]"), true), + arguments(dualValueWithPath("address", "number"), false)); + } + + @Test + void should_treat_empty_compared_fields_as_not_restricting_comparison() { + // GIVEN + recursiveComparisonConfiguration.compareOnlyFields(); + // WHEN + boolean shoudlBeCompared = !recursiveComparisonConfiguration.shouldIgnore(dualValueWithPath("name")); + // THEN + then(shoudlBeCompared).isTrue(); } static DualValue dualValue(Object value1, Object value2) { diff --git a/src/test/java/org/assertj/core/api/zoneddatetime/ZonedDateTimeAssert_isEqualToIgnoringHours_Test.java b/src/test/java/org/assertj/core/api/zoneddatetime/ZonedDateTimeAssert_isEqualToIgnoringHours_Test.java index 726332fd3d1..f72c78980aa 100644 --- a/src/test/java/org/assertj/core/api/zoneddatetime/ZonedDateTimeAssert_isEqualToIgnoringHours_Test.java +++ b/src/test/java/org/assertj/core/api/zoneddatetime/ZonedDateTimeAssert_isEqualToIgnoringHours_Test.java @@ -52,7 +52,7 @@ void should_pass_if_actual_is_equal_to_other_ignoring_hours_in_different_timezon // THEN assertThat(assertionError).hasMessage(format("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2013-06-10T00:00Z (java.time.ZonedDateTime)%n" + "to have same year, month and day as:%n" + " 2013-06-09T22:00Z (java.time.ZonedDateTime)%n" + @@ -64,7 +64,7 @@ void should_fail_if_actual_is_not_equal_to_given_datetime_with_hours_ignored() { // WHEN AssertionError assertionError = expectAssertionError(() -> assertThat(refDatetime).isEqualToIgnoringHours(refDatetime.minusHours(1))); // THEN - then(assertionError).hasMessage(format("%nExpecting:%n 2000-01-02T00:00Z (java.time.ZonedDateTime)%nto have same year, month and day as:%n 2000-01-01T23:00Z (java.time.ZonedDateTime)%nbut had not.")); + then(assertionError).hasMessage(format("%nExpecting actual:%n 2000-01-02T00:00Z (java.time.ZonedDateTime)%nto have same year, month and day as:%n 2000-01-01T23:00Z (java.time.ZonedDateTime)%nbut had not.")); } @Test @@ -73,7 +73,7 @@ void should_fail_as_hours_fields_are_different_even_if_time_difference_is_less_t AssertionError assertionError = expectAssertionError(() -> assertThat(refDatetime).isEqualToIgnoringHours(refDatetime.minusNanos(1))); // THEN then(assertionError).hasMessage(format( - "%nExpecting:%n 2000-01-02T00:00Z (java.time.ZonedDateTime)%nto have same year, month and day as:%n 2000-01-01T23:59:59.999999999Z (java.time.ZonedDateTime)%nbut had not.")); + "%nExpecting actual:%n 2000-01-02T00:00Z (java.time.ZonedDateTime)%nto have same year, month and day as:%n 2000-01-01T23:59:59.999999999Z (java.time.ZonedDateTime)%nbut had not.")); } @Test diff --git a/src/test/java/org/assertj/core/api/zoneddatetime/ZonedDateTimeAssert_isEqualToIgnoringMinutes_Test.java b/src/test/java/org/assertj/core/api/zoneddatetime/ZonedDateTimeAssert_isEqualToIgnoringMinutes_Test.java index 19f2d2393b3..44466719247 100644 --- a/src/test/java/org/assertj/core/api/zoneddatetime/ZonedDateTimeAssert_isEqualToIgnoringMinutes_Test.java +++ b/src/test/java/org/assertj/core/api/zoneddatetime/ZonedDateTimeAssert_isEqualToIgnoringMinutes_Test.java @@ -40,7 +40,7 @@ void should_fail_if_actual_is_not_equal_to_given_datetime_with_minute_ignored() AssertionError assertionError = expectAssertionError(() -> assertThat(refDatetime).isEqualToIgnoringMinutes(refDatetime.minusMinutes(1))); // THEN then(assertionError).hasMessage(format("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2000-01-01T23:00Z (java.time.ZonedDateTime)%n" + "to have same year, month, day and hour as:%n" + " 2000-01-01T22:59Z (java.time.ZonedDateTime)%n" + @@ -53,7 +53,7 @@ void should_fail_as_minutes_fields_are_different_even_if_time_difference_is_less AssertionError assertionError = expectAssertionError(() -> assertThat(refDatetime).isEqualToIgnoringMinutes(refDatetime.minusNanos(1))); // THEN then(assertionError).hasMessage(format("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2000-01-01T23:00Z (java.time.ZonedDateTime)%n" + "to have same year, month, day and hour as:%n" + " 2000-01-01T22:59:59.999999999Z (java.time.ZonedDateTime)%n" + diff --git a/src/test/java/org/assertj/core/api/zoneddatetime/ZonedDateTimeAssert_isEqualToIgnoringNanoseconds_Test.java b/src/test/java/org/assertj/core/api/zoneddatetime/ZonedDateTimeAssert_isEqualToIgnoringNanoseconds_Test.java index f32cb978000..f8c62b0b5e6 100644 --- a/src/test/java/org/assertj/core/api/zoneddatetime/ZonedDateTimeAssert_isEqualToIgnoringNanoseconds_Test.java +++ b/src/test/java/org/assertj/core/api/zoneddatetime/ZonedDateTimeAssert_isEqualToIgnoringNanoseconds_Test.java @@ -41,7 +41,7 @@ void should_fail_if_actual_is_not_equal_to_given_datetime_with_nanoseconds_ignor AssertionError assertionError = expectAssertionError(() -> assertThat(refDatetime).isEqualToIgnoringNanos(refDatetime.plusSeconds(1))); // THEN then(assertionError).hasMessage(format("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2000-01-01T00:00:01Z (java.time.ZonedDateTime)%n" + "to have same year, month, day, hour, minute and second as:%n" + " 2000-01-01T00:00:02Z (java.time.ZonedDateTime)%n" + @@ -54,7 +54,7 @@ void should_fail_as_seconds_fields_are_different_even_if_time_difference_is_less AssertionError assertionError = expectAssertionError(() -> assertThat(refDatetime).isEqualToIgnoringNanos(refDatetime.minusNanos(1))); // THEN then(assertionError).hasMessage(format("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2000-01-01T00:00:01Z (java.time.ZonedDateTime)%n" + "to have same year, month, day, hour, minute and second as:%n" + " 2000-01-01T00:00:00.999999999Z (java.time.ZonedDateTime)%n" + diff --git a/src/test/java/org/assertj/core/api/zoneddatetime/ZonedDateTimeAssert_isEqualToIgnoringSeconds_Test.java b/src/test/java/org/assertj/core/api/zoneddatetime/ZonedDateTimeAssert_isEqualToIgnoringSeconds_Test.java index 92df7931bb5..68f20c169ec 100644 --- a/src/test/java/org/assertj/core/api/zoneddatetime/ZonedDateTimeAssert_isEqualToIgnoringSeconds_Test.java +++ b/src/test/java/org/assertj/core/api/zoneddatetime/ZonedDateTimeAssert_isEqualToIgnoringSeconds_Test.java @@ -40,7 +40,7 @@ void should_fail_if_actual_is_not_equal_to_given_datetime_with_second_ignored() AssertionError assertionError = expectAssertionError(() -> assertThat(refDatetime).isEqualToIgnoringSeconds(refDatetime.plusMinutes(1))); // THEN then(assertionError).hasMessage(format("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2000-01-01T23:51Z (java.time.ZonedDateTime)%n" + "to have same year, month, day, hour and minute as:%n" + " 2000-01-01T23:52Z (java.time.ZonedDateTime)%n" + @@ -53,7 +53,7 @@ void should_fail_as_seconds_fields_are_different_even_if_time_difference_is_less AssertionError assertionError = expectAssertionError(() -> assertThat(refDatetime).isEqualToIgnoringSeconds(refDatetime.minusNanos(1))); // THEN then(assertionError).hasMessage(format("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2000-01-01T23:51Z (java.time.ZonedDateTime)%n" + "to have same year, month, day, hour and minute as:%n" + " 2000-01-01T23:50:59.999999999Z (java.time.ZonedDateTime)%n" + diff --git a/src/test/java/org/assertj/core/api/zoneddatetime/ZonedDateTimeAssert_isIn_errors_Test.java b/src/test/java/org/assertj/core/api/zoneddatetime/ZonedDateTimeAssert_isIn_errors_Test.java index a84ca308380..134bd8ad1c6 100644 --- a/src/test/java/org/assertj/core/api/zoneddatetime/ZonedDateTimeAssert_isIn_errors_Test.java +++ b/src/test/java/org/assertj/core/api/zoneddatetime/ZonedDateTimeAssert_isIn_errors_Test.java @@ -44,7 +44,7 @@ void test_isIn_assertion_error_message() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> { assertThat(ZonedDateTime.of(2000, 1, 5, 3, 0, 5, 0, UTC)).isIn(ZonedDateTime.of(2012, 1, 1, 3, 3, 3, 0, UTC) .toString()); - }).withMessage(format("%nExpecting:%n 2000-01-05T03:00:05Z (java.time.ZonedDateTime)%nto be in:%n [2012-01-01T03:03:03Z (java.time.ZonedDateTime)]%n")); + }).withMessage(format("%nExpecting actual:%n 2000-01-05T03:00:05Z (java.time.ZonedDateTime)%nto be in:%n [2012-01-01T03:03:03Z (java.time.ZonedDateTime)]%n")); } @Test diff --git a/src/test/java/org/assertj/core/api/zoneddatetime/ZonedDateTimeAssert_isNotIn_errors_Test.java b/src/test/java/org/assertj/core/api/zoneddatetime/ZonedDateTimeAssert_isNotIn_errors_Test.java index 2fe1750cc24..785f1df24ff 100644 --- a/src/test/java/org/assertj/core/api/zoneddatetime/ZonedDateTimeAssert_isNotIn_errors_Test.java +++ b/src/test/java/org/assertj/core/api/zoneddatetime/ZonedDateTimeAssert_isNotIn_errors_Test.java @@ -43,7 +43,7 @@ void test_isNotIn_assertion() { void test_isNotIn_assertion_error_message() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(ZonedDateTime.of(2000, 1, 5, 3, 0, 5, 0, UTC)).isNotIn(ZonedDateTime.of(2000, 1, 5, 3, 0, 5, 0, UTC).toString(), ZonedDateTime.of(2012, 1, 1, 3, 3, 3, 0, UTC).toString())) - .withMessage(format("%nExpecting:%n 2000-01-05T03:00:05Z (java.time.ZonedDateTime)%nnot to be in:%n" + .withMessage(format("%nExpecting actual:%n 2000-01-05T03:00:05Z (java.time.ZonedDateTime)%nnot to be in:%n" + " [2000-01-05T03:00:05Z (java.time.ZonedDateTime),%n 2012-01-01T03:03:03Z (java.time.ZonedDateTime)]%n")); } diff --git a/src/test/java/org/assertj/core/condition/AllOf_conditionDescriptionWithStatus_Test.java b/src/test/java/org/assertj/core/condition/AllOf_conditionDescriptionWithStatus_Test.java new file mode 100644 index 00000000000..9d88860a15c --- /dev/null +++ b/src/test/java/org/assertj/core/condition/AllOf_conditionDescriptionWithStatus_Test.java @@ -0,0 +1,60 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.condition; + +import static java.lang.String.format; +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.condition.AllOf.allOf; + +import org.assertj.core.api.Condition; +import org.assertj.core.api.TestCondition; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class AllOf_conditionDescriptionWithStatus_Test { + + private TestCondition condition1; + private TestCondition condition2; + private Condition allOf; + + @BeforeEach + public void setUp() { + condition1 = new TestCondition<>(); + condition2 = new TestCondition<>(); + allOf = allOf(condition1, condition2); + } + + @Test + void should_return_description_with_all_succeeding_conditions() { + // GIVEN + condition1.shouldMatch(true); + condition2.shouldMatch(true); + // WHEN/THEN + then(allOf.conditionDescriptionWithStatus("Yoda")).hasToString(format("[✓] all of:[%n" + + " [✓] TestCondition,%n" + + " [✓] TestCondition%n" + + "]")); + } + + @Test + void should_return_description_with_failing_and_succeeding_conditions() { + // GIVEN + condition1.shouldMatch(true); + condition2.shouldMatch(false); + // WHEN/THEN + then(allOf.conditionDescriptionWithStatus("Yoda")).hasToString(format("[✗] all of:[%n" + + " [✓] TestCondition,%n" + + " [✗] TestCondition%n" + + "]")); + } +} diff --git a/src/test/java/org/assertj/core/condition/ConditionBuiltWithPredicateTest.java b/src/test/java/org/assertj/core/condition/ConditionBuiltWithPredicateTest.java index 90939b87e5d..bbac7351e5b 100644 --- a/src/test/java/org/assertj/core/condition/ConditionBuiltWithPredicateTest.java +++ b/src/test/java/org/assertj/core/condition/ConditionBuiltWithPredicateTest.java @@ -66,7 +66,7 @@ void doesNotHave_condition_should_be_met() { void should_fail_if_condition_is_not_met() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat("Vader").is(jedi)) .withMessage(format("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " \"Vader\"%n" + "to be a jedi")); } diff --git a/src/test/java/org/assertj/core/condition/Condition_conditionDescriptionWithStatus_Test.java b/src/test/java/org/assertj/core/condition/Condition_conditionDescriptionWithStatus_Test.java new file mode 100644 index 00000000000..41c8066fdbf --- /dev/null +++ b/src/test/java/org/assertj/core/condition/Condition_conditionDescriptionWithStatus_Test.java @@ -0,0 +1,45 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.condition; + +import static org.assertj.core.api.BDDAssertions.then; + +import org.assertj.core.api.Condition; +import org.assertj.core.description.Description; +import org.junit.jupiter.api.Test; + +class Condition_conditionDescriptionWithStatus_Test { + + private Condition jediCondition = new JediCondition(); + + @Test + void should_return_description_with_success_status() { + // GIVEN + String yoda = "Yoda"; + // WHEN + Description conditionDescriptionWithStatus = jediCondition.conditionDescriptionWithStatus(yoda); + // THEN + then(conditionDescriptionWithStatus).hasToString("[✓] Jedi"); + } + + @Test + void should_return_description_with_failed_status() { + // GIVEN + String vader = "Vader"; + // WHEN + Description conditionDescriptionWithStatus = jediCondition.conditionDescriptionWithStatus(vader); + // THEN + then(conditionDescriptionWithStatus).hasToString("[✗] Jedi"); + } + +} diff --git a/src/test/java/org/assertj/core/condition/MappedConditionTest.java b/src/test/java/org/assertj/core/condition/MappedConditionTest.java new file mode 100644 index 00000000000..533b27d9157 --- /dev/null +++ b/src/test/java/org/assertj/core/condition/MappedConditionTest.java @@ -0,0 +1,126 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.condition; + +import static java.lang.String.format; +import static java.lang.System.lineSeparator; +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.api.BDDAssertions.thenNullPointerException; +import static org.assertj.core.condition.MappedCondition.mappedCondition; + +import java.util.Optional; + +import org.assertj.core.api.Condition; +import org.junit.jupiter.api.Test; + +class MappedConditionTest { + + private static final String INNER_CONDITION_DESCRIPTION = "isString and BAR"; + + private static final String BAR = "bar"; + + private static final String FOO = "foo"; + + private final static Condition isBarString = new Condition<>(s -> BAR.equals(s), INNER_CONDITION_DESCRIPTION); + + private final static String BAR_CONDITION_DESCRIPTION = format("mapped%n" + + " using: ::toString%n" + + " from: " + BAR + "%n" + + " to: " + BAR + "%n" + + " then checked:%n" + + " " + INNER_CONDITION_DESCRIPTION); + + private final static String BAR_CONDITION_DESCRIPTION_PLAIN = format("mapped%n" + + " from: " + BAR + "%n" + + " to: " + BAR + "%n" + + " then checked:%n" + + " " + INNER_CONDITION_DESCRIPTION); + + private final static String FOO_CONDITION_DESCRIPTION = format("mapped%n" + + " using: ::toString%n" + + " from: " + FOO + "%n" + + " to: " + FOO + "%n" + + " then checked:%n" + + " " + INNER_CONDITION_DESCRIPTION); + + @Test + void mappedCondition_withDescription_works() { + // WHEN + Condition mappedCondition = mappedCondition(StringBuilder::toString, isBarString, "%stoString", "::"); + // THEN + then(mappedCondition.matches(new StringBuilder(BAR))).isTrue(); + then(mappedCondition).hasToString(BAR_CONDITION_DESCRIPTION); + then(mappedCondition.matches(new StringBuilder(FOO))).isFalse(); + then(mappedCondition).hasToString(FOO_CONDITION_DESCRIPTION); + } + + @Test + void mappedCondition_withoutDescription_works() { + // WHEN + Condition mappedCondition = mappedCondition(StringBuilder::toString, isBarString); + // THEN + then(mappedCondition.matches(new StringBuilder(BAR))).isTrue(); + then(mappedCondition).hasToString(BAR_CONDITION_DESCRIPTION_PLAIN); + } + + @Test + void mappedCondition_with_description_and_null_condition_should_throw_NPE() { + // GIVEN + Condition nullCondition = null; + // WHEN/THEN + thenNullPointerException().isThrownBy(() -> mappedCondition(StringBuilder::toString, nullCondition, "::toString")) + .withMessage("The given condition should not be null"); + } + + @Test + void mappedCondition_with_description_and_null_mapping_function_should_throw_NPE() { + thenNullPointerException().isThrownBy(() -> mappedCondition(null, isBarString, "::toString")) + .withMessage("The given mapping function should not be null"); + } + + @Test + void mappedCondition_without_description_and_null_condition_should_throw_NPE() { + // GIVEN + Condition nullCondition = null; + // WHEN/THEN + thenNullPointerException().isThrownBy(() -> mappedCondition(StringBuilder::toString, nullCondition)) + .withMessage("The given condition should not be null"); + } + + @Test + void mappedCondition_without_description_and_null_mapping_function_should_throw_NPE() { + thenNullPointerException().isThrownBy(() -> mappedCondition(null, isBarString)) + .withMessage("The given mapping function should not be null"); + } + + @Test + void mappedCondition_with_null_description_and_should_throw_NPE() { + // GIVEN + String nullDescription = null; + // WHEN/THEN + thenNullPointerException().isThrownBy(() -> mappedCondition(StringBuilder::toString, isBarString, nullDescription)) + .withMessage("The given mappingDescription should not be null"); + } + + @Test + void example() { + // GIVEN + Condition hasLineSeparator = new Condition<>(text -> text.contains(lineSeparator()), "has lineSeparator"); + Optional optionalString = Optional.of("a" + lineSeparator()); + // WHEN + Condition> mappedCondition = mappedCondition(Optional::get, hasLineSeparator); + boolean matches = mappedCondition.matches(optionalString); + // THEN + then(matches).isTrue(); + } +} diff --git a/src/test/java/org/assertj/core/condition/MatchPredicateTest.java b/src/test/java/org/assertj/core/condition/MatchPredicateTest.java index a9087d75074..f68167f5214 100644 --- a/src/test/java/org/assertj/core/condition/MatchPredicateTest.java +++ b/src/test/java/org/assertj/core/condition/MatchPredicateTest.java @@ -43,7 +43,7 @@ void should_match_predicate_with_description_() { void should_fail_if_object_does_not_match_predicate() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(yoda).matches(x -> x.lightSaberColor.equals("Red"))) .withMessage(format("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " Yoda the Jedi%n" + "to match given predicate.%n" + "%n" + @@ -54,7 +54,7 @@ void should_fail_if_object_does_not_match_predicate() { + "will give an error message looking like:%n" + "%n" + - "Expecting:%n" + + "Expecting actual:%n" + " player%n" + "to match 'is rookie' predicate")); } @@ -65,7 +65,7 @@ void should_fail_if_object_does_not_match_predicate_and_use_predicate_descriptio .matches(x -> x.lightSaberColor.equals("Red"), "has red light saber")) .withMessage(format("[check light saber] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " Yoda the Jedi%n" + "to match 'has red light saber' predicate.")); } diff --git a/src/test/java/org/assertj/core/condition/Multiple_combined_conditions_Test.java b/src/test/java/org/assertj/core/condition/Multiple_combined_conditions_Test.java index a990bff6f15..fc6700d3017 100644 --- a/src/test/java/org/assertj/core/condition/Multiple_combined_conditions_Test.java +++ b/src/test/java/org/assertj/core/condition/Multiple_combined_conditions_Test.java @@ -56,21 +56,20 @@ void should_report_error_message_with_all_conditions_described() { // WHEN AssertionError assertionError = expectAssertionError(code); // THEN - assertThat(assertionError).hasMessage(format("%n" + - "Expecting:%n" + - " \"Gandalf\"%n" + - "to have:%n" + - " any of:[%n" + - " contains i,%n" + - " all of:[%n" + - " contains o,%n" + - " any of:[%n" + - " contains a,%n" + - " contains b,%n" + - " contains c%n" + - " ]%n" + - " ]%n" + - "]")); + then(assertionError).hasMessage(format("%n" + + "Expecting actual:%n" + + " \"Gandalf\"%n" + + "to have any of:[%n" + + " contains i,%n" + + " all of:[%n" + + " contains o,%n" + + " any of:[%n" + + " contains a,%n" + + " contains b,%n" + + " contains c%n" + + " ]%n" + + " ]%n" + + "]")); } @Test @@ -84,21 +83,20 @@ void should_report_error_message_with_all_conditions_in_list_described() { // WHEN AssertionError assertionError = expectAssertionError(code); // THEN - assertThat(assertionError).hasMessage(format("%n" + - "Expecting:%n" + - " \"Gandalf\"%n" + - "to have:%n" + - " any of:[%n" + - " contains i,%n" + - " all of:[%n" + - " contains o,%n" + - " any of:[%n" + - " contains a,%n" + - " contains b,%n" + - " contains c%n" + - " ]%n" + - " ]%n" + - "]")); + then(assertionError).hasMessage(format("%n" + + "Expecting actual:%n" + + " \"Gandalf\"%n" + + "to have any of:[%n" + + " contains i,%n" + + " all of:[%n" + + " contains o,%n" + + " any of:[%n" + + " contains a,%n" + + " contains b,%n" + + " contains c%n" + + " ]%n" + + " ]%n" + + "]")); } private static Condition contains(String s) { diff --git a/src/test/java/org/assertj/core/condition/VerboseConditionTest.java b/src/test/java/org/assertj/core/condition/VerboseConditionTest.java new file mode 100644 index 00000000000..d17174241e9 --- /dev/null +++ b/src/test/java/org/assertj/core/condition/VerboseConditionTest.java @@ -0,0 +1,80 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.condition; + +import static java.lang.String.format; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatNullPointerException; +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.condition.VerboseCondition.verboseCondition; +import static org.assertj.core.util.AssertionsUtil.expectAssertionError; + +import org.assertj.core.api.Condition; +import org.junit.jupiter.api.Test; + +class VerboseConditionTest { + + private static final Condition VERBOSE_CONDITION = verboseCondition(actual -> actual.length() < 4, + "shorter than 4", + s -> format(" but length was %s", s.length(), s)); + + @Test + public void should_succeed_and_display_description_without_actual() { + assertThat(VERBOSE_CONDITION.matches("foo")).isTrue(); + assertThat(VERBOSE_CONDITION).hasToString("shorter than 4"); + } + + @Test + public void should_fail_and_display_actual_description_as_per_transformation_function_with_isCondition() { + // WHEN + AssertionError assertionError = expectAssertionError(() -> assertThat("foooo").is(VERBOSE_CONDITION)); + // THEN + then(assertionError).hasMessage(format("%nExpecting actual:%n" + + " \"foooo\"%n" + + "to be shorter than 4 but length was 5")); + } + + @Test + public void should_fail_and_display_actual_description_as_per_transformation_function_with_hasCondition() { + // GIVEN + Condition shortLength = verboseCondition(actual -> actual.length() < 4, + "length shorter than 4", + s -> format(" but length was %s", s.length(), s)); + // WHEN + AssertionError assertionError = expectAssertionError(() -> assertThat("foooo").has(shortLength)); + // THEN + then(assertionError).hasMessage(format("%nExpecting actual:%n" + + " \"foooo\"%n" + + "to have length shorter than 4 but length was 5")); + } + + @Test + public void multiple_matches_should_not_change_description() { + VERBOSE_CONDITION.matches("foooo"); + assertThat(VERBOSE_CONDITION).hasToString("shorter than 4 but length was 5"); + VERBOSE_CONDITION.matches("foooo"); + VERBOSE_CONDITION.matches("foooo"); + assertThat(VERBOSE_CONDITION).hasToString("shorter than 4 but length was 5"); + } + + @Test + public void should_throw_NullPointerException_if_condition_predicate_is_null() { + assertThatNullPointerException().isThrownBy(() -> verboseCondition(null, "description", t -> "")); + } + + @Test + public void should_throw_NullPointerException_if_objectUnderTestDescriptor_parameter_is_null() { + assertThatNullPointerException().isThrownBy(() -> verboseCondition(s -> s != null, "shorter than 4", null)); + } + +} diff --git a/src/test/java/org/assertj/core/configuration/Configuration_apply_Test.java b/src/test/java/org/assertj/core/configuration/Configuration_apply_Test.java index d95070642bd..99d28056f7d 100644 --- a/src/test/java/org/assertj/core/configuration/Configuration_apply_Test.java +++ b/src/test/java/org/assertj/core/configuration/Configuration_apply_Test.java @@ -13,6 +13,7 @@ package org.assertj.core.configuration; import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.util.AssertionsUtil.expectAssertionError; import java.text.SimpleDateFormat; import java.util.Date; @@ -35,12 +36,12 @@ void apply_should_change_assertj_behavior() throws Exception { // THEN then(FieldSupport.extraction().isAllowedToUsePrivateFields()).isEqualTo(configuration.extractingPrivateFieldsEnabled()); then(FieldSupport.comparison().isAllowedToUsePrivateFields()).isEqualTo(configuration.comparingPrivateFieldsEnabled()); - then(Introspection.canIntrospectExtractBareNamePropertyMethods()).isEqualTo(configuration.bareNamePropertyExtractionEnabled()); + then(Introspection.canExtractBareNamePropertyMethods()).isEqualTo(configuration.bareNamePropertyExtractionEnabled()); then(configuration.hasCustomRepresentation()).isTrue(); // a bit dodgy but since our custom representation inherits StandardRepresentation, changing maxElementsForPrinting amd // maxLengthForSingleLineDescription will be effective. then(StandardRepresentation.getMaxElementsForPrinting()).isEqualTo(configuration.maxElementsForPrinting()); - then(StandardRepresentation.getMaxStackTraceElementsDisplayed ()).isEqualTo(configuration.maxStackTraceElementsDisplayed ()); + then(StandardRepresentation.getMaxStackTraceElementsDisplayed()).isEqualTo(configuration.maxStackTraceElementsDisplayed()); then(StandardRepresentation.getMaxLengthForSingleLineDescription()).isEqualTo(configuration.maxLengthForSingleLineDescription()); boolean removeAssertJRelatedElementsFromStackTrace = Failures.instance().isRemoveAssertJRelatedElementsFromStackTrace(); then(removeAssertJRelatedElementsFromStackTrace).isEqualTo(configuration.removeAssertJRelatedElementsFromStackTraceEnabled()); @@ -55,6 +56,19 @@ void apply_should_change_assertj_behavior() throws Exception { .isEqualTo("2001|02|03"); } + @Test + void should_reset_date_formats() throws Exception { + // GIVEN + Configuration configuration = new NonDefaultConfiguration(); + // WHEN + configuration.apply(); + Configuration.DEFAULT_CONFIGURATION.apply(); + // THEN + then(Configuration.DEFAULT_CONFIGURATION.additionalDateFormats()).isEmpty(); + Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2001-02-03"); + expectAssertionError(() -> then(date).isEqualTo("2001_02_03")); + } + @AfterEach public void afterEach() { // revert whatever we did in the other tests diff --git a/src/test/java/org/assertj/core/data/Offset_Test.java b/src/test/java/org/assertj/core/data/Offset_Test.java index 1af942d44b8..c72bab34bf6 100644 --- a/src/test/java/org/assertj/core/data/Offset_Test.java +++ b/src/test/java/org/assertj/core/data/Offset_Test.java @@ -103,4 +103,14 @@ void should_implement_toString() { then(result).isEqualTo("Offset[value=0.0]"); } + @Test + void toString_should_describe_strict_offset() { + // GIVEN + Offset underTest = Offset.strictOffset(1.0); + // WHEN + String result = underTest.toString(); + // THEN + then(result).isEqualTo("strict Offset[value=1.0]"); + } + } diff --git a/src/test/java/org/assertj/core/error/AssertJMultipleFailuresError_getMessage_Test.java b/src/test/java/org/assertj/core/error/AssertJMultipleFailuresError_getMessage_Test.java deleted file mode 100644 index e6dcecbb701..00000000000 --- a/src/test/java/org/assertj/core/error/AssertJMultipleFailuresError_getMessage_Test.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - * Copyright 2012-2021 the original author or authors. - */ -package org.assertj.core.error; - -import static java.lang.String.format; -import static org.assertj.core.api.BDDAssertions.then; -import static org.assertj.core.test.ErrorMessagesForTest.shouldBeEqualMessage; -import static org.assertj.core.util.AssertionsUtil.expectAssertionError; -import static org.assertj.core.util.Lists.list; - -import org.assertj.core.api.SoftAssertions; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -@DisplayName("AssertJMultipleFailuresError getMessage") -class AssertJMultipleFailuresError_getMessage_Test { - - @Test - void should_honor_description() { - // GIVEN - String description = "desc"; - AssertJMultipleFailuresError error = new AssertJMultipleFailuresError(description, list(new AssertionError("boom"))); - // WHEN - String message = error.getMessage(); - // THEN - then(message).startsWith(format("%n%s", description)); - } - - @Test - void should_include_errors_count_and_clearly_separate_error_messages() { - // GIVEN - SoftAssertions softly = new SoftAssertions(); - softly.assertThat(list("")).isEmpty(); - softly.assertThat(list("a", "b", "c")).as("isEmpty list").isEmpty(); - softly.assertThat("abc").isEmpty(); - softly.assertThat("abc").as("isEmpty string").isEmpty(); - softly.assertThat("abc").isEqualTo("bcd"); - softly.assertThat("abc").as("isEqualTo").isEqualTo("bcd"); - softly.assertThat(list("a", "b", "c")).as("contains").contains("e").doesNotContain("a"); - softly.assertThat(list("a", "b", "c")).contains("e").doesNotContain("a"); - // WHEN - AssertionError error = expectAssertionError(() -> softly.assertAll()); - // THEN - then(error).hasMessage(format("%nMultiple Failures (10 failures)%n" + - "-- failure 1 --%n" + - "Expecting empty but was: [\"\"]%n" + - "-- failure 2 --%n" + - "[isEmpty list] %n" + - "Expecting empty but was: [\"a\", \"b\", \"c\"]%n" + - "-- failure 3 --%n" + - "Expecting empty but was: \"abc\"%n" + - "-- failure 4 --%n" + - "[isEmpty string] %n" + - "Expecting empty but was: \"abc\"%n" + - "-- failure 5 --" + - shouldBeEqualMessage("\"abc\"", "\"bcd\"") + "%n" + - "-- failure 6 --%n" + - shouldBeEqualMessage("isEqualTo", "\"abc\"", "\"bcd\"") + "%n" + - "-- failure 7 --%n" + - "[contains] %n" + - "Expecting ArrayList:%n" + - " [\"a\", \"b\", \"c\"]%n" + - "to contain:%n" + - " [\"e\"]%n" + - "but could not find the following element(s):%n" + - " [\"e\"]%n" + - "%n" + - "-- failure 8 --%n" + - "[contains] %n" + - "Expecting%n" + - " [\"a\", \"b\", \"c\"]%n" + - "not to contain%n" + - " [\"a\"]%n" + - "but found%n" + - " [\"a\"]%n" + - "%n" + - "-- failure 9 --%n" + - "Expecting ArrayList:%n" + - " [\"a\", \"b\", \"c\"]%n" + - "to contain:%n" + - " [\"e\"]%n" + - "but could not find the following element(s):%n" + - " [\"e\"]%n" + - "%n" + - "-- failure 10 --%n" + - "Expecting%n" + - " [\"a\", \"b\", \"c\"]%n" + - "not to contain%n" + - " [\"a\"]%n" + - "but found%n" + - " [\"a\"]%n")); - } - -} diff --git a/src/test/java/org/assertj/core/error/ClassModifierShouldBe_create_Test.java b/src/test/java/org/assertj/core/error/ClassModifierShouldBe_create_Test.java index 8cb1791c28a..b1dc11320c3 100644 --- a/src/test/java/org/assertj/core/error/ClassModifierShouldBe_create_Test.java +++ b/src/test/java/org/assertj/core/error/ClassModifierShouldBe_create_Test.java @@ -33,7 +33,7 @@ void should_create_error_message_for_is_final() { String error = shouldBeFinal(nonFinalClass).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " java.lang.Object%n" + "to be a \"final\" class but was \"public\".")); } @@ -46,7 +46,7 @@ void should_create_error_message_for_is_not_final() { String error = shouldNotBeFinal(finalClass).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " java.lang.String%n" + "not to be a \"final\" class but was \"public final\".")); } @@ -59,7 +59,7 @@ void should_create_clear_error_message_when_actual_is_package_private_enum() { String error = shouldBePublic(packagePrivateEnum).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " org.assertj.core.error.ClassModifierShouldBe_create_Test.PackagePrivateEnum%n" + "to be a \"public\" class but was \"package-private static final\".")); } @@ -72,7 +72,7 @@ void should_create_clear_error_message_when_actual_is_only_package_private() { String error = shouldBePublic(packagePrivateClass).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " org.assertj.core.error.ClassModifierShouldBe_create_Test.PackagePrivateClass%n" + "to be a \"public\" class but was \"package-private\".")); } diff --git a/src/test/java/org/assertj/core/error/GroupTypeDescription_getGroupTypeDescription_Test.java b/src/test/java/org/assertj/core/error/GroupTypeDescription_getGroupTypeDescription_Test.java index 01bf19c600e..a65037e43d1 100644 --- a/src/test/java/org/assertj/core/error/GroupTypeDescription_getGroupTypeDescription_Test.java +++ b/src/test/java/org/assertj/core/error/GroupTypeDescription_getGroupTypeDescription_Test.java @@ -12,12 +12,13 @@ */ package org.assertj.core.error; -import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; +import static org.assertj.core.api.BDDAssertions.then; import static org.assertj.core.error.GroupTypeDescription.getGroupTypeDescription; import static org.assertj.core.test.Maps.mapOf; import static org.assertj.core.util.Lists.list; import static org.assertj.core.util.Sets.newLinkedHashSet; +import static org.junit.jupiter.params.provider.Arguments.arguments; import java.util.stream.Stream; @@ -36,25 +37,35 @@ void should_return_group_description(Object obj, String groupTypeName, String el // WHEN GroupTypeDescription description = getGroupTypeDescription(obj); // THEN - assertThat(description.getGroupTypeName()).isEqualTo(groupTypeName); - assertThat(description.getElementTypeName()).isEqualTo(elementTypeName); + then(description.getGroupTypeName()).isEqualTo(groupTypeName); + then(description.getElementTypeName()).isEqualTo(elementTypeName); + } + + @ParameterizedTest(name = "{0}: {1} {2} ") + @MethodSource("argumentsStreamProvider") + void should_return_group_description_from_class(Object obj, String groupTypeName, String elementTypeName) { + // WHEN + GroupTypeDescription description = getGroupTypeDescription(obj.getClass()); + // THEN + then(description.getGroupTypeName()).isEqualTo(groupTypeName); + then(description.getElementTypeName()).isEqualTo(elementTypeName); } private static Stream argumentsStreamProvider() { - return Stream.of(Arguments.of(mapOf(entry("1", 2d)), "map", "map entries"), - Arguments.of(new int[] { 1, 2 }, "int[]", "int(s)"), - Arguments.of(new double[] { 1, 2 }, "double[]", "double(s)"), - Arguments.of(new float[] { 1f, 2f }, "float[]", "float(s)"), - Arguments.of(new byte[] { 1, 2 }, "byte[]", "byte(s)"), - Arguments.of(new long[] { 1L, 2L }, "long[]", "long(s)"), - Arguments.of(new boolean[] { true }, "boolean[]", "boolean(s)"), - Arguments.of(new char[] { 'a', 'b' }, "char[]", "char(s)"), - Arguments.of(new short[] { 1, 2 }, "short[]", "short(s)"), - Arguments.of(new String[] { "a", "c" }, "String[]", "string(s)"), - Arguments.of(new Object[] { "a", "c" }, "Object[]", "object(s)"), - Arguments.of(new Jedi[] { new Jedi("Yoda", "green") }, "Jedi[]", "jedi(s)"), - Arguments.of(list(1, 2), "ArrayList", "element(s)"), - Arguments.of(newLinkedHashSet(1, 2), "LinkedHashSet", "element(s)")); + return Stream.of(arguments(mapOf(entry("1", 2d)), "map", "map entries"), + arguments(new int[] { 1, 2 }, "int[]", "int(s)"), + arguments(new double[] { 1, 2 }, "double[]", "double(s)"), + arguments(new float[] { 1f, 2f }, "float[]", "float(s)"), + arguments(new byte[] { 1, 2 }, "byte[]", "byte(s)"), + arguments(new long[] { 1L, 2L }, "long[]", "long(s)"), + arguments(new boolean[] { true }, "boolean[]", "boolean(s)"), + arguments(new char[] { 'a', 'b' }, "char[]", "char(s)"), + arguments(new short[] { 1, 2 }, "short[]", "short(s)"), + arguments(new String[] { "a", "c" }, "String[]", "string(s)"), + arguments(new Object[] { "a", "c" }, "Object[]", "object(s)"), + arguments(new Jedi[] { new Jedi("Yoda", "green") }, "Jedi[]", "jedi(s)"), + arguments(list(1, 2), "ArrayList", "element(s)"), + arguments(newLinkedHashSet(1, 2), "LinkedHashSet", "element(s)")); } } diff --git a/src/test/java/org/assertj/core/error/OptionalDouble_ShouldHaveValueCloseToOffset_create_Test.java b/src/test/java/org/assertj/core/error/OptionalDouble_ShouldHaveValueCloseToOffset_create_Test.java index ae19e8c9b01..ffab43f8363 100644 --- a/src/test/java/org/assertj/core/error/OptionalDouble_ShouldHaveValueCloseToOffset_create_Test.java +++ b/src/test/java/org/assertj/core/error/OptionalDouble_ShouldHaveValueCloseToOffset_create_Test.java @@ -38,7 +38,7 @@ void should_create_error_message() { // WHEN String errorMessage = shouldHaveValueCloseToOffset(OptionalDouble.of(20.0), 10.0, within(2.0), 3).create(); // THEN - then(errorMessage).isEqualTo(format("%nExpecting:%n OptionalDouble[20.0]%nto be close to:%n 10.0%n" + + then(errorMessage).isEqualTo(format("%nExpecting actual:%n OptionalDouble[20.0]%nto be close to:%n 10.0%n" + "by less than 2.0 but difference was 3.0.%n" + "(a difference of exactly 2.0 being considered valid)")); } diff --git a/src/test/java/org/assertj/core/error/OptionalDouble_ShouldHaveValueCloseToPercentage_create_Test.java b/src/test/java/org/assertj/core/error/OptionalDouble_ShouldHaveValueCloseToPercentage_create_Test.java index 9321ab8fa0d..e11382b8f8e 100644 --- a/src/test/java/org/assertj/core/error/OptionalDouble_ShouldHaveValueCloseToPercentage_create_Test.java +++ b/src/test/java/org/assertj/core/error/OptionalDouble_ShouldHaveValueCloseToPercentage_create_Test.java @@ -38,7 +38,7 @@ void should_create_error_message_when_optionaldouble_value_is_not_close_enough_t // WHEN String errorMessage = shouldHaveValueCloseToPercentage(OptionalDouble.of(20), 10, withinPercentage(2), 3).create(); // THEN - then(errorMessage).isEqualTo(format("%nExpecting:%n OptionalDouble[20.0]%n" + + then(errorMessage).isEqualTo(format("%nExpecting actual:%n OptionalDouble[20.0]%n" + "to be close to:%n" + " 10.0%n" + "by less than 2%% but difference was 30.0%%.%n" + diff --git a/src/test/java/org/assertj/core/error/OptionalShouldContainInstanceOf_create_Test.java b/src/test/java/org/assertj/core/error/OptionalShouldContainInstanceOf_create_Test.java index 7ac1444fa9f..82b3a197008 100644 --- a/src/test/java/org/assertj/core/error/OptionalShouldContainInstanceOf_create_Test.java +++ b/src/test/java/org/assertj/core/error/OptionalShouldContainInstanceOf_create_Test.java @@ -27,7 +27,7 @@ void should_create_error_message_with_empty() { // WHEN String errorMessage = shouldContainInstanceOf(Optional.empty(), Object.class).create(); // THEN - then(errorMessage).isEqualTo(format("%nExpecting:%n Optional%n" + + then(errorMessage).isEqualTo(format("%nExpecting actual:%n Optional%n" + "to contain a value that is an instance of:%n java.lang.Object%n" + "but was empty")); } @@ -37,7 +37,7 @@ void should_create_error_message_with_expected_type() { // WHEN String errorMessage = shouldContainInstanceOf(Optional.of(Integer.MIN_VALUE), String.class).create(); // THEN - then(errorMessage).isEqualTo(format("%nExpecting:%n Optional%n" + + then(errorMessage).isEqualTo(format("%nExpecting actual:%n Optional%n" + "to contain a value that is an instance of:%n java.lang.String%n" + "but did contain an instance of:%n java.lang.Integer")); } diff --git a/src/test/java/org/assertj/core/error/Optional_ShouldContain_create_Test.java b/src/test/java/org/assertj/core/error/Optional_ShouldContain_create_Test.java index b723af67cfe..60ffcf7815d 100644 --- a/src/test/java/org/assertj/core/error/Optional_ShouldContain_create_Test.java +++ b/src/test/java/org/assertj/core/error/Optional_ShouldContain_create_Test.java @@ -41,7 +41,7 @@ void should_create_error_message() { // WHEN String errorMessage = shouldContain(Optional.of(20), 10).create(); // THEN - then(errorMessage).isEqualTo(format("%nExpecting:%n" + + then(errorMessage).isEqualTo(format("%nExpecting actual:%n" + " Optional[20]%n" + "to contain:%n" + " 10%n" + @@ -63,7 +63,7 @@ void should_create_error_message_with_optionaldouble() { // WHEN String errorMessage = shouldContain(OptionalDouble.of(20.0), 10.0).create(); // THEN - then(errorMessage).isEqualTo(format("%nExpecting:%n" + + then(errorMessage).isEqualTo(format("%nExpecting actual:%n" + " OptionalDouble[20.0]%n" + "to contain:%n" + " 10.0%n" + @@ -85,7 +85,7 @@ void should_create_error_message_with_optionalint() { // WHEN String errorMessage = shouldContain(OptionalInt.of(20), 10).create(); // THEN - then(errorMessage).isEqualTo(format("%nExpecting:%n" + + then(errorMessage).isEqualTo(format("%nExpecting actual:%n" + " OptionalInt[20]%n" + "to contain:%n" + " 10%n" + @@ -107,7 +107,7 @@ void should_create_error_message_with_optionallong() { // WHEN String errorMessage = shouldContain(OptionalLong.of(20L), 10L).create(); // THEN - then(errorMessage).isEqualTo(format("%nExpecting:%n" + + then(errorMessage).isEqualTo(format("%nExpecting actual:%n" + " OptionalLong[20]%n" + "to contain:%n" + " 10L%n" + @@ -129,7 +129,7 @@ void should_create_error_message_for_different_instances() { // WHEN String errorMessage = shouldContainSame(Optional.of(10), 10).create(); // THEN - then(errorMessage).isEqualTo(format("%nExpecting:%n" + + then(errorMessage).isEqualTo(format("%nExpecting actual:%n" + " Optional[10]%n" + "to contain the instance (i.e. compared with ==):%n" + " 10%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldAccept_create_Test.java b/src/test/java/org/assertj/core/error/ShouldAccept_create_Test.java index 83261aa0914..b141332160d 100644 --- a/src/test/java/org/assertj/core/error/ShouldAccept_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldAccept_create_Test.java @@ -31,7 +31,7 @@ void should_create_error_message_with_default_predicate_description() { // WHEN String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n given predicate%nto accept \"Yoda\" but it did not.")); + then(message).isEqualTo(format("[Test] %nExpecting actual:%n given predicate%nto accept \"Yoda\" but it did not.")); } @Test @@ -42,7 +42,7 @@ void should_create_error_message_with_predicate_description() { // WHEN String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n 'green light saber' predicate%nto accept \"Yoda\" but it did not.")); + then(message).isEqualTo(format("[Test] %nExpecting actual:%n 'green light saber' predicate%nto accept \"Yoda\" but it did not.")); } @Test diff --git a/src/test/java/org/assertj/core/error/ShouldBeAbstract_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeAbstract_create_Test.java index 52189e623df..f9148256f78 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeAbstract_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeAbstract_create_Test.java @@ -30,7 +30,7 @@ void should_create_error_message() { String message = errorMessageFactory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " java.lang.String%n" + "to be abstract")); } diff --git a/src/test/java/org/assertj/core/error/ShouldBeAfterOrEqualTo_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeAfterOrEqualTo_create_Test.java index a3b9205b575..538c91399e3 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeAfterOrEqualTo_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeAfterOrEqualTo_create_Test.java @@ -41,7 +41,7 @@ void should_create_error_message() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2011-01-01T00:00:00.000 (java.util.Date)%n" + "to be after or equal to:%n" + " 2012-01-01T00:00:00.000 (java.util.Date)%n")); @@ -56,7 +56,7 @@ void should_create_error_message_with_comparison_strategy() { String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2011-01-01T00:00:00.000 (java.util.Date)%n" + "to be after or equal to:%n" + " 2012-01-01T00:00:00.000 (java.util.Date)%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldBeAfter_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeAfter_create_Test.java index 90404d2c0bd..6c39ff9ecd7 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeAfter_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeAfter_create_Test.java @@ -40,7 +40,7 @@ void should_create_error_message() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2011-01-01T00:00:00.000 (java.util.Date)%n" + "to be strictly after:%n" + " 2012-01-01T00:00:00.000 (java.util.Date)%n")); @@ -55,7 +55,7 @@ void should_create_error_message_with_comparison_strategy() { String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2011-01-01T00:00:00.000 (java.util.Date)%n" + "to be strictly after:%n" + " 2012-01-01T00:00:00.000 (java.util.Date)%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldBeAtIndex_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeAtIndex_create_Test.java index 729f87e2cfb..c7ed79b6d54 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeAtIndex_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeAtIndex_create_Test.java @@ -39,6 +39,6 @@ void should_create_error_message() { // WHEN String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n \"Luke\"%nat index 1 to be:%n red lightsaber%nin:%n [\"Yoda\", \"Luke\"]%n")); + then(message).isEqualTo(format("[Test] %nExpecting actual:%n \"Luke\"%nat index 1 to be:%n red lightsaber%nin:%n [\"Yoda\", \"Luke\"]%n")); } } diff --git a/src/test/java/org/assertj/core/error/ShouldBeBeforeOrEqualTo_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeBeforeOrEqualTo_create_Test.java index 1171e09de19..54beae63d43 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeBeforeOrEqualTo_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeBeforeOrEqualTo_create_Test.java @@ -33,7 +33,7 @@ void should_create_error_message() { String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2019-01-01T00:00:00.000 (java.util.Date)%n" + "to be before or equal to:%n" + " 2012-01-01T00:00:00.000 (java.util.Date)%n")); @@ -48,7 +48,7 @@ void should_create_error_message_with_comparison_strategy() { String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2019-01-01T00:00:00.000 (java.util.Date)%n" + "to be before or equal to:%n" + " 2012-01-01T00:00:00.000 (java.util.Date)%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldBeBefore_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeBefore_create_Test.java index 77e44f983c5..f746be6951f 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeBefore_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeBefore_create_Test.java @@ -39,7 +39,7 @@ void should_create_error_message() { String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // WHEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2019-01-01T00:00:00.000 (java.util.Date)%n" + "to be strictly before:%n" + " 2012-01-01T00:00:00.000 (java.util.Date)%n")); @@ -54,7 +54,7 @@ void should_create_error_message_with_comparison_strategy() { String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2019-01-01T00:00:00.000 (java.util.Date)%n" + "to be strictly before:%n" + " 2012-01-01T00:00:00.000 (java.util.Date)%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldBeBetween_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeBetween_create_Test.java index 7da4954734e..01cb478e8f5 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeBetween_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeBetween_create_Test.java @@ -38,7 +38,7 @@ void should_create_error_message_with_period_boundaries_included() { String message = factory.create(new TextDescription("Test")); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2010-01-01T00:00:00.000 (java.util.Date)%n" + "to be in period:%n" + " [2011-01-01T00:00:00.000 (java.util.Date), 2012-01-01T00:00:00.000 (java.util.Date)]%n")); @@ -52,7 +52,7 @@ void should_create_error_message_with_period_lower_boundary_included() { String message = factory.create(new TextDescription("Test")); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2010-01-01T00:00:00.000 (java.util.Date)%n" + "to be in period:%n" + " [2011-01-01T00:00:00.000 (java.util.Date), 2012-01-01T00:00:00.000 (java.util.Date)[%n")); @@ -66,7 +66,7 @@ void should_create_error_message_with_period_upper_boundary_included() { String message = factory.create(new TextDescription("Test")); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2010-01-01T00:00:00.000 (java.util.Date)%n" + "to be in period:%n" + " ]2011-01-01T00:00:00.000 (java.util.Date), 2012-01-01T00:00:00.000 (java.util.Date)]%n")); @@ -80,7 +80,7 @@ void should_create_error_message_with_period_boundaries_excluded() { String message = factory.create(new TextDescription("Test")); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2010-01-01T00:00:00.000 (java.util.Date)%n" + "to be in period:%n" + " ]2011-01-01T00:00:00.000 (java.util.Date), 2012-01-01T00:00:00.000 (java.util.Date)[%n")); @@ -96,7 +96,7 @@ void should_create_error_message_with_comparison_strategy() { String message = factory.create(new TextDescription("Test")); // THEN then(message).isEqualTo("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2010-01-01T00:00:00.000 (java.util.Date)%n" + "to be in period:%n" + " ]2011-01-01T00:00:00.000 (java.util.Date), 2012-01-01T00:00:00.000 (java.util.Date)[%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldBeCloseTo_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeCloseTo_create_Test.java index 6ab75e75865..9990869334e 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeCloseTo_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeCloseTo_create_Test.java @@ -42,7 +42,7 @@ void should_create_error_message_with_period_boundaries_included() { String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2011-01-01T00:00:00.000%n" + "to be close to:%n" + " 2011-01-01T00:00:00.101%n" + @@ -58,7 +58,7 @@ void should_create_error_message_with_TemporalAmount() { String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " PT1H%n" + "to be close to:%n" + " PT2H%n" + @@ -73,7 +73,7 @@ void should_create_error_message_with_Temporal() { String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 13:22:37%n" + "to be close to:%n" + " 13:22:32%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldBeEmptyDirectory_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeEmptyDirectory_create_Test.java index 1766d9d8098..851f406a8fe 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeEmptyDirectory_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeEmptyDirectory_create_Test.java @@ -40,7 +40,7 @@ void should_create_error_message_for_Path() { // WHEN String message = shouldBeEmptyDirectory(directory, directoryContent).create(DESCRIPTION, STANDARD_REPRESENTATION); // THEN - then(message).isEqualTo("[Test] %nExpecting:%n" + + then(message).isEqualTo("[Test] %nExpecting actual:%n" + " /root%n" + "to be an empty directory but it contained:%n" + " [/bin/file1, /bin/file2]", @@ -56,7 +56,7 @@ void should_create_error_message_for_File() { // WHEN String message = shouldBeEmptyDirectory(directory, directoryContent).create(DESCRIPTION, STANDARD_REPRESENTATION); // THEN - then(message).isEqualTo("[Test] %nExpecting:%n" + + then(message).isEqualTo("[Test] %nExpecting actual:%n" + " %s%n" + "to be an empty directory but it contained:%n" + " %s", diff --git a/src/test/java/org/assertj/core/error/ShouldBeEqualByComparingFieldByFieldRecursively_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeEqualByComparingFieldByFieldRecursively_create_Test.java index 4d01cbea307..ad3f91b78b8 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeEqualByComparingFieldByFieldRecursively_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeEqualByComparingFieldByFieldRecursively_create_Test.java @@ -212,19 +212,19 @@ void should_show_multiple_differences() { // @format:on // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " Name[first='Magic', last='Johnson']%n" + "to be equal to:%n" + " Name[first='null', last='Ginobili']%n" + "when recursively comparing field by field, but found the following 2 differences:%n" + "%n" + "field/property 'first' differ:%n" + - "- actual value : \"Magic\"%n" + - "- expected value : null%n" + + "- actual value : \"Magic\"%n" + + "- expected value: null%n" + "%n" + "field/property 'last' differ:%n" + - "- actual value : \"Johnson\"%n" + - "- expected value : \"Ginobili\"%n" + + "- actual value : \"Johnson\"%n" + + "- expected value: \"Ginobili\"%n" + "%n" + "The recursive comparison was performed with this configuration:%n%s", CONFIGURATION_PROVIDER.representation().toStringOf(recursiveComparisonConfiguration))); @@ -248,15 +248,15 @@ void should_show_one_difference() { // @format:on // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " Name[first='Magic', last='Johnson']%n" + "to be equal to:%n" + " Name[first='null', last='Johnson']%n" + "when recursively comparing field by field, but found the following difference:%n" + "%n" + "field/property 'first' differ:%n" + - "- actual value : \"Magic\"%n" + - "- expected value : null%n" + + "- actual value : \"Magic\"%n" + + "- expected value: null%n" + "%n" + "The recursive comparison was performed with this configuration:%n%s", CONFIGURATION_PROVIDER.representation().toStringOf(recursiveComparisonConfiguration))); @@ -280,15 +280,15 @@ void should_show_difference_with_percentage() { // @format:on // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " Name[first='%%%%Ma%%gi%%', last='%%Johnson']%n" + "to be equal to:%n" + " Name[first='null', last='%%Johnson']%n" + "when recursively comparing field by field, but found the following difference:%n" + "%n" + "field/property 'first' differ:%n" + - "- actual value : \"%%%%Ma%%gi%%\"%n" + - "- expected value : null%n" + + "- actual value : \"%%%%Ma%%gi%%\"%n" + + "- expected value: null%n" + "%n" + "The recursive comparison was performed with this configuration:%n%s", CONFIGURATION_PROVIDER.representation().toStringOf(recursiveComparisonConfiguration))); diff --git a/src/test/java/org/assertj/core/error/ShouldBeEqualIgnoringMinutes_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeEqualIgnoringMinutes_create_Test.java index 6de6da3a34f..ad3701e2c09 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeEqualIgnoringMinutes_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeEqualIgnoringMinutes_create_Test.java @@ -39,7 +39,7 @@ void should_create_error_message_for_LocalTime() { String message = factory.create(new TestDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 12:00%n" + "to have same hour as:%n" + " 12:01%n" + @@ -55,7 +55,7 @@ void should_create_error_message_for_OffsetTime() { String message = factory.create(new TestDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 12:00Z%n" + "to have same hour as:%n" + " 12:01Z%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldBeEqualIgnoringNanos_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeEqualIgnoringNanos_create_Test.java index 36a3e42d4a5..2a4774c7d8b 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeEqualIgnoringNanos_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeEqualIgnoringNanos_create_Test.java @@ -39,7 +39,7 @@ void should_create_error_message_for_LocalTime() { String message = factory.create(new TestDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 12:00%n" + "to have same hour, minute and second as:%n" + " 13:00%n" + @@ -54,7 +54,7 @@ void should_create_error_message_for_OffsetTime() { String message = factory.create(new TestDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 12:00Z%n" + "to have same hour, minute and second as:%n" + " 13:00Z%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldBeEqualIgnoringNewlines_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeEqualIgnoringNewlines_create_Test.java index 77de89821f0..41e405d3b9f 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeEqualIgnoringNewlines_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeEqualIgnoringNewlines_create_Test.java @@ -30,7 +30,7 @@ void should_create_error_message() { String message = factory.create(new TestDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " \"foo\"%n" + "to be equal to:%n" + " \"bar\"%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldBeEqualIgnoringSeconds_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeEqualIgnoringSeconds_create_Test.java index 47cc484477a..7a8dd2d8b31 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeEqualIgnoringSeconds_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeEqualIgnoringSeconds_create_Test.java @@ -39,7 +39,7 @@ void should_create_error_message_for_LocalTime() { String message = factory.create(new TestDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 12:00:01%n" + "to have same hour and minute as:%n" + " 12:00:02%n" + @@ -55,7 +55,7 @@ void should_create_error_message_for_OffsetTime() { String message = factory.create(new TestDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 12:00:01Z%n" + "to have same hour and minute as:%n" + " 12:00:02Z%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldBeEqualIgnoringTimezone_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeEqualIgnoringTimezone_create_Test.java index 5fa3c5d3e3f..6f01c0abcb5 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeEqualIgnoringTimezone_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeEqualIgnoringTimezone_create_Test.java @@ -43,7 +43,7 @@ void should_create_error_message_for_OffsetTime() { String message = factory.create(new TestDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 12:00Z%n" + "to have same time fields except timezone as:%n" + " 12:00-18:00%n" + @@ -59,7 +59,7 @@ void should_create_error_message_for_OffsetDateTime() { String message = factory.create(new TestDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2000-05-13T12:00Z (java.time.OffsetDateTime)%n" + "to have same time fields except timezone as:%n" + " 2000-05-13T12:00-18:00 (java.time.OffsetDateTime)%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldBeEqualIgnoringWhitespace_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeEqualIgnoringWhitespace_create_Test.java index 4425ea9218d..b1835b93268 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeEqualIgnoringWhitespace_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeEqualIgnoringWhitespace_create_Test.java @@ -39,7 +39,7 @@ void should_create_error_message() { String message = factory.create(new TestDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " \" my\tfoo bar \"%n" + "to be equal to:%n" + " \" myfoo bar \"%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldBeEqualNormalizingPunctuationAndWhitespace_create_test.java b/src/test/java/org/assertj/core/error/ShouldBeEqualNormalizingPunctuationAndWhitespace_create_test.java index a58dad67c19..25aec2714a6 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeEqualNormalizingPunctuationAndWhitespace_create_test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeEqualNormalizingPunctuationAndWhitespace_create_test.java @@ -37,7 +37,7 @@ void should_create_error_message() { String message = factory.create(new TestDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " \" Game-of-Thrones \"%n" + "to be equal to:%n" + " \" Game of Thrones \"%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldBeEqualNormalizingWhitespace_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeEqualNormalizingWhitespace_create_Test.java index 5ea91e42f11..112887215e8 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeEqualNormalizingWhitespace_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeEqualNormalizingWhitespace_create_Test.java @@ -39,7 +39,7 @@ void should_create_error_message() { String message = factory.create(new TestDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " \" my\tfoo bar \"%n" + "to be equal to:%n" + " \" myfoo bar \"%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldBeEqualWithTimePrecision_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeEqualWithTimePrecision_create_Test.java index ebedc0066b4..f6a8f3bce98 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeEqualWithTimePrecision_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeEqualWithTimePrecision_create_Test.java @@ -38,7 +38,7 @@ void should_create_error_message_ignoring_milliseconds() { parseDatetimeWithMs("2011-01-01T06:05:17.003"), TimeUnit.MILLISECONDS); String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); - then(message).isEqualTo(format("[Test] %nExpecting:%n" + + then(message).isEqualTo(format("[Test] %nExpecting actual:%n" + " 2011-01-01T05:00:00.000 (java.util.Date)%n" + "to have same year, month, day, hour, minute and second as:%n" + " 2011-01-01T06:05:17.003 (java.util.Date)%n" + @@ -51,7 +51,7 @@ void should_create_error_message_ignoring_seconds() { parseDatetimeWithMs("2011-01-01T06:05:17.003"), TimeUnit.SECONDS); String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); - then(message).isEqualTo(format("[Test] %nExpecting:%n" + + then(message).isEqualTo(format("[Test] %nExpecting actual:%n" + " 2011-01-01T05:00:00.000 (java.util.Date)%n" + "to have same year, month, day, hour and minute as:%n" + " 2011-01-01T06:05:17.003 (java.util.Date)%n" + @@ -64,7 +64,7 @@ void should_create_error_message_ignoring_minutes() { parseDatetimeWithMs("2011-01-01T06:05:17.003"), TimeUnit.MINUTES); String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); - then(message).isEqualTo(format("[Test] %nExpecting:%n" + + then(message).isEqualTo(format("[Test] %nExpecting actual:%n" + " 2011-01-01T05:00:00.000 (java.util.Date)%n" + "to have same year, month, day and hour as:%n" + " 2011-01-01T06:05:17.003 (java.util.Date)%n" + @@ -77,7 +77,7 @@ void should_create_error_message_ignoring_hours() { parseDatetimeWithMs("2011-01-01T06:05:17.003"), TimeUnit.HOURS); String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); - then(message).isEqualTo(format("[Test] %nExpecting:%n" + + then(message).isEqualTo(format("[Test] %nExpecting actual:%n" + " 2011-01-01T05:00:00.000 (java.util.Date)%n" + "to have same year, month and day as:%n" + " 2011-01-01T06:05:17.003 (java.util.Date)%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldBeEqualWithinOffset_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeEqualWithinOffset_create_Test.java index 25ae1d2ade1..463440afdf9 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeEqualWithinOffset_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeEqualWithinOffset_create_Test.java @@ -38,7 +38,7 @@ void should_create_error_message() { String message = factory.create(new TestDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 8.0f%n" + "to be close to:%n" + " 6.0f%n" + @@ -54,7 +54,7 @@ void should_create_error_message_for_strict_offset() { String message = factory.create(new TestDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 8.0f%n" + "to be close to:%n" + " 6.0f%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldBeEqualWithinPercentage_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeEqualWithinPercentage_create_Test.java index 41ff3c87644..cb42cdce9e3 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeEqualWithinPercentage_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeEqualWithinPercentage_create_Test.java @@ -37,7 +37,7 @@ void should_create_error_message_with_int_percentage_displayed_as_int() { String message = factory.create(new TestDescription("Test")); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 12.0%n" + "to be close to:%n" + " 10.0%n" + @@ -53,7 +53,7 @@ void should_create_error_message_with_double_percentage_displayed_as_int() { String message = factory.create(new TestDescription("Test")); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 12.0%n" + "to be close to:%n" + " 10.0%n" + @@ -69,7 +69,7 @@ void should_create_error_message_with_percentage_as_double() { String message = factory.create(new TestDescription("Test")); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 12.0%n" + "to be close to:%n" + " 10.0%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldBeEqual_Test.java b/src/test/java/org/assertj/core/error/ShouldBeEqual_Test.java index 461cc5946a4..bcf252d3ef5 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeEqual_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeEqual_Test.java @@ -39,7 +39,7 @@ void should_display_comparison_strategy_in_error_message() { then(error.getExpected().getValue()).isEqualTo(STANDARD_REPRESENTATION.toStringOf(expected)); then(error).hasMessage(format("[Jedi] %n" + "expected: \"Yoda\"%n" + - "but was : \"Luke\"%n" + + " but was: \"Luke\"%n" + "when comparing values using CaseInsensitiveStringComparator")); } @@ -56,7 +56,7 @@ void should_use_actual_and_expected_representation_in_AssertionFailedError_actua then(error.getExpected().getValue()).isEqualTo("[1, 2, 4]"); then(error).hasMessage(format("[numbers] %n" + "expected: [1, 2, 4]%n" + - "but was : [1, 2, 3]")); + " but was: [1, 2, 3]")); } } diff --git a/src/test/java/org/assertj/core/error/ShouldBeEqual_newAssertionError_Test.java b/src/test/java/org/assertj/core/error/ShouldBeEqual_newAssertionError_Test.java index 3e8f94b0236..d6b8d11daee 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeEqual_newAssertionError_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeEqual_newAssertionError_Test.java @@ -59,7 +59,7 @@ void should_create_AssertionFailedError_if_JUnit5_is_present_and_trim_spaces_in_ then(error).isInstanceOf(AssertionFailedError.class) .hasMessage(format("[Jedi] %n" + "expected: \"Yoda\"%n" + - "but was : \"Luke\"")); + " but was: \"Luke\"")); } public static Stream parameters() { diff --git a/src/test/java/org/assertj/core/error/ShouldBeEqual_newAssertionError_differentiating_expected_and_actual_Test.java b/src/test/java/org/assertj/core/error/ShouldBeEqual_newAssertionError_differentiating_expected_and_actual_Test.java index d4866a085c3..a0b8c70ac56 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeEqual_newAssertionError_differentiating_expected_and_actual_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeEqual_newAssertionError_differentiating_expected_and_actual_Test.java @@ -61,7 +61,7 @@ void should_create_AssertionError_with_message_differentiating_expected_double_a then(error).isInstanceOf(AssertionFailedError.class) .hasMessage(format("[my test] %n" + "expected: 42.0%n" + - "but was : 42.0f")); + " but was: 42.0f")); } @Test @@ -78,7 +78,7 @@ void should_create_AssertionError_with_message_differentiating_expected_and_actu then(error).isInstanceOf(AssertionFailedError.class) .hasMessage("[my test] %n" + "expected: \"Person[name=Jake] (Person@%s)\"%n" + - "but was : \"Person[name=Jake] (Person@%s)\"", + " but was: \"Person[name=Jake] (Person@%s)\"", toHexString(expected.hashCode()), toHexString(actual.hashCode())); } @@ -97,7 +97,7 @@ void should_create_AssertionError_with_message_differentiating_expected_and_actu then(error).isInstanceOf(AssertionFailedError.class) .hasMessage("[my test] %n" + "expected: \"Person[name=Jake] (Person@%s)\"%n" + - "but was : \"Person[name=Jake] (Person@%s)\"%n" + + " but was: \"Person[name=Jake] (Person@%s)\"%n" + "when comparing values using PersonComparator", toHexString(expected.hashCode()), toHexString(actual.hashCode())); } @@ -116,7 +116,7 @@ void should_create_AssertionError_with_message_differentiating_null_and_object_w then(error).isInstanceOf(AssertionFailedError.class) .hasMessage("[my test] %n" + "expected: \"null (ToStringIsNull@%s)\"%n" + - "but was : null", + " but was: null", toHexString(expected.hashCode())); } @@ -134,7 +134,7 @@ void should_create_AssertionError_with_message_differentiating_object_with_null_ then(error).isInstanceOf(AssertionFailedError.class) .hasMessage("[my test] %n" + "expected: null%n" + - "but was : \"null (ToStringIsNull@%s)\"", + " but was: \"null (ToStringIsNull@%s)\"", toHexString(actual.hashCode())); } diff --git a/src/test/java/org/assertj/core/error/ShouldBeEqual_newAssertionError_without_JUnit_Test.java b/src/test/java/org/assertj/core/error/ShouldBeEqual_newAssertionError_without_JUnit_Test.java index d95db0e16fb..28a060d8a9a 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeEqual_newAssertionError_without_JUnit_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeEqual_newAssertionError_without_JUnit_Test.java @@ -75,7 +75,7 @@ private void check(AssertionError error) throws Exception { new Class[] { String.class, Object.class, Object.class }, format("[Jedi] %n" + "expected: \"Yoda\"%n" + - "but was : \"Luke\""), + " but was: \"Luke\""), STANDARD_REPRESENTATION.toStringOf("Yoda"), STANDARD_REPRESENTATION.toStringOf("Luke")); assertThat(error).isNotInstanceOf(ComparisonFailure.class) @@ -85,7 +85,7 @@ private void check(AssertionError error) throws Exception { assertThat(assertionFailedError.getExpected().getValue()).isEqualTo(STANDARD_REPRESENTATION.toStringOf("Yoda")); assertThat(error).hasMessage(format("[Jedi] %n" + "expected: \"Yoda\"%n" + - "but was : \"Luke\"")); + " but was: \"Luke\"")); } private static Object createComparisonFailure(ConstructorInvoker invoker) throws Exception { diff --git a/src/test/java/org/assertj/core/error/ShouldBeEqual_newAssertionError_without_JUnit_and_OTA4J_Test.java b/src/test/java/org/assertj/core/error/ShouldBeEqual_newAssertionError_without_JUnit_and_OTA4J_Test.java index dbc0a126d97..ec9d64eae00 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeEqual_newAssertionError_without_JUnit_and_OTA4J_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeEqual_newAssertionError_without_JUnit_and_OTA4J_Test.java @@ -79,7 +79,7 @@ private void check(AssertionError error) throws Exception { array(String.class, Object.class, Object.class), format("[Jedi] %n" + "expected: \"Yoda\"%n" + - "but was : \"Luke\""), + " but was: \"Luke\""), STANDARD_REPRESENTATION.toStringOf("Yoda"), STANDARD_REPRESENTATION.toStringOf("Luke")); verify(constructorInvoker).newInstance(ComparisonFailure.class.getName(), @@ -90,6 +90,6 @@ private void check(AssertionError error) throws Exception { assertThat(error).isNotInstanceOfAny(ComparisonFailure.class, AssertionFailedError.class) .hasMessage(format("[Jedi] %n" + "expected: \"Yoda\"%n" + - "but was : \"Luke\"")); + " but was: \"Luke\"")); } } diff --git a/src/test/java/org/assertj/core/error/ShouldBeExactlyInstance_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeExactlyInstance_create_Test.java index 9c1349ceb7f..2305a99590f 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeExactlyInstance_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeExactlyInstance_create_Test.java @@ -39,7 +39,7 @@ void should_create_error_message() { String message = factory.create(new TestDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " \"Yoda%%s\"%n" + "to be exactly an instance of:%n" + " java.io.File%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldBeExecutable_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeExecutable_create_Test.java index efcffbd5c09..9fb85c26221 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeExecutable_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeExecutable_create_Test.java @@ -41,7 +41,7 @@ void should_create_error_message_for_File() { // WHEN String message = factory.create(TEST_DESCRIPTION, STANDARD_REPRESENTATION); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n xyz%nto be executable.", file)); + then(message).isEqualTo(format("[Test] %nExpecting actual:%n xyz%nto be executable.", file)); } @Test @@ -52,6 +52,6 @@ void should_create_error_message_for_Path() { // WHEN String message = factory.create(TEST_DESCRIPTION, STANDARD_REPRESENTATION); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n %s%nto be executable.", path)); + then(message).isEqualTo(format("[Test] %nExpecting actual:%n %s%nto be executable.", path)); } } diff --git a/src/test/java/org/assertj/core/error/ShouldBeFile_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeFile_create_Test.java index 159d77885f6..a9de9b19092 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeFile_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeFile_create_Test.java @@ -34,6 +34,6 @@ void should_create_error_message() { // WHEN String message = factory.create(new TestDescription("Test"), new StandardRepresentation()); // THEN - then(message).isEqualTo(String.format("[Test] %nExpecting:%n xyz%nto be a file")); + then(message).isEqualTo(String.format("[Test] %nExpecting actual:%n xyz%nto be a file")); } } diff --git a/src/test/java/org/assertj/core/error/ShouldBeGreaterOrEqual_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeGreaterOrEqual_create_Test.java index 0383e73fb77..9858575abff 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeGreaterOrEqual_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeGreaterOrEqual_create_Test.java @@ -39,7 +39,7 @@ void should_create_error_message() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(String.format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 6%n" + "to be greater than or equal to:%n" + " 8%n")); @@ -54,7 +54,7 @@ void should_create_error_message_with_custom_comparison_strategy() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(String.format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 6%n" + "to be greater than or equal to:%n" + " 8%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldBeGreater_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeGreater_create_Test.java index 8c38cb3a85e..e4869c0081f 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeGreater_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeGreater_create_Test.java @@ -39,7 +39,7 @@ void should_create_error_message() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 6%n" + "to be greater than:%n" + " 8%n")); @@ -53,7 +53,7 @@ void should_create_error_message_with_custom_comparison_strategy() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 6%n" + "to be greater than:%n" + " 8%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldBeInSameDay_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeInSameDay_create_Test.java index abe46075e87..970e048de45 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeInSameDay_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeInSameDay_create_Test.java @@ -37,7 +37,7 @@ void should_create_error_message() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2010-01-01T00:00:00.000 (java.util.Date)%n" + "to be on same year, month and day as:%n" + " 2010-01-25T00:00:00.000 (java.util.Date)")); diff --git a/src/test/java/org/assertj/core/error/ShouldBeInSameHourWindow_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeInSameHourWindow_create_Test.java index 9bc57d6389c..f06263d584c 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeInSameHourWindow_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeInSameHourWindow_create_Test.java @@ -40,7 +40,7 @@ void should_create_error_message() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2011-01-01T05:00:00.000 (java.util.Date)%n" + "to be close to:%n" + " 2011-01-01T06:05:17.003 (java.util.Date)%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldBeInSameHour_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeInSameHour_create_Test.java index 6dc8e915f8f..0336638a91f 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeInSameHour_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeInSameHour_create_Test.java @@ -31,7 +31,7 @@ void should_create_error_message() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2010-01-01T03:01:02.000 (java.util.Date)%n" + "to have same year, month, day and hour fields values as:%n" + " 2010-01-01T11:01:02.000 (java.util.Date)")); diff --git a/src/test/java/org/assertj/core/error/ShouldBeInSameMinuteWindow_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeInSameMinuteWindow_create_Test.java index d505e9c9a15..5e467d340e8 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeInSameMinuteWindow_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeInSameMinuteWindow_create_Test.java @@ -40,7 +40,7 @@ void should_create_error_message() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2011-01-01T05:00:00.000 (java.util.Date)%n" + "to be close to:%n" + " 2011-01-01T05:02:01.000 (java.util.Date)%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldBeInSameMinute_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeInSameMinute_create_Test.java index 986b373bdce..a72096f7e2b 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeInSameMinute_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeInSameMinute_create_Test.java @@ -31,7 +31,7 @@ void should_create_error_message() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2010-01-01T03:01:02.000 (java.util.Date)%n" + "to have same year, month, day, hour and minute fields values as:%n" + " 2010-01-01T03:11:02.000 (java.util.Date)")); diff --git a/src/test/java/org/assertj/core/error/ShouldBeInSameMonth_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeInSameMonth_create_Test.java index 9960ac0ff78..32d8d35fa81 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeInSameMonth_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeInSameMonth_create_Test.java @@ -38,7 +38,7 @@ void should_create_error_message() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2010-01-01T00:00:00.000 (java.util.Date)%n" + "to be on same year and month as:%n" + " 2010-02-01T00:00:00.000 (java.util.Date)")); diff --git a/src/test/java/org/assertj/core/error/ShouldBeInSameSecondWindow_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeInSameSecondWindow_create_Test.java index a05ba467dd0..68dc77b3663 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeInSameSecondWindow_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeInSameSecondWindow_create_Test.java @@ -40,7 +40,7 @@ void should_create_error_message() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2011-01-01T05:00:01.000 (java.util.Date)%n" + "to be close to:%n" + " 2011-01-01T05:00:02.001 (java.util.Date)%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldBeInSameSecond_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeInSameSecond_create_Test.java index 7151ab997f2..cbae6d317de 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeInSameSecond_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeInSameSecond_create_Test.java @@ -31,7 +31,7 @@ void should_create_error_message() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2010-01-01T03:01:02.000 (java.util.Date)%n" + "to have same year, month, day, hour, minute and second fields values as:%n" + " 2010-01-01T03:01:08.000 (java.util.Date)")); diff --git a/src/test/java/org/assertj/core/error/ShouldBeInSameYear_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeInSameYear_create_Test.java index 9f5c757827e..525e45e8118 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeInSameYear_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeInSameYear_create_Test.java @@ -38,7 +38,7 @@ void should_create_error_message() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2010-01-01T00:00:00.000 (java.util.Date)%n" + "to be on same year as:%n" + " 2011-01-01T00:00:00.000 (java.util.Date)")); diff --git a/src/test/java/org/assertj/core/error/ShouldBeIn_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeIn_create_Test.java index 65517f16bb0..35db51c81e3 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeIn_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeIn_create_Test.java @@ -40,7 +40,7 @@ void should_create_error_message() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " \"Yoda\"%n" + "to be in:%n" + " [\"Luke\", \"Leia\"]%n")); @@ -55,7 +55,7 @@ void should_create_error_message_with_custom_comparison_strategy() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " \"Yoda\"%n" + "to be in:%n" + " [\"Luke\", \"Leia\"]%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldBeInstanceOfAny_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeInstanceOfAny_create_Test.java index 79b2b9c5c39..0e4938f67ad 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeInstanceOfAny_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeInstanceOfAny_create_Test.java @@ -44,7 +44,7 @@ void should_create_error_message() { String message = factory.create(new TestDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " \"Yoda\"%n" + "to be an instance of any of:%n" + " [java.io.File, java.util.regex.Pattern]%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldBeInstance_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeInstance_create_Test.java index 7694c1329e3..59701e99b3c 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeInstance_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeInstance_create_Test.java @@ -40,7 +40,7 @@ void should_create_error_message() { String message = factory.create(new TestDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " \"Yoda\"%n" + "to be an instance of:%n" + " java.io.File%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldBeLessOrEqual_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeLessOrEqual_create_Test.java index cb736cbfaf9..8ef5f31e4b7 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeLessOrEqual_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeLessOrEqual_create_Test.java @@ -32,7 +32,7 @@ void should_create_error_message() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 8%n" + "to be less than or equal to:%n" + " 6 ")); @@ -46,7 +46,7 @@ void should_create_error_message_with_custom_comparison_strategy() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 8%n" + "to be less than or equal to:%n" + " 6 when comparing values using AbsValueComparator")); diff --git a/src/test/java/org/assertj/core/error/ShouldBeLess_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeLess_create_Test.java index 8b5c2652ff9..6ef57eb89fd 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeLess_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeLess_create_Test.java @@ -40,7 +40,7 @@ void should_create_error_message() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 8%n" + "to be less than:%n" + " 6 ")); @@ -54,7 +54,7 @@ void should_create_error_message_with_custom_comparison_strategy() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 8%n" + "to be less than:%n" + " 6 when comparing values using AbsValueComparator")); diff --git a/src/test/java/org/assertj/core/error/ShouldBeOfClassIn_Test.java b/src/test/java/org/assertj/core/error/ShouldBeOfClassIn_Test.java index d77b22f855e..11d211f4c22 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeOfClassIn_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeOfClassIn_Test.java @@ -37,6 +37,6 @@ void should_create_error_message() { // WHEN String message = factory.create(new TestDescription("Test"), new StandardRepresentation()); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n \"Yoda\"%nto be of one these types:%n [java.lang.Long, java.io.File]%nbut was:%n java.lang.String")); + then(message).isEqualTo(format("[Test] %nExpecting actual:%n \"Yoda\"%nto be of one these types:%n [java.lang.Long, java.io.File]%nbut was:%n java.lang.String")); } } diff --git a/src/test/java/org/assertj/core/error/ShouldBeSameGenericBetweenIterableAndCondition_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeSameGenericBetweenIterableAndCondition_create_Test.java index 229d0ca3d99..972dafd997c 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeSameGenericBetweenIterableAndCondition_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeSameGenericBetweenIterableAndCondition_create_Test.java @@ -38,7 +38,7 @@ void should_create_error_message() { // WHEN String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN - then(message).isEqualTo(format("[Test] %nExpecting: [\"Yoda\", \"Leia\"] to have the same generic type as condition Not a Jedi")); + then(message).isEqualTo(format("[Test] %nExpecting actual: [\"Yoda\", \"Leia\"] to have the same generic type as condition Not a Jedi")); } } diff --git a/src/test/java/org/assertj/core/error/ShouldBeSame_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeSame_create_Test.java index 46bab309892..c793a36e6f8 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeSame_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeSame_create_Test.java @@ -34,6 +34,6 @@ void should_create_error_message() { // WHEN String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n \"Luke\"%nand actual:%n \"Yoda\"%nto refer to the same object")); + then(message).isEqualTo(format("[Test] %nExpecting actual:%n \"Luke\"%nand actual:%n \"Yoda\"%nto refer to the same object")); } } diff --git a/src/test/java/org/assertj/core/error/ShouldBeSubstringOf_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBeSubstringOf_create_Test.java index c6501c387c1..43f35c1f46c 100644 --- a/src/test/java/org/assertj/core/error/ShouldBeSubstringOf_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBeSubstringOf_create_Test.java @@ -33,7 +33,7 @@ void should_create_error_message() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " \"bcd\"%n" + "to be a substring of:%n" + " \"abcdef\"%n")); @@ -48,7 +48,7 @@ void should_create_error_message_with_comparison_strategy() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " \"bcd\"%n" + "to be a substring of:%n" + " \"abcdef\"%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldBe_create_Test.java b/src/test/java/org/assertj/core/error/ShouldBe_create_Test.java index fc5640a935f..8879a8df5cc 100644 --- a/src/test/java/org/assertj/core/error/ShouldBe_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldBe_create_Test.java @@ -13,9 +13,12 @@ package org.assertj.core.error; import static java.lang.String.format; +import static org.assertj.core.api.Assertions.allOf; +import static org.assertj.core.api.Assertions.anyOf; import static org.assertj.core.api.BDDAssertions.then; import static org.assertj.core.error.ShouldBe.shouldBe; +import org.assertj.core.api.Condition; import org.assertj.core.api.TestCondition; import org.assertj.core.description.Description; import org.assertj.core.description.TextDescription; @@ -36,6 +39,157 @@ void should_create_error_message() { // WHEN String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n \"Yoda\"%nto be green")); + then(message).isEqualTo(format("[Test] %n" + + "Expecting actual:%n" + + " \"Yoda\"%n" + + "to be green")); } + + @Test + void should_create_error_message_for_allOf_condition() { + // GIVEN + TestCondition condition1 = new TestCondition<>("a Jedi"); + TestCondition condition2 = new TestCondition<>("very tall"); + TestCondition condition3 = new TestCondition<>("young"); + condition1.shouldMatch(true); + condition2.shouldMatch(false); + condition3.shouldMatch(false); + Condition allOf = allOf(condition1, condition2, condition3); + ErrorMessageFactory factory = shouldBe("Yoda", allOf); + // WHEN + String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); + // THEN + then(message).isEqualTo(format("[Test] %n" + + "Expecting actual:%n" + + " \"Yoda\"%n" + + "to be:%n" + + "[✗] all of:[%n" + + " [✓] a Jedi,%n" + + " [✗] very tall,%n" + + " [✗] young%n" + + "]")); + } + + @Test + void should_create_error_message_for_allOf_condition_single_failed_condition() { + // GIVEN + TestCondition condition1 = new TestCondition<>("a Jedi"); + TestCondition condition2 = new TestCondition<>("very tall"); + condition1.shouldMatch(true); + condition2.shouldMatch(false); + Condition allOf = allOf(condition1, condition2); + ErrorMessageFactory factory = shouldBe("Yoda", allOf); + // WHEN + String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); + // THEN + then(message).isEqualTo(format("[Test] %n" + + "Expecting actual:%n" + + " \"Yoda\"%n" + + "to be:%n" + + "[✗] all of:[%n" + + " [✓] a Jedi,%n" + + " [✗] very tall%n" + + "]")); + } + + @Test + void should_create_error_message_for_allOf_condition_with_all_nested_failed_conditions() { + // GIVEN + TestCondition condition1 = new TestCondition<>("a Sith"); + TestCondition condition2 = new TestCondition<>("very tall"); + TestCondition condition3 = new TestCondition<>("young"); + condition1.shouldMatch(false); + condition2.shouldMatch(false); + condition3.shouldMatch(false); + Condition allOf = allOf(condition1, + allOf(condition1, condition2), + anyOf(condition2, condition3)); + ErrorMessageFactory factory = shouldBe("Yoda", allOf); + // WHEN + String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); + // THEN + then(message).isEqualTo(format("[Test] %n" + + "Expecting actual:%n" + + " \"Yoda\"%n" + + "to be:%n" + + "[✗] all of:[%n" + + " [✗] a Sith,%n" + + " [✗] all of:[%n" + + " [✗] a Sith,%n" + + " [✗] very tall%n" + + " ],%n" + + " [✗] any of:[%n" + + " [✗] very tall,%n" + + " [✗] young%n" + + " ]%n" + + "]")); + } + + @Test + void should_create_error_message_reporting_which_allOf_nested_conditions_failed() { + // GIVEN + TestCondition condition1 = new TestCondition<>("a Jedi"); + TestCondition condition2 = new TestCondition<>("very tall"); + TestCondition condition3 = new TestCondition<>("very old"); + condition1.shouldMatch(true); + condition2.shouldMatch(false); + condition3.shouldMatch(true); + Condition allOf = allOf(condition1, + allOf(condition1, condition2), + anyOf(condition2, condition3)); + ErrorMessageFactory factory = shouldBe("Yoda", allOf); + // WHEN + String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); + // THEN + then(message).isEqualTo(format("[Test] %n" + + "Expecting actual:%n" + + " \"Yoda\"%n" + + "to be:%n" + + "[✗] all of:[%n" + + " [✓] a Jedi,%n" + + " [✗] all of:[%n" + + " [✓] a Jedi,%n" + + " [✗] very tall%n" + + " ],%n" + + " [✓] any of:[%n" + + " [✗] very tall,%n" + + " [✓] very old%n" + + " ]%n" + + "]")); + } + + @Test + void should_create_error_message_reporting_which_allOf_deep_nested_conditions_failed() { + // GIVEN + TestCondition condition1 = new TestCondition<>("a Jedi"); + TestCondition condition2 = new TestCondition<>("very tall"); + TestCondition condition3 = new TestCondition<>("old"); + condition1.shouldMatch(true); + condition2.shouldMatch(false); + condition3.shouldMatch(true); + Condition allOf = allOf(allOf(condition1, + allOf(condition1, + allOf(condition2, condition3)))); + ErrorMessageFactory factory = shouldBe("Yoda", allOf); + // WHEN + String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); + // THEN + then(message).isEqualTo(format("[Test] %n" + + "Expecting actual:%n" + + " \"Yoda\"%n" + + "to be:%n" + + "[✗] all of:[%n" + + " [✗] all of:[%n" + + " [✓] a Jedi,%n" + + " [✗] all of:[%n" + + " [✓] a Jedi,%n" + + " [✗] all of:[%n" + + " [✗] very tall,%n" + + " [✓] old%n" + + " ]%n" + + " ]%n" + + " ]%n" + + "]")); + } + } diff --git a/src/test/java/org/assertj/core/error/ShouldContainAnyOf_create_Test.java b/src/test/java/org/assertj/core/error/ShouldContainAnyOf_create_Test.java index 806720e14a1..ad68b9dc232 100644 --- a/src/test/java/org/assertj/core/error/ShouldContainAnyOf_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldContainAnyOf_create_Test.java @@ -33,7 +33,7 @@ void should_create_error_message() { String message = factory.create(new TextDescription("Test"), CONFIGURATION_PROVIDER.representation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " [\"Yoda\", \"Han\", \"Han\"]%n" + "to contain at least one of the following elements:%n" + " [\"Vador\", \"Leia\"]%n" + @@ -49,7 +49,7 @@ void should_create_error_message_with_custom_comparison_strategy() { String message = factory.create(new TextDescription("Test"), CONFIGURATION_PROVIDER.representation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " [\"Yoda\", \"Han\", \"Han\"]%n" + "to contain at least one of the following elements:%n" + " [\"Vador\", \"Leia\"]%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldContainAtIndex_create_Test.java b/src/test/java/org/assertj/core/error/ShouldContainAtIndex_create_Test.java index 4f85abfaec6..a0595d4f90d 100644 --- a/src/test/java/org/assertj/core/error/ShouldContainAtIndex_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldContainAtIndex_create_Test.java @@ -39,7 +39,7 @@ void should_create_error_message() { // WHEN String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n \"Leia\"%nat index 1 but found:%n \"Luke\"%nin:%n [\"Yoda\", \"Luke\"]%n")); + then(message).isEqualTo(format("[Test] %nExpecting actual:%n \"Leia\"%nat index 1 but found:%n \"Luke\"%nin:%n [\"Yoda\", \"Luke\"]%n")); } @Test @@ -50,7 +50,7 @@ void should_create_error_message_with_custom_comparison_strategy() { // WHEN String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n \"Leia\"%nat index 1 but found:%n \"Luke\"%nin:%n [\"Yoda\", \"Luke\"]%n" + then(message).isEqualTo(format("[Test] %nExpecting actual:%n \"Leia\"%nat index 1 but found:%n \"Luke\"%nin:%n [\"Yoda\", \"Luke\"]%n" + "when comparing values using CaseInsensitiveStringComparator")); } } diff --git a/src/test/java/org/assertj/core/error/ShouldContainCharSequenceOnlyOnce_create_Test.java b/src/test/java/org/assertj/core/error/ShouldContainCharSequenceOnlyOnce_create_Test.java index 112c56e4b82..d4db6c769dc 100644 --- a/src/test/java/org/assertj/core/error/ShouldContainCharSequenceOnlyOnce_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldContainCharSequenceOnlyOnce_create_Test.java @@ -40,7 +40,7 @@ void should_create_error_message_when_string_to_search_appears_several_times() { // WHEN String message = factoryWithSeveralOccurrences.create(new TestDescription("Test"), new StandardRepresentation()); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n \"motif\"%nto appear only once in:%n \"aaamotifmotifaabbbmotifaaa\"%nbut it appeared 3 times ")); + then(message).isEqualTo(format("[Test] %nExpecting actual:%n \"motif\"%nto appear only once in:%n \"aaamotifmotifaabbbmotifaaa\"%nbut it appeared 3 times ")); } @Test @@ -48,7 +48,7 @@ void should_create_error_message_when_string_to_search_does_not_appear() { // WHEN String message = factoryWithNoOccurrence.create(new TestDescription("Test"), new StandardRepresentation()); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n \"motif\"%nto appear only once in:%n \"aaamodifmoifaabbbmotfaaa\"%nbut it did not appear ")); + then(message).isEqualTo(format("[Test] %nExpecting actual:%n \"motif\"%nto appear only once in:%n \"aaamodifmoifaabbbmotfaaa\"%nbut it did not appear ")); } @Test @@ -59,7 +59,7 @@ void should_create_error_message_when_string_to_search_does_not_appear_with_cust // WHEN String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n \"MOtif\"%nto appear only once in:%n \"aaamoDifmoifaabbbmotfaaa\"%nbut it did not appear when comparing values using CaseInsensitiveStringComparator")); + then(message).isEqualTo(format("[Test] %nExpecting actual:%n \"MOtif\"%nto appear only once in:%n \"aaamoDifmoifaabbbmotfaaa\"%nbut it did not appear when comparing values using CaseInsensitiveStringComparator")); } @Test @@ -70,7 +70,7 @@ void should_create_error_message_when_string_to_search_appears_several_times_wit // WHEN String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n \"MOtif\"%nto appear only once in:%n \"aaamotIFmoTifaabbbmotifaaa\"%nbut it appeared 3 times when comparing values using CaseInsensitiveStringComparator")); + then(message).isEqualTo(format("[Test] %nExpecting actual:%n \"MOtif\"%nto appear only once in:%n \"aaamotIFmoTifaabbbmotifaaa\"%nbut it appeared 3 times when comparing values using CaseInsensitiveStringComparator")); } } diff --git a/src/test/java/org/assertj/core/error/ShouldContainCharSequence_create_Test.java b/src/test/java/org/assertj/core/error/ShouldContainCharSequence_create_Test.java index 5f5aea7c135..ef0b3df6484 100644 --- a/src/test/java/org/assertj/core/error/ShouldContainCharSequence_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldContainCharSequence_create_Test.java @@ -16,12 +16,14 @@ import static org.assertj.core.api.BDDAssertions.then; import static org.assertj.core.error.ShouldContainCharSequence.shouldContain; import static org.assertj.core.error.ShouldContainCharSequence.shouldContainIgnoringCase; +import static org.assertj.core.error.ShouldContainCharSequence.shouldContainIgnoringWhitespaces; +import static org.assertj.core.presentation.StandardRepresentation.STANDARD_REPRESENTATION; import static org.assertj.core.util.Arrays.array; import static org.mockito.internal.util.collections.Sets.newSet; import org.assertj.core.description.TextDescription; import org.assertj.core.internal.ComparatorBasedComparisonStrategy; -import org.assertj.core.presentation.StandardRepresentation; +import org.assertj.core.internal.StandardComparisonStrategy; import org.assertj.core.util.CaseInsensitiveStringComparator; import org.junit.jupiter.api.Test; @@ -39,9 +41,13 @@ void should_create_error_message() { // GIVEN ErrorMessageFactory factory = shouldContain("Yoda", "Luke"); // WHEN - String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); + String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n \"Yoda\"%nto contain:%n \"Luke\" ")); + then(message).isEqualTo(format("[Test] %n" + + "Expecting actual:%n" + + " \"Yoda\"%n" + + "to contain:%n" + + " \"Luke\" ")); } @Test @@ -50,9 +56,42 @@ void should_create_error_message_with_custom_comparison_strategy() { ErrorMessageFactory factory = shouldContain("Yoda", "Luke", new ComparatorBasedComparisonStrategy(CaseInsensitiveStringComparator.instance)); // WHEN - String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); + String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n \"Yoda\"%nto contain:%n \"Luke\" when comparing values using CaseInsensitiveStringComparator")); + then(message).isEqualTo(format("[Test] %n" + + "Expecting actual:%n" + + " \"Yoda\"%n" + + "to contain:%n" + + " \"Luke\" when comparing values using CaseInsensitiveStringComparator")); + } + + @Test + void should_create_error_message_when_ignoring_whitespaces() { + // GIVEN + ErrorMessageFactory factory = shouldContainIgnoringWhitespaces("Yoda", "Luke", StandardComparisonStrategy.instance()); + // WHEN + String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); + // THEN + then(message).isEqualTo(format("[Test] %n" + + "Expecting actual:%n" + + " \"Yoda\"%n" + + "to contain (ignoring whitespaces):%n" + + " \"Luke\" ")); + } + + @Test + void should_create_error_message_with_custom_comparison_strategy_when_ignoring_whitespaces() { + // GIVEN + ErrorMessageFactory factory = shouldContainIgnoringWhitespaces("Yoda", "Luke", + new ComparatorBasedComparisonStrategy(CaseInsensitiveStringComparator.instance)); + // WHEN + String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); + // THEN + then(message).isEqualTo(format("[Test] %n" + + "Expecting actual:%n" + + " \"Yoda\"%n" + + "to contain (ignoring whitespaces):%n" + + " \"Luke\" when comparing values using CaseInsensitiveStringComparator")); } @Test @@ -60,9 +99,14 @@ void should_create_error_message_when_ignoring_case() { // GIVEN ErrorMessageFactory factory = shouldContainIgnoringCase("Yoda", "Luke"); // WHEN - String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); + String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n \"Yoda\"%nto contain:%n \"Luke\"%n (ignoring case)")); + then(message).isEqualTo(format("[Test] %n" + + "Expecting actual:%n" + + " \"Yoda\"%n" + + "to contain:%n" + + " \"Luke\"%n" + + " (ignoring case)")); } @Test @@ -71,9 +115,33 @@ void should_create_error_message_with_several_CharSequence_values() { CharSequence[] charSequences = array("Luke", "Vador", "Solo"); ErrorMessageFactory factory = shouldContain("Yoda, Luke", charSequences, newSet("Vador", "Solo")); // WHEN - String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); + String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); + // THEN + then(message).isEqualTo(format("[Test] %n" + + "Expecting actual:%n" + + " \"Yoda, Luke\"%n" + + "to contain:%n" + + " [\"Luke\", \"Vador\", \"Solo\"]%n" + + "but could not find:%n" + + " [\"Vador\", \"Solo\"]%n ")); + } + + @Test + void should_create_error_message_with_several_CharSequence_values_when_ignoring_whitespaces() { + // GIVEN + CharSequence[] charSequences = array("Luke", "Vador", "Solo"); + ErrorMessageFactory factory = shouldContainIgnoringWhitespaces("Yoda, Luke", charSequences, newSet("Vador", "Solo"), + StandardComparisonStrategy.instance()); + // WHEN + String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n \"Yoda, Luke\"%nto contain:%n [\"Luke\", \"Vador\", \"Solo\"]%nbut could not find:%n [\"Vador\", \"Solo\"]%n ")); + then(message).isEqualTo(format("[Test] %n" + + "Expecting actual:%n" + + " \"Yoda, Luke\"%n" + + "to contain (ignoring whitespaces):%n" + + " [\"Luke\", \"Vador\", \"Solo\"]%n" + + "but could not find:%n" + + " [\"Vador\", \"Solo\"]%n ")); } } diff --git a/src/test/java/org/assertj/core/error/ShouldContainEntry_create_Test.java b/src/test/java/org/assertj/core/error/ShouldContainEntry_create_Test.java index 334bef0cd26..cbaeb8ec65e 100644 --- a/src/test/java/org/assertj/core/error/ShouldContainEntry_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldContainEntry_create_Test.java @@ -40,7 +40,7 @@ void should_create_error_message_with_entry_condition() { String message = factory.create(new TextDescription("Test"), CONFIGURATION_PROVIDER.representation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " {\"color\"=\"green\", \"name\"=\"Yoda\"}%n" + "to contain an entry satisfying:%n" + " test condition")); @@ -56,7 +56,7 @@ void should_create_error_message_with_key_and_value_conditions() { String message = factory.create(new TextDescription("Test"), CONFIGURATION_PROVIDER.representation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " {\"color\"=\"green\", \"name\"=\"Yoda\"}%n" + "to contain an entry satisfying both key and value conditions:%n" + "- key condition:%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldContainExactlyInAnyOrder_create_Test.java b/src/test/java/org/assertj/core/error/ShouldContainExactlyInAnyOrder_create_Test.java index a447579e65d..d53ef40fd4d 100644 --- a/src/test/java/org/assertj/core/error/ShouldContainExactlyInAnyOrder_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldContainExactlyInAnyOrder_create_Test.java @@ -51,7 +51,7 @@ void should_create_error_message_with_custom_comparison_strategy() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" - + "Expecting:%n" + + "Expecting actual:%n" + " [\"Yoda\", \"Han\"]%n" + "to contain exactly in any order:%n" + " [\"Luke\", \"Yoda\"]%n" @@ -74,7 +74,7 @@ void should_not_display_unexpected_elements_when_there_are_none_with_custom_comp String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" - + "Expecting:%n" + + "Expecting actual:%n" + " [\"Yoda\"]%n" + "to contain exactly in any order:%n" + " [\"Luke\", \"Yoda\"]%n" @@ -95,7 +95,7 @@ void should_not_display_elements_not_found_when_there_are_none_with_custom_compa String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" - + "Expecting:%n" + + "Expecting actual:%n" + " [\"Yoda\", \"Leia\"]%n" + "to contain exactly in any order:%n" + " [\"Yoda\"]%n" diff --git a/src/test/java/org/assertj/core/error/ShouldContainExactly_create_Test.java b/src/test/java/org/assertj/core/error/ShouldContainExactly_create_Test.java index ee7c30b3fcf..ca0f87d1308 100644 --- a/src/test/java/org/assertj/core/error/ShouldContainExactly_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldContainExactly_create_Test.java @@ -39,7 +39,7 @@ void should_display_missing_and_unexpected_elements() { String message = factory.create(new TextDescription("Test")); // THEN then(message).isEqualTo(format("[Test] %n" - + "Expecting:%n" + + "Expecting actual:%n" + " [\"Yoda\", \"Han\"]%n" + "to contain exactly (and in same order):%n" + " [\"Luke\", \"Yoda\"]%n" @@ -58,7 +58,7 @@ void should_not_display_missing_elements_when_there_are_none() { String message = factory.create(new TextDescription("Test")); // THEN then(message).isEqualTo(format("[Test] %n" - + "Expecting:%n" + + "Expecting actual:%n" + " [\"Yoda\", \"Han\"]%n" + "to contain exactly (and in same order):%n" + " [\"Yoda\"]%n" @@ -75,7 +75,7 @@ void should_not_display_unexpected_elements_when_there_are_none() { String message = factory.create(new TextDescription("Test")); // THEN then(message).isEqualTo(format("[Test] %n" - + "Expecting:%n" + + "Expecting actual:%n" + " [\"Yoda\"]%n" + "to contain exactly (and in same order):%n" + " [\"Luke\", \"Yoda\"]%n" @@ -112,7 +112,7 @@ void should_display_missing_and_unexpected_elements_with_custom_comparison_strat String message = factory.create(new TextDescription("Test")); // THEN then(message).isEqualTo(format("[Test] %n" - + "Expecting:%n" + + "Expecting actual:%n" + " [\"Yoda\", \"Han\"]%n" + "to contain exactly (and in same order):%n" + " [\"Luke\", \"Yoda\"]%n" @@ -149,7 +149,7 @@ void should_not_display_unexpected_elements_when_there_are_none_with_custom_comp String message = factory.create(new TextDescription("Test")); // THEN then(message).isEqualTo(format("[Test] %n" - + "Expecting:%n" + + "Expecting actual:%n" + " [\"Yoda\"]%n" + "to contain exactly (and in same order):%n" + " [\"Luke\", \"Yoda\"]%n" @@ -168,7 +168,7 @@ void should_not_display_missing_elements_when_there_are_none_with_custom_compari String message = factory.create(new TextDescription("Test")); // THEN then(message).isEqualTo(format("[Test] %n" - + "Expecting:%n" + + "Expecting actual:%n" + " [\"Yoda\", \"Han\"]%n" + "to contain exactly (and in same order):%n" + " [\"Yoda\"]%n" diff --git a/src/test/java/org/assertj/core/error/ShouldContainKey_create_Test.java b/src/test/java/org/assertj/core/error/ShouldContainKey_create_Test.java index a9c4a87e9d4..61940941e26 100644 --- a/src/test/java/org/assertj/core/error/ShouldContainKey_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldContainKey_create_Test.java @@ -40,7 +40,7 @@ void should_create_error_message_with_key_condition() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " {\"color\"=\"green\", \"name\"=\"Yoda\"}%n" + "to contain a key satisfying:%n" + " test condition")); diff --git a/src/test/java/org/assertj/core/error/ShouldContainKeys_create_Test.java b/src/test/java/org/assertj/core/error/ShouldContainKeys_create_Test.java index 2cfd726d5cd..ff55a69fac1 100644 --- a/src/test/java/org/assertj/core/error/ShouldContainKeys_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldContainKeys_create_Test.java @@ -42,7 +42,7 @@ void should_create_error_message() { // WHEN String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN - then(message).isEqualTo(String.format("[Test] %nExpecting:%n {\"color\"=\"green\", \"name\"=\"Yoda\"}%nto contain key:%n \"name\"")); + then(message).isEqualTo(String.format("[Test] %nExpecting actual:%n {\"color\"=\"green\", \"name\"=\"Yoda\"}%nto contain key:%n \"name\"")); } @Test @@ -53,6 +53,6 @@ void should_create_error_message_with_multiple_keys() { // WHEN String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN - then(message).isEqualTo(String.format("[Test] %nExpecting:%n {\"color\"=\"green\", \"name\"=\"Yoda\"}%nto contain keys:%n [\"name\", \"color\"]")); + then(message).isEqualTo(String.format("[Test] %nExpecting actual:%n {\"color\"=\"green\", \"name\"=\"Yoda\"}%nto contain keys:%n [\"name\", \"color\"]")); } } diff --git a/src/test/java/org/assertj/core/error/ShouldContainNull_create_Test.java b/src/test/java/org/assertj/core/error/ShouldContainNull_create_Test.java index dc829e5fff4..e0329d6e935 100644 --- a/src/test/java/org/assertj/core/error/ShouldContainNull_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldContainNull_create_Test.java @@ -30,7 +30,7 @@ void should_create_error_message() { // WHEN String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN - then(message).isEqualTo(String.format("[Test] %nExpecting:%n [\"Luke\", \"Yoda\"]%nto contain a null element")); + then(message).isEqualTo(String.format("[Test] %nExpecting actual:%n [\"Luke\", \"Yoda\"]%nto contain a null element")); } } diff --git a/src/test/java/org/assertj/core/error/ShouldContainOnlyDigits_create_Test.java b/src/test/java/org/assertj/core/error/ShouldContainOnlyDigits_create_Test.java index fa0afed6f89..3ad90a105c1 100644 --- a/src/test/java/org/assertj/core/error/ShouldContainOnlyDigits_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldContainOnlyDigits_create_Test.java @@ -33,7 +33,7 @@ void should_create_error_message() { String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " \"10$\"%n" + "to contain only digits%n" + "but found non-digit character '$' at index <2>")); @@ -47,7 +47,7 @@ void should_create_error_message_for_empty_string() { String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " \"\"%n" + "to contain only digits%n" + "but could not found any digits at all")); diff --git a/src/test/java/org/assertj/core/error/ShouldContainOnlyKeys_create_Test.java b/src/test/java/org/assertj/core/error/ShouldContainOnlyKeys_create_Test.java index 58fa6631313..aa8f1e06313 100644 --- a/src/test/java/org/assertj/core/error/ShouldContainOnlyKeys_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldContainOnlyKeys_create_Test.java @@ -43,7 +43,7 @@ void should_create_error_message() { String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(String.format("[Test] %n" - + "Expecting:%n" + + "Expecting actual:%n" + " {\"color\"=\"green\", \"name\"=\"Yoda\"}%n" + "to contain only following keys:%n" + " [\"jedi\", \"color\"]%n" @@ -63,7 +63,7 @@ void should_not_display_unexpected_elements_when_there_are_none() { String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(String.format("[Test] %n" - + "Expecting:%n" + + "Expecting actual:%n" + " {\"color\"=\"green\"}%n" + "to contain only following keys:%n" + " [\"jedi\", \"color\"]%n" diff --git a/src/test/java/org/assertj/core/error/ShouldContainOnlyNulls_create_Test.java b/src/test/java/org/assertj/core/error/ShouldContainOnlyNulls_create_Test.java index ff88bf36954..54b7694516f 100644 --- a/src/test/java/org/assertj/core/error/ShouldContainOnlyNulls_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldContainOnlyNulls_create_Test.java @@ -36,7 +36,7 @@ void should_create_error_message_with_unexpected_element() { String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" - + "Expecting:%n" + + "Expecting actual:%n" + " [\"person\", null]%n" + "to contain only null elements but some elements were not:%n" + " [\"person\"]")); @@ -50,7 +50,7 @@ void should_create_error_message_with_no_any_element() { String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" - + "Expecting:%n" + + "Expecting actual:%n" + " []%n" + "to contain only null elements but it was empty")); } diff --git a/src/test/java/org/assertj/core/error/ShouldContainPattern_create_Test.java b/src/test/java/org/assertj/core/error/ShouldContainPattern_create_Test.java index 94828a302c6..b6292fa0fa2 100644 --- a/src/test/java/org/assertj/core/error/ShouldContainPattern_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldContainPattern_create_Test.java @@ -29,7 +29,7 @@ void should_create_error_message() { // WHEN String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n \"Frodo\"%nto contain pattern:%n \".*Orc.*\"")); + then(message).isEqualTo(format("[Test] %nExpecting actual:%n \"Frodo\"%nto contain pattern:%n \".*Orc.*\"")); } } diff --git a/src/test/java/org/assertj/core/error/ShouldContainSequenceOfCharSequence_create_Test.java b/src/test/java/org/assertj/core/error/ShouldContainSequenceOfCharSequence_create_Test.java index 445323e6f2b..9c60bc6016c 100644 --- a/src/test/java/org/assertj/core/error/ShouldContainSequenceOfCharSequence_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldContainSequenceOfCharSequence_create_Test.java @@ -37,7 +37,7 @@ void should_create_error_message() { // WHEN String message = shouldContainSequence(actual, sequenceValues).create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n" + + then(message).isEqualTo(format("[Test] %nExpecting actual:%n" + " \"{ 'title':'A Game of Thrones', 'author':'George Martin'}\"%n" + "to contain sequence:%n" + " [\"{\", \"author\", \"title\", \"}\"]%n")); @@ -53,7 +53,7 @@ void should_create_error_message_with_custom_comparison_strategy() { // WHEN String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n" + + then(message).isEqualTo(format("[Test] %nExpecting actual:%n" + " \"{ 'title':'A Game of Thrones', 'author':'George Martin'}\"%n" + "to contain sequence:%n" + " [\"{\", \"author\", \"title\", \"}\"]%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldContainSequence_create_Test.java b/src/test/java/org/assertj/core/error/ShouldContainSequence_create_Test.java index a3352438a71..8e60c55a9c0 100644 --- a/src/test/java/org/assertj/core/error/ShouldContainSequence_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldContainSequence_create_Test.java @@ -39,7 +39,7 @@ void should_create_error_message() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " [\"Yoda\", \"Luke\"]%n" + "to contain sequence:%n" + " [\"Han\", \"Leia\"]%n")); @@ -54,7 +54,7 @@ void should_create_error_message_with_custom_comparison_strategy() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " [\"Yoda\", \"Luke\"]%n" + "to contain sequence:%n" + " [\"Han\", \"Leia\"]%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldContainSubsequenceOfCharSequence_create_Test.java b/src/test/java/org/assertj/core/error/ShouldContainSubsequenceOfCharSequence_create_Test.java index 16e904c7105..1a04be8ef56 100644 --- a/src/test/java/org/assertj/core/error/ShouldContainSubsequenceOfCharSequence_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldContainSubsequenceOfCharSequence_create_Test.java @@ -38,7 +38,7 @@ void should_create_error_message() { // WHEN String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n" + + then(message).isEqualTo(format("[Test] %nExpecting actual:%n" + " \"" + actual + "\"%n" + "to contain the following CharSequences in this order:%n" + " [\"{\", \"author\", \"title\", \"}\"]%n" + @@ -55,7 +55,7 @@ void should_create_error_message_with_custom_comparison_strategy() { // WHEN String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n" + + then(message).isEqualTo(format("[Test] %nExpecting actual:%n" + " \"" + actual + "\"%n" + "to contain the following CharSequences in this order:%n" + " [\"{\", \"author\", \"title\", \"}\"]%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldContainSubsequence_create_Test.java b/src/test/java/org/assertj/core/error/ShouldContainSubsequence_create_Test.java index 40ee373d7e5..0665e646028 100644 --- a/src/test/java/org/assertj/core/error/ShouldContainSubsequence_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldContainSubsequence_create_Test.java @@ -37,7 +37,7 @@ void should_create_error_message() { // WHEN String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n [\"Yoda\", \"Luke\"]%nto contain subsequence:%n [\"Han\", \"Leia\"]%n")); + then(message).isEqualTo(format("[Test] %nExpecting actual:%n [\"Yoda\", \"Luke\"]%nto contain subsequence:%n [\"Han\", \"Leia\"]%n")); } @Test @@ -48,7 +48,7 @@ void should_create_error_message_with_custom_comparison_strategy() { // WHEN String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n [\"Yoda\", \"Luke\"]%nto contain subsequence:%n [\"Han\", \"Leia\"]%n" + then(message).isEqualTo(format("[Test] %nExpecting actual:%n [\"Yoda\", \"Luke\"]%nto contain subsequence:%n [\"Han\", \"Leia\"]%n" + "when comparing values using CaseInsensitiveStringComparator")); } } diff --git a/src/test/java/org/assertj/core/error/ShouldContainValue_create_Test.java b/src/test/java/org/assertj/core/error/ShouldContainValue_create_Test.java index 211125cb8aa..c4c3a08ef1a 100644 --- a/src/test/java/org/assertj/core/error/ShouldContainValue_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldContainValue_create_Test.java @@ -43,7 +43,7 @@ void should_create_error_message() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " {\"color\"=\"green\", \"name\"=\"Yoda\"}%n" + "to contain value:%n" + " \"VeryOld\"")); @@ -58,7 +58,7 @@ void should_create_error_message_with_value_condition() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " {\"color\"=\"green\", \"name\"=\"Yoda\"}%n" + "to contain a value satisfying:%n" + " test condition")); diff --git a/src/test/java/org/assertj/core/error/ShouldContainValues_create_Test.java b/src/test/java/org/assertj/core/error/ShouldContainValues_create_Test.java index 0e715af697f..c75d9611bf7 100644 --- a/src/test/java/org/assertj/core/error/ShouldContainValues_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldContainValues_create_Test.java @@ -34,7 +34,7 @@ void should_create_error_message_with_multiple_values() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(String.format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " {\"color\"=\"green\", \"name\"=\"Yoda\"}%n" + "to contain values:%n" + " [\"VeryOld\", \"Vader\"]")); @@ -49,7 +49,7 @@ void should_create_error_message_with_single_value() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(String.format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " {\"color\"=\"green\", \"name\"=\"Yoda\"}%n" + "to contain value:%n" + " \"VeryOld\"")); diff --git a/src/test/java/org/assertj/core/error/ShouldContainsOnlyOnce_create_Test.java b/src/test/java/org/assertj/core/error/ShouldContainsOnlyOnce_create_Test.java index 32bfe31a5e8..c321380461e 100644 --- a/src/test/java/org/assertj/core/error/ShouldContainsOnlyOnce_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldContainsOnlyOnce_create_Test.java @@ -45,7 +45,7 @@ void should_create_error_message() { // WHEN String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n" + + then(message).isEqualTo(format("[Test] %nExpecting actual:%n" + " [\"Yoda\", \"Han\", \"Han\"]%n" + "to contain only once:%n" + " [\"Luke\", \"Yoda\"]%n" + @@ -65,7 +65,7 @@ void should_create_error_message_with_custom_comparison_strategy() { String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " [\"Yoda\", \"Han\"]%n" + "to contain only once:%n" + " [\"Luke\", \"Yoda\"]%n" + @@ -83,7 +83,7 @@ void should_create_error_message_without_not_found_elements() { // WHEN String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n" + + then(message).isEqualTo(format("[Test] %nExpecting actual:%n" + " [\"Yoda\", \"Han\", \"Han\"]%n" + "to contain only once:%n" + " [\"Yoda\"]%n" + @@ -98,7 +98,7 @@ void should_create_error_message_without_elements_found_many_times() { // WHEN String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n" + + then(message).isEqualTo(format("[Test] %nExpecting actual:%n" + " [\"Yoda\", \"Han\"]%n" + "to contain only once:%n" + " [\"Luke\"]%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldEndWith_create_Test.java b/src/test/java/org/assertj/core/error/ShouldEndWith_create_Test.java index 54eb0b75d08..b7875801e0f 100644 --- a/src/test/java/org/assertj/core/error/ShouldEndWith_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldEndWith_create_Test.java @@ -38,7 +38,7 @@ void should_create_error_message() { // WHEN String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n [\"Yoda\", \"Luke\"]%nto end with:%n [\"Han\", \"Leia\"]%n")); + then(message).isEqualTo(format("[Test] %nExpecting actual:%n [\"Yoda\", \"Luke\"]%nto end with:%n [\"Han\", \"Leia\"]%n")); } @Test @@ -49,7 +49,7 @@ void should_create_error_message_with_custom_comparison_strategy() { // WHEN String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN - then(message).isEqualTo(String.format("[Test] %nExpecting:%n [\"Yoda\", \"Luke\"]%nto end with:%n [\"Han\", \"Leia\"]%n" + then(message).isEqualTo(String.format("[Test] %nExpecting actual:%n [\"Yoda\", \"Luke\"]%nto end with:%n [\"Han\", \"Leia\"]%n" + "when comparing values using CaseInsensitiveStringComparator")); } } diff --git a/src/test/java/org/assertj/core/error/ShouldHaveAtIndex_create_Test.java b/src/test/java/org/assertj/core/error/ShouldHaveAtIndex_create_Test.java index d0fdf761c5c..756ebc96e68 100644 --- a/src/test/java/org/assertj/core/error/ShouldHaveAtIndex_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldHaveAtIndex_create_Test.java @@ -38,6 +38,6 @@ void should_create_error_message() { // WHEN String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n \"Luke\"%nat index 1 to have:%n red lightsaber%nin:%n [\"Yoda\", \"Luke\"]%n")); + then(message).isEqualTo(format("[Test] %nExpecting actual:%n \"Luke\"%nat index 1 to have:%n red lightsaber%nin:%n [\"Yoda\", \"Luke\"]%n")); } } diff --git a/src/test/java/org/assertj/core/error/ShouldHaveAtLeastOneElementOfType_create_Test.java b/src/test/java/org/assertj/core/error/ShouldHaveAtLeastOneElementOfType_create_Test.java index c02225aa7c6..6bf23fa3e77 100644 --- a/src/test/java/org/assertj/core/error/ShouldHaveAtLeastOneElementOfType_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldHaveAtLeastOneElementOfType_create_Test.java @@ -34,7 +34,7 @@ void should_create_error_message_for_iterable() { String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(String.format("[Test] %n" - + "Expecting:%n" + + "Expecting actual:%n" + " [\"Yoda\", \"Luke\"]%n" + "to have at least one element of type:%n" + " java.lang.Long%n" @@ -49,7 +49,7 @@ void should_create_error_message_for_array() { String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(String.format("[Test] %n" - + "Expecting:%n" + + "Expecting actual:%n" + " [\"Yoda\", \"Luke\"]%n" + "to have at least one element of type:%n" + " java.lang.Long%n" diff --git a/src/test/java/org/assertj/core/error/ShouldHaveDateField_create_Test.java b/src/test/java/org/assertj/core/error/ShouldHaveDateField_create_Test.java index 6732be5e618..e587a06e7c9 100644 --- a/src/test/java/org/assertj/core/error/ShouldHaveDateField_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldHaveDateField_create_Test.java @@ -34,7 +34,7 @@ void should_create_error_message_for_fields() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2015-12-31T00:00:00.000 (java.util.Date)%n" + "to be on \"month\" 10")); } diff --git a/src/test/java/org/assertj/core/error/ShouldHaveExactlyTypes_create_Test.java b/src/test/java/org/assertj/core/error/ShouldHaveExactlyTypes_create_Test.java new file mode 100644 index 00000000000..facb1df1f33 --- /dev/null +++ b/src/test/java/org/assertj/core/error/ShouldHaveExactlyTypes_create_Test.java @@ -0,0 +1,98 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.error; + +import static java.lang.String.format; +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.error.ShouldHaveExactlyTypes.elementsTypesDifferAtIndex; +import static org.assertj.core.error.ShouldHaveExactlyTypes.shouldHaveTypes; +import static org.assertj.core.util.Lists.list; + +import org.assertj.core.description.TextDescription; +import org.junit.jupiter.api.Test; + +class ShouldHaveExactlyTypes_create_Test { + + @Test + void should_display_missing_and_unexpected_elements_types() { + // GIVEN + ErrorMessageFactory factory = shouldHaveTypes(list("Yoda", 123), + list(String.class, Double.class), + list(Double.class), + list(Integer.class)); + // WHEN + String message = factory.create(new TextDescription("Test")); + // THEN + then(message).isEqualTo(format("[Test] %n" + + "Expecting actual elements:%n" + + " [\"Yoda\", 123]%n" + + "to have the following types (in this order):%n" + + " [java.lang.String, java.lang.Double]%n" + + "but there were no actual elements with these types:%n" + + " [java.lang.Double]%n" + + "and these actual elements types were not expected:%n" + + " [java.lang.Integer]")); + } + + @Test + void should_not_display_missing_elements_types_when_there_are_none() { + // GIVEN + ErrorMessageFactory factory = shouldHaveTypes(list("Yoda", 123), + list(String.class, String.class), + list(), + list(Integer.class)); + // WHEN + String message = factory.create(new TextDescription("Test")); + // THEN + then(message).isEqualTo(format("[Test] %n" + + "Expecting actual elements:%n" + + " [\"Yoda\", 123]%n" + + "to have the following types (in this order):%n" + + " [java.lang.String, java.lang.String]%n" + + "but these actual elements types were not expected:%n" + + " [java.lang.Integer]")); + } + + @Test + void should_not_display_unexpected_elements_types_when_there_are_none() { + // GIVEN + ErrorMessageFactory factory = shouldHaveTypes(list("Yoda", 123, 456), + list(String.class, Integer.class, Double.class), + list(Double.class), + list()); + // WHEN + String message = factory.create(new TextDescription("Test")); + // THEN + then(message).isEqualTo(format("[Test] %n" + + "Expecting actual elements:%n" + + " [\"Yoda\", 123, 456]%n" + + "to have the following types (in this order):%n" + + " [java.lang.String, java.lang.Integer, java.lang.Double]%n" + + "but there were no actual elements with these types:%n" + + " [java.lang.Double]")); + } + + @Test + void should_display_first_wrong_element_type_when_only_elements_types_order_differs() { + // GIVEN + ErrorMessageFactory factory = elementsTypesDifferAtIndex("Luke", Double.class, 1); + // WHEN + String message = factory.create(new TextDescription("Test")); + // THEN + then(message).isEqualTo(format("[Test] %n" + + "actual element at index 1 does not have the expected type, element was:\"Luke\"%n" + + "actual element type: java.lang.String%n" + + "expected type : java.lang.Double")); + } + +} diff --git a/src/test/java/org/assertj/core/error/ShouldHaveOnlyElementsOfType_create_Test.java b/src/test/java/org/assertj/core/error/ShouldHaveOnlyElementsOfType_create_Test.java index 90a7ca77823..7e950e9d0b4 100644 --- a/src/test/java/org/assertj/core/error/ShouldHaveOnlyElementsOfType_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldHaveOnlyElementsOfType_create_Test.java @@ -37,7 +37,7 @@ void should_create_error_message_for_iterable() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" - + "Expecting:%n" + + "Expecting actual:%n" + " [\"Yoda\", 5L]%n" + "to only have elements of type:%n" + " java.lang.String%n" @@ -54,7 +54,7 @@ void should_create_error_message_for_array() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" - + "Expecting:%n" + + "Expecting actual:%n" + " [\"Yoda\", 5L]%n" + "to only have elements of type:%n" + " java.lang.String%n" diff --git a/src/test/java/org/assertj/core/error/ShouldHaveSameHourAs_create_Test.java b/src/test/java/org/assertj/core/error/ShouldHaveSameHourAs_create_Test.java index de9f92b4070..cfdb836cc4b 100644 --- a/src/test/java/org/assertj/core/error/ShouldHaveSameHourAs_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldHaveSameHourAs_create_Test.java @@ -38,7 +38,7 @@ void should_create_error_message_localtime() { // WHEN String errorMessage = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN - then(errorMessage).isEqualTo(format("[Test] %nExpecting:%n 12:00%nto have same hour as:%n 13:00%nbut had not.")); + then(errorMessage).isEqualTo(format("[Test] %nExpecting actual:%n 12:00%nto have same hour as:%n 13:00%nbut had not.")); } @Test @@ -49,6 +49,6 @@ void should_create_error_message_offset() { // WHEN String errorMessage = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN - then(errorMessage).isEqualTo(format("[Test] %nExpecting:%n 12:00Z%nto have same hour as:%n 13:00Z%nbut had not.")); + then(errorMessage).isEqualTo(format("[Test] %nExpecting actual:%n 12:00Z%nto have same hour as:%n 13:00Z%nbut had not.")); } } diff --git a/src/test/java/org/assertj/core/error/ShouldHaveSuppressedException_create_Test.java b/src/test/java/org/assertj/core/error/ShouldHaveSuppressedException_create_Test.java index c00c2e21572..edb59c3b38e 100644 --- a/src/test/java/org/assertj/core/error/ShouldHaveSuppressedException_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldHaveSuppressedException_create_Test.java @@ -37,7 +37,7 @@ void should_create_error_message() { String message = factory.create(new TextDescription("Test"), CONFIGURATION_PROVIDER.representation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %s%n" + "to have a suppressed exception with the following type and message:%n" + " \"java.lang.IllegalArgumentException\" / \"foo\"%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldHave_create_Test.java b/src/test/java/org/assertj/core/error/ShouldHave_create_Test.java index 598636b225f..599030b1849 100644 --- a/src/test/java/org/assertj/core/error/ShouldHave_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldHave_create_Test.java @@ -13,9 +13,12 @@ package org.assertj.core.error; import static java.lang.String.format; +import static org.assertj.core.api.Assertions.allOf; +import static org.assertj.core.api.Assertions.anyOf; import static org.assertj.core.api.BDDAssertions.then; import static org.assertj.core.error.ShouldHave.shouldHave; +import org.assertj.core.api.Condition; import org.assertj.core.api.TestCondition; import org.assertj.core.description.TextDescription; import org.assertj.core.presentation.StandardRepresentation; @@ -35,6 +38,157 @@ void should_create_error_message() { // WHEN String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n \"Yoda\"%nto have:%n green lightsaber")); + then(message).isEqualTo(format("[Test] %n" + + "Expecting actual:%n" + + " \"Yoda\"%n" + + "to have green lightsaber")); } + + @Test + void should_create_error_message_for_allOf_condition() { + // GIVEN + TestCondition condition1 = new TestCondition<>("jedi power"); + TestCondition condition2 = new TestCondition<>("sith power"); + TestCondition condition3 = new TestCondition<>("a short life"); + condition1.shouldMatch(true); + condition2.shouldMatch(false); + condition3.shouldMatch(false); + Condition allOf = allOf(condition1, condition2, condition3); + ErrorMessageFactory factory = shouldHave("Yoda", allOf); + // WHEN + String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); + // THEN + then(message).isEqualTo(format("[Test] %n" + + "Expecting actual:%n" + + " \"Yoda\"%n" + + "to have:%n" + + "[✗] all of:[%n" + + " [✓] jedi power,%n" + + " [✗] sith power,%n" + + " [✗] a short life%n" + + "]")); + } + + @Test + void should_create_error_message_for_allOf_condition_single_failed_condition() { + // GIVEN + TestCondition condition1 = new TestCondition<>("jedi power"); + TestCondition condition2 = new TestCondition<>("sith power"); + condition1.shouldMatch(true); + condition2.shouldMatch(false); + Condition allOf = allOf(condition1, condition2); + ErrorMessageFactory factory = shouldHave("Yoda", allOf); + // WHEN + String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); + // THEN + then(message).isEqualTo(format("[Test] %n" + + "Expecting actual:%n" + + " \"Yoda\"%n" + + "to have:%n" + + "[✗] all of:[%n" + + " [✓] jedi power,%n" + + " [✗] sith power%n" + + "]")); + } + + @Test + void should_create_error_message_for_allOf_condition_with_all_nested_failed_conditions() { + // GIVEN + TestCondition condition1 = new TestCondition<>("a Sith"); + TestCondition condition2 = new TestCondition<>("sith power"); + TestCondition condition3 = new TestCondition<>("a short life"); + condition1.shouldMatch(false); + condition2.shouldMatch(false); + condition3.shouldMatch(false); + Condition allOf = allOf(condition1, + allOf(condition1, condition2), + anyOf(condition2, condition3)); + ErrorMessageFactory factory = shouldHave("Yoda", allOf); + // WHEN + String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); + // THEN + then(message).isEqualTo(format("[Test] %n" + + "Expecting actual:%n" + + " \"Yoda\"%n" + + "to have:%n" + + "[✗] all of:[%n" + + " [✗] a Sith,%n" + + " [✗] all of:[%n" + + " [✗] a Sith,%n" + + " [✗] sith power%n" + + " ],%n" + + " [✗] any of:[%n" + + " [✗] sith power,%n" + + " [✗] a short life%n" + + " ]%n" + + "]")); + } + + @Test + void should_create_error_message_reporting_which_allOf_nested_conditions_failed() { + // GIVEN + TestCondition condition1 = new TestCondition<>("jedi power"); + TestCondition condition2 = new TestCondition<>("sith power"); + TestCondition condition3 = new TestCondition<>("long life"); + condition1.shouldMatch(true); + condition2.shouldMatch(false); + condition3.shouldMatch(true); + Condition allOf = allOf(condition1, + allOf(condition1, condition2), + anyOf(condition2, condition3)); + ErrorMessageFactory factory = shouldHave("Yoda", allOf); + // WHEN + String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); + // THEN + then(message).isEqualTo(format("[Test] %n" + + "Expecting actual:%n" + + " \"Yoda\"%n" + + "to have:%n" + + "[✗] all of:[%n" + + " [✓] jedi power,%n" + + " [✗] all of:[%n" + + " [✓] jedi power,%n" + + " [✗] sith power%n" + + " ],%n" + + " [✓] any of:[%n" + + " [✗] sith power,%n" + + " [✓] long life%n" + + " ]%n" + + "]")); + } + + @Test + void should_create_error_message_reporting_which_allOf_deep_nested_conditions_failed() { + // GIVEN + TestCondition condition1 = new TestCondition<>("jedi power"); + TestCondition condition2 = new TestCondition<>("sith power"); + TestCondition condition3 = new TestCondition<>("a long life"); + condition1.shouldMatch(true); + condition2.shouldMatch(false); + condition3.shouldMatch(true); + Condition allOf = allOf(allOf(condition1, + allOf(condition1, + allOf(condition2, condition3)))); + ErrorMessageFactory factory = shouldHave("Yoda", allOf); + // WHEN + String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); + // THEN + then(message).isEqualTo(format("[Test] %n" + + "Expecting actual:%n" + + " \"Yoda\"%n" + + "to have:%n" + + "[✗] all of:[%n" + + " [✗] all of:[%n" + + " [✓] jedi power,%n" + + " [✗] all of:[%n" + + " [✓] jedi power,%n" + + " [✗] all of:[%n" + + " [✗] sith power,%n" + + " [✓] a long life%n" + + " ]%n" + + " ]%n" + + " ]%n" + + "]")); + } + } diff --git a/src/test/java/org/assertj/core/error/ShouldMatchPattern_create_Test.java b/src/test/java/org/assertj/core/error/ShouldMatchPattern_create_Test.java index 1434d39cd42..5c1307f3854 100644 --- a/src/test/java/org/assertj/core/error/ShouldMatchPattern_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldMatchPattern_create_Test.java @@ -34,7 +34,7 @@ void should_create_error_message() { // WHEN String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n \"Yoda\"%nto match pattern:%n \"Luke\"")); + then(message).isEqualTo(format("[Test] %nExpecting actual:%n \"Yoda\"%nto match pattern:%n \"Luke\"")); } @Test @@ -44,6 +44,6 @@ void should_create_error_message_escaping_percent() { // WHEN String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n \"%%%%E\"%nto match pattern:%n \"fffff\"")); + then(message).isEqualTo(format("[Test] %nExpecting actual:%n \"%%%%E\"%nto match pattern:%n \"fffff\"")); } } diff --git a/src/test/java/org/assertj/core/error/ShouldMatch_create_Test.java b/src/test/java/org/assertj/core/error/ShouldMatch_create_Test.java index 8254204d735..764da051b8d 100644 --- a/src/test/java/org/assertj/core/error/ShouldMatch_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldMatch_create_Test.java @@ -31,7 +31,7 @@ void should_create_error_message_with_default_predicate_description() { // WHEN String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n \"Yoda\"%nto match given predicate." + ShouldMatch.ADVICE)); + then(message).isEqualTo(format("[Test] %nExpecting actual:%n \"Yoda\"%nto match given predicate." + ShouldMatch.ADVICE)); } @Test @@ -42,7 +42,7 @@ void should_create_error_message_with_predicate_description() { // WHEN String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n \"Yoda\"%nto match 'green light saber' predicate.")); + then(message).isEqualTo(format("[Test] %nExpecting actual:%n \"Yoda\"%nto match 'green light saber' predicate.")); } @Test diff --git a/src/test/java/org/assertj/core/error/ShouldNotAccept_create_Test.java b/src/test/java/org/assertj/core/error/ShouldNotAccept_create_Test.java index 515c4c35018..6a5885e2ba0 100644 --- a/src/test/java/org/assertj/core/error/ShouldNotAccept_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldNotAccept_create_Test.java @@ -31,7 +31,7 @@ void should_create_error_message_with_default_predicate_description() { // WHEN String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n given predicate%nnot to accept \"Yoda\" but it did.")); + then(message).isEqualTo(format("[Test] %nExpecting actual:%n given predicate%nnot to accept \"Yoda\" but it did.")); } @Test @@ -42,7 +42,7 @@ void should_create_error_message_with_predicate_description() { // WHEN String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n 'red light saber' predicate%nnot to accept \"Yoda\" but it did.")); + then(message).isEqualTo(format("[Test] %nExpecting actual:%n 'red light saber' predicate%nnot to accept \"Yoda\" but it did.")); } @Test diff --git a/src/test/java/org/assertj/core/error/ShouldNotBeBetween_create_Test.java b/src/test/java/org/assertj/core/error/ShouldNotBeBetween_create_Test.java index 2e40fb79c82..073352cfc48 100644 --- a/src/test/java/org/assertj/core/error/ShouldNotBeBetween_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldNotBeBetween_create_Test.java @@ -39,7 +39,7 @@ void should_create_error_message_with_period_boundaries_included() { String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2009-01-01T00:00:00.000 (java.util.Date)%n" + "not to be in period:%n" + " [2011-01-01T00:00:00.000 (java.util.Date), 2012-01-01T00:00:00.000 (java.util.Date)]")); @@ -54,7 +54,7 @@ void should_create_error_message_with_period_lower_boundary_included() { String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2012-01-01T00:00:00.000 (java.util.Date)%n" + "not to be in period:%n" + " [2011-01-01T00:00:00.000 (java.util.Date), 2012-01-01T00:00:00.000 (java.util.Date)[")); @@ -69,7 +69,7 @@ void should_create_error_message_with_period_upper_boundary_included() { String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2011-01-01T00:00:00.000 (java.util.Date)%n" + "not to be in period:%n" + " ]2011-01-01T00:00:00.000 (java.util.Date), 2012-01-01T00:00:00.000 (java.util.Date)]")); @@ -84,7 +84,7 @@ void should_create_error_message_with_period_boundaries_excluded() { String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 2011-01-01T00:00:00.000 (java.util.Date)%n" + "not to be in period:%n" + " ]2011-01-01T00:00:00.000 (java.util.Date), 2012-01-01T00:00:00.000 (java.util.Date)[")); diff --git a/src/test/java/org/assertj/core/error/ShouldNotBeEqualComparingFieldByFieldRecursively_create_Test.java b/src/test/java/org/assertj/core/error/ShouldNotBeEqualComparingFieldByFieldRecursively_create_Test.java index 691af253bbc..66bda29ab1f 100644 --- a/src/test/java/org/assertj/core/error/ShouldNotBeEqualComparingFieldByFieldRecursively_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldNotBeEqualComparingFieldByFieldRecursively_create_Test.java @@ -35,7 +35,7 @@ void should_show_error_message() { REPRESENTATION).create(TEST_DESCRIPTION, REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " \"Yoda\"%n" + "not to be equal to:%n" + " \"Luke\"%n" + @@ -58,7 +58,7 @@ void should_show_error_message_with_custom_comparison_configuration() { REPRESENTATION).create(TEST_DESCRIPTION, REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " \"Yoda\"%n" + "not to be equal to:%n" + " \"Luke\"%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldNotBeEqualIgnoringCase_create_Test.java b/src/test/java/org/assertj/core/error/ShouldNotBeEqualIgnoringCase_create_Test.java index dbbcd2ba10e..69588a9fa61 100644 --- a/src/test/java/org/assertj/core/error/ShouldNotBeEqualIgnoringCase_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldNotBeEqualIgnoringCase_create_Test.java @@ -36,7 +36,7 @@ void should_create_error_message() { String message = factory.create(new TestDescription("Test")); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " \"Yoda\"%n" + "not to be equal to:%n" + " \"Luke\"%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldNotBeEqualIgnoringWhitespace_create_Test.java b/src/test/java/org/assertj/core/error/ShouldNotBeEqualIgnoringWhitespace_create_Test.java index ceb8a00a470..3cc2873e35d 100644 --- a/src/test/java/org/assertj/core/error/ShouldNotBeEqualIgnoringWhitespace_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldNotBeEqualIgnoringWhitespace_create_Test.java @@ -37,7 +37,7 @@ void should_create_error_message() { String message = factory.create(new TestDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " \" my\tfoo bar \"%n" + "not to be equal to:%n" + " \" my foo bar \"%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldNotBeEqualNormalizingWhitespace_create_Test.java b/src/test/java/org/assertj/core/error/ShouldNotBeEqualNormalizingWhitespace_create_Test.java index bfab0293dbd..d67113b4f6a 100644 --- a/src/test/java/org/assertj/core/error/ShouldNotBeEqualNormalizingWhitespace_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldNotBeEqualNormalizingWhitespace_create_Test.java @@ -37,7 +37,7 @@ void should_create_error_message() { String message = factory.create(new TestDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " \" my\tfoo bar \"%n" + "not to be equal to:%n" + " \" my foo bar \"%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldNotBeEqualWithinOffset_create_Test.java b/src/test/java/org/assertj/core/error/ShouldNotBeEqualWithinOffset_create_Test.java index 715ce22b2ce..ef8156df64a 100644 --- a/src/test/java/org/assertj/core/error/ShouldNotBeEqualWithinOffset_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldNotBeEqualWithinOffset_create_Test.java @@ -32,7 +32,7 @@ void should_create_error_message() { String message = factory.create(new TestDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 8.0f%n" + "not to be close to:%n" + " 6.0f%n" + @@ -48,7 +48,7 @@ void should_create_error_message_for_strict_offset() { String message = factory.create(new TestDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " 8.0f%n" + "not to be close to:%n" + " 6.0f%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldNotBeEqual_create_Test.java b/src/test/java/org/assertj/core/error/ShouldNotBeEqual_create_Test.java index 5a8ffd18980..e3676476d0c 100644 --- a/src/test/java/org/assertj/core/error/ShouldNotBeEqual_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldNotBeEqual_create_Test.java @@ -37,7 +37,7 @@ void should_create_error_message() { // WHEN String message = factory.create(new TestDescription("Jedi"), new StandardRepresentation()); // THEN - then(message).isEqualTo(format("[Jedi] %nExpecting:%n \"Yoda\"%nnot to be equal to:%n \"Luke\"%n")); + then(message).isEqualTo(format("[Jedi] %nExpecting actual:%n \"Yoda\"%nnot to be equal to:%n \"Luke\"%n")); } @Test @@ -48,6 +48,6 @@ void should_create_error_message_with_custom_comparison_strategy() { // WHEN String message = factory.create(new TestDescription("Jedi"), new StandardRepresentation()); // THEN - then(message).isEqualTo(format("[Jedi] %nExpecting:%n \"Yoda\"%nnot to be equal to:%n \"Luke\"%nwhen comparing values using CaseInsensitiveStringComparator")); + then(message).isEqualTo(format("[Jedi] %nExpecting actual:%n \"Yoda\"%nnot to be equal to:%n \"Luke\"%nwhen comparing values using CaseInsensitiveStringComparator")); } } diff --git a/src/test/java/org/assertj/core/error/ShouldNotBeFinite_create_Test.java b/src/test/java/org/assertj/core/error/ShouldNotBeFinite_create_Test.java new file mode 100644 index 00000000000..6ca8761278f --- /dev/null +++ b/src/test/java/org/assertj/core/error/ShouldNotBeFinite_create_Test.java @@ -0,0 +1,47 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.error; + +import static java.lang.String.format; +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.error.ShouldNotBeFinite.shouldNotBeFinite; +import static org.assertj.core.presentation.StandardRepresentation.STANDARD_REPRESENTATION; + +import org.assertj.core.internal.TestDescription; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +@DisplayName("ShouldNotBeFinite create") +class ShouldNotBeFinite_create_Test { + + @Test + void should_create_error_message_with_double() { + // GIVEN + double actual = 1.0; + // WHEN + String message = shouldNotBeFinite(actual).create(new TestDescription("TEST"), STANDARD_REPRESENTATION); + // THEN + then(message).isEqualTo(format("[TEST] %nExpecting 1.0 not to be finite")); + } + + @Test + void should_create_error_message_with_float() { + // GIVEN + float actual = 1.0f; + // WHEN + String message = shouldNotBeFinite(actual).create(new TestDescription("TEST"), STANDARD_REPRESENTATION); + // THEN + then(message).isEqualTo(format("[TEST] %nExpecting 1.0f not to be finite")); + } + +} diff --git a/src/test/java/org/assertj/core/error/ShouldNotBeIn_create_Test.java b/src/test/java/org/assertj/core/error/ShouldNotBeIn_create_Test.java index 08e08b4cfb5..07a3f1b42e2 100644 --- a/src/test/java/org/assertj/core/error/ShouldNotBeIn_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldNotBeIn_create_Test.java @@ -41,7 +41,7 @@ void should_create_error_message() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" - + "Expecting:%n" + + "Expecting actual:%n" + " \"Luke\"%n" + "not to be in:%n" + " [\"Luke\", \"Leia\"]%n")); @@ -56,7 +56,7 @@ void should_create_error_message_with_custom_comparison_strategy() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" - + "Expecting:%n" + + "Expecting actual:%n" + " \"Luke\"%n" + "not to be in:%n" + " [\"Luke\", \"Leia\"]%n" diff --git a/src/test/java/org/assertj/core/error/ShouldNotBeInfinite_create_Test.java b/src/test/java/org/assertj/core/error/ShouldNotBeInfinite_create_Test.java new file mode 100644 index 00000000000..621d87d64d3 --- /dev/null +++ b/src/test/java/org/assertj/core/error/ShouldNotBeInfinite_create_Test.java @@ -0,0 +1,47 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.error; + +import static java.lang.String.format; +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.error.ShouldNotBeInfinite.shouldNotBeInfinite; +import static org.assertj.core.presentation.StandardRepresentation.STANDARD_REPRESENTATION; + +import org.assertj.core.internal.TestDescription; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +@DisplayName("ShouldNotBeInfinite create") +class ShouldNotBeInfinite_create_Test { + + @Test + void should_create_error_message_with_double() { + // GIVEN + double actual = Double.POSITIVE_INFINITY; + // WHEN + String message = shouldNotBeInfinite(actual).create(new TestDescription("TEST"), STANDARD_REPRESENTATION); + // THEN + then(message).isEqualTo(format("[TEST] %nExpecting Infinity not to be infinite")); + } + + @Test + void should_create_error_message_with_float() { + // GIVEN + float actual = Float.POSITIVE_INFINITY; + // WHEN + String message = shouldNotBeInfinite(actual).create(new TestDescription("TEST"), STANDARD_REPRESENTATION); + // THEN + then(message).isEqualTo(format("[TEST] %nExpecting Infinityf not to be infinite")); + } + +} diff --git a/src/test/java/org/assertj/core/error/ShouldNotBeInstanceOfAny_create_Test.java b/src/test/java/org/assertj/core/error/ShouldNotBeInstanceOfAny_create_Test.java index 4ab9fd245f5..a03ccf5b305 100644 --- a/src/test/java/org/assertj/core/error/ShouldNotBeInstanceOfAny_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldNotBeInstanceOfAny_create_Test.java @@ -37,7 +37,7 @@ void should_create_error_message() { String message = factory.create(new TestDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " \"Yoda\"%n" + "not to be an instance of any of these types:%n" + " [java.lang.String, java.lang.Object]")); @@ -51,7 +51,7 @@ void should_create_error_message_with_stack_trace_for_throwable() { // WHEN String message = shouldNotBeInstanceOfAny(throwable, types).create(); // THEN - then(message).isEqualTo(format("%nExpecting:%n" + + then(message).isEqualTo(format("%nExpecting actual:%n" + " \"" + getStackTrace(throwable) + "\"%n" + "not to be an instance of any of these types:%n" + " [java.lang.NullPointerException, java.lang.IllegalArgumentException]")); diff --git a/src/test/java/org/assertj/core/error/ShouldNotBeInstance_create_Test.java b/src/test/java/org/assertj/core/error/ShouldNotBeInstance_create_Test.java index 9d1e91df17e..99b4642c3fd 100644 --- a/src/test/java/org/assertj/core/error/ShouldNotBeInstance_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldNotBeInstance_create_Test.java @@ -36,7 +36,7 @@ void should_create_error_message() { String message = factory.create(new TestDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " \"Yoda\"%n" + "not to be an instance of: java.lang.String")); } @@ -48,7 +48,7 @@ void should_create_error_message_with_stack_trace_for_throwable() { // WHEN String message = shouldNotBeInstance(throwable, IllegalArgumentException.class).create(); // THEN - then(message).isEqualTo(format("%nExpecting:%n" + + then(message).isEqualTo(format("%nExpecting actual:%n" + " \"" + getStackTrace(throwable) + "\"%n" + "not to be an instance of: java.lang.IllegalArgumentException")); } diff --git a/src/test/java/org/assertj/core/error/ShouldNotBeOfClassIn_Test.java b/src/test/java/org/assertj/core/error/ShouldNotBeOfClassIn_Test.java index dda1684733a..fcb6519333c 100644 --- a/src/test/java/org/assertj/core/error/ShouldNotBeOfClassIn_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldNotBeOfClassIn_Test.java @@ -35,6 +35,6 @@ void should_create_error_message() { // WHEN String message = factory.create(new TestDescription("Test"), new StandardRepresentation()); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n \"Yoda\"%nnot to be of any type in:%n [java.lang.Long, java.lang.String]%nbut was of type: java.lang.String")); + then(message).isEqualTo(format("[Test] %nExpecting actual:%n \"Yoda\"%nnot to be of any type in:%n [java.lang.Long, java.lang.String]%nbut was of type: java.lang.String")); } } diff --git a/src/test/java/org/assertj/core/error/ShouldNotBe_create_Test.java b/src/test/java/org/assertj/core/error/ShouldNotBe_create_Test.java index 47ad7cc77ca..033b867b029 100644 --- a/src/test/java/org/assertj/core/error/ShouldNotBe_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldNotBe_create_Test.java @@ -34,6 +34,6 @@ void should_create_error_message() { // WHEN String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN - then(message).isEqualTo(String.format("[Test] %nExpecting:%n \"Yoda\"%nnot to be Sith")); + then(message).isEqualTo(String.format("[Test] %nExpecting actual:%n \"Yoda\"%nnot to be Sith")); } } diff --git a/src/test/java/org/assertj/core/error/ShouldNotContainAtIndex_create_Test.java b/src/test/java/org/assertj/core/error/ShouldNotContainAtIndex_create_Test.java index bb8b49b0670..cf0ff856593 100644 --- a/src/test/java/org/assertj/core/error/ShouldNotContainAtIndex_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldNotContainAtIndex_create_Test.java @@ -45,7 +45,7 @@ void should_create_error_message() { // WHEN String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n [\"Yoda\", \"Luke\"]%nnot to contain:%n \"Luke\"%nat index 1%n")); + then(message).isEqualTo(format("[Test] %nExpecting actual:%n [\"Yoda\", \"Luke\"]%nnot to contain:%n \"Luke\"%nat index 1%n")); } @Test @@ -56,7 +56,7 @@ void should_create_error_message_with_custom_comparison_strategy() { // WHEN String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n [\"Yoda\", \"Luke\"]%nnot to contain:%n \"Luke\"%n" + then(message).isEqualTo(format("[Test] %nExpecting actual:%n [\"Yoda\", \"Luke\"]%nnot to contain:%n \"Luke\"%n" + "at index 1%n" + "when comparing values using CaseInsensitiveStringComparator")); } diff --git a/src/test/java/org/assertj/core/error/ShouldNotContainCharSequence_create_Test.java b/src/test/java/org/assertj/core/error/ShouldNotContainCharSequence_create_Test.java index 9fead4ad056..1940ebdc009 100644 --- a/src/test/java/org/assertj/core/error/ShouldNotContainCharSequence_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldNotContainCharSequence_create_Test.java @@ -46,7 +46,7 @@ void should_create_error_message() { String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " \"Yoda\"%n" + "not to contain:%n" + " \"od\"%n")); @@ -61,7 +61,7 @@ void should_create_error_message_with_custom_comparison_strategy() { String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " \"Yoda\"%n" + "not to contain:%n" + " \"od\"%n" + @@ -77,7 +77,7 @@ void should_create_error_message_with_several_string_values() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " \"Yoda\"%n" + "not to contain:%n" + " [\"od\", \"ya\"]%n" + @@ -93,7 +93,7 @@ void should_create_error_message_for_ignoring_case() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " \"Yoda\"%n" + "not to contain (ignoring case):%n" + " \"OD\"%n")); @@ -107,7 +107,7 @@ void should_create_error_message_for_ignoring_case_with_multiple_findings() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " \"Yoda\"%n" + "not to contain (ignoring case):%n" + " [\"OD\", \"da\", \"Luke\"]%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldNotContainKey_create_Test.java b/src/test/java/org/assertj/core/error/ShouldNotContainKey_create_Test.java index 21b2e3e7ede..a5e71480679 100644 --- a/src/test/java/org/assertj/core/error/ShouldNotContainKey_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldNotContainKey_create_Test.java @@ -42,7 +42,7 @@ void should_create_error_message() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " {\"color\"=\"green\", \"name\"=\"Yoda\"}%n" + "not to contain key:%n" + " \"age\"")); diff --git a/src/test/java/org/assertj/core/error/ShouldNotContainKeys_create_Test.java b/src/test/java/org/assertj/core/error/ShouldNotContainKeys_create_Test.java index cc181d58b4f..b080299e686 100644 --- a/src/test/java/org/assertj/core/error/ShouldNotContainKeys_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldNotContainKeys_create_Test.java @@ -50,7 +50,7 @@ void should_create_error_message() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " {\"color\"=\"green\", \"name\"=\"Yoda\"}%n" + "not to contain key:%n" + " \"age\"")); @@ -64,7 +64,7 @@ void should_create_error_message_with_multiple_keys() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " {\"color\"=\"green\", \"name\"=\"Yoda\"}%n" + "not to contain keys:%n" + " [\"name\", \"color\"]")); diff --git a/src/test/java/org/assertj/core/error/ShouldNotContainNull_create_Test.java b/src/test/java/org/assertj/core/error/ShouldNotContainNull_create_Test.java index 31b87d80a16..2f720389a8b 100644 --- a/src/test/java/org/assertj/core/error/ShouldNotContainNull_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldNotContainNull_create_Test.java @@ -30,6 +30,6 @@ void should_create_error_message() { // WHEN String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN - then(message).isEqualTo(String.format("[Test] %nExpecting:%n [\"Luke\", \"Yoda\", null]%nnot to contain null elements")); + then(message).isEqualTo(String.format("[Test] %nExpecting actual:%n [\"Luke\", \"Yoda\", null]%nnot to contain null elements")); } } diff --git a/src/test/java/org/assertj/core/error/ShouldNotContainPattern_create_Test.java b/src/test/java/org/assertj/core/error/ShouldNotContainPattern_create_Test.java index 86536ffbad9..28c462efd93 100644 --- a/src/test/java/org/assertj/core/error/ShouldNotContainPattern_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldNotContainPattern_create_Test.java @@ -30,7 +30,7 @@ void should_create_error_message() { String message = factory.create(new TextDescription("Test"), CONFIGURATION_PROVIDER.representation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " \"Frodo\"%n" + "not to contain pattern:%n" + " \"Fr.do\"")); diff --git a/src/test/java/org/assertj/core/error/ShouldNotContainSequence_create_Test.java b/src/test/java/org/assertj/core/error/ShouldNotContainSequence_create_Test.java index c5ef97a66ed..ab273f6353c 100644 --- a/src/test/java/org/assertj/core/error/ShouldNotContainSequence_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldNotContainSequence_create_Test.java @@ -33,7 +33,7 @@ void should_create_error_message() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " [\"Yoda\", \"Luke\"]%n" + "to not contain sequence:%n" + " [\"Yoda\", \"Luke\"]%n" + @@ -49,7 +49,7 @@ void should_create_error_message_with_custom_comparison_strategy() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " [\"yoDA\", \"LUke\"]%n" + "to not contain sequence:%n" + " [\"Yoda\", \"Luke\"]%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldNotContainSubsequence_create_Test.java b/src/test/java/org/assertj/core/error/ShouldNotContainSubsequence_create_Test.java index 888ec98ebe3..3ae159d6938 100644 --- a/src/test/java/org/assertj/core/error/ShouldNotContainSubsequence_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldNotContainSubsequence_create_Test.java @@ -32,7 +32,7 @@ void should_create_error_message() { // WHEN String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n [\"Yoda\", \"Luke\", \"Leia\"]%nto not contain subsequence:%n [\"Luke\", \"Leia\"]%nbut was found starting at index 1%n")); + then(message).isEqualTo(format("[Test] %nExpecting actual:%n [\"Yoda\", \"Luke\", \"Leia\"]%nto not contain subsequence:%n [\"Luke\", \"Leia\"]%nbut was found starting at index 1%n")); } @Test @@ -43,7 +43,7 @@ void should_create_error_message_with_custom_comparison_strategy() { // WHEN String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n [\"Yoda\", \"LUke\", \"LeiA\"]%nto not contain subsequence:%n [\"Luke\", \"Leia\"]%n" + then(message).isEqualTo(format("[Test] %nExpecting actual:%n [\"Yoda\", \"LUke\", \"LeiA\"]%nto not contain subsequence:%n [\"Luke\", \"Leia\"]%n" + "but was found starting at index 1%n" + "when comparing values using CaseInsensitiveStringComparator")); } diff --git a/src/test/java/org/assertj/core/error/ShouldNotContainValue_create_Test.java b/src/test/java/org/assertj/core/error/ShouldNotContainValue_create_Test.java index 9c6629f5ff0..9e43e33dc4b 100644 --- a/src/test/java/org/assertj/core/error/ShouldNotContainValue_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldNotContainValue_create_Test.java @@ -35,7 +35,7 @@ void should_create_error_message() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " {\"color\"=\"green\", \"name\"=\"Yoda\"}%n" + "not to contain value:%n" + " \"green\"")); diff --git a/src/test/java/org/assertj/core/error/ShouldNotEndWith_create_Test.java b/src/test/java/org/assertj/core/error/ShouldNotEndWith_create_Test.java index b17508c51ea..4bffef1863b 100644 --- a/src/test/java/org/assertj/core/error/ShouldNotEndWith_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldNotEndWith_create_Test.java @@ -40,7 +40,7 @@ void should_create_error_message() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " [\"Yoda\", \"Luke\"]%n" + "not to end with:%n" + " [\"Han\", \"Leia\"]%n")); @@ -55,7 +55,7 @@ void should_create_error_message_with_custom_comparison_strategy() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " [\"Yoda\", \"Luke\"]%n" + "not to end with:%n" + " [\"Han\", \"Leia\"]%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldNotHaveAnyElementsOfTypes_create_Test.java b/src/test/java/org/assertj/core/error/ShouldNotHaveAnyElementsOfTypes_create_Test.java index 26e1d0400c4..196cf16988b 100644 --- a/src/test/java/org/assertj/core/error/ShouldNotHaveAnyElementsOfTypes_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldNotHaveAnyElementsOfTypes_create_Test.java @@ -47,7 +47,7 @@ void should_create_error_message() { // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " [1, 2, 3.0, 4.1, 1]%n" + "to not have any elements of the following types:%n" + " [java.lang.Long, java.lang.Double, java.math.BigDecimal]%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldNotHaveSameClass_create_Test.java b/src/test/java/org/assertj/core/error/ShouldNotHaveSameClass_create_Test.java index 9cc661db325..e66ac2beeeb 100644 --- a/src/test/java/org/assertj/core/error/ShouldNotHaveSameClass_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldNotHaveSameClass_create_Test.java @@ -34,6 +34,6 @@ void should_create_error_message() { // WHEN String message = factory.create(new TestDescription("Test"), new StandardRepresentation()); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n \"Yoda\"%nnot to have the same class as:%n \"Luke\" (java.lang.String)")); + then(message).isEqualTo(format("[Test] %nExpecting actual:%n \"Yoda\"%nnot to have the same class as:%n \"Luke\" (java.lang.String)")); } } diff --git a/src/test/java/org/assertj/core/error/ShouldNotHave_create_Test.java b/src/test/java/org/assertj/core/error/ShouldNotHave_create_Test.java index ac7a4e922e0..26630cddafc 100644 --- a/src/test/java/org/assertj/core/error/ShouldNotHave_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldNotHave_create_Test.java @@ -39,6 +39,6 @@ void should_create_error_message() { // WHEN String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n \"Yoda\"%nnot to have:%n red lightsaber")); + then(message).isEqualTo(format("[Test] %nExpecting actual:%n \"Yoda\"%nnot to have red lightsaber")); } } diff --git a/src/test/java/org/assertj/core/error/ShouldNotMatchPattern_create_Test.java b/src/test/java/org/assertj/core/error/ShouldNotMatchPattern_create_Test.java index 0f9aaea5bff..46e1c95e7f2 100644 --- a/src/test/java/org/assertj/core/error/ShouldNotMatchPattern_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldNotMatchPattern_create_Test.java @@ -34,6 +34,6 @@ void should_create_error_message() { // WHEN String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n \"Yoda\"%nnot to match pattern:%n \"Luke\"")); + then(message).isEqualTo(format("[Test] %nExpecting actual:%n \"Yoda\"%nnot to match pattern:%n \"Luke\"")); } } diff --git a/src/test/java/org/assertj/core/error/ShouldNotMatch_create_Test.java b/src/test/java/org/assertj/core/error/ShouldNotMatch_create_Test.java index 16259ca2bf2..738e77d7598 100644 --- a/src/test/java/org/assertj/core/error/ShouldNotMatch_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldNotMatch_create_Test.java @@ -34,7 +34,7 @@ void should_create_error_message_with_default_predicate_description() { // WHEN String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n \"Yoda\"%nnot to match given predicate." + ShouldNotMatch.ADVICE)); + then(message).isEqualTo(format("[Test] %nExpecting actual:%n \"Yoda\"%nnot to match given predicate." + ShouldNotMatch.ADVICE)); } @Test @@ -45,7 +45,7 @@ void should_create_error_message_with_predicate_description() { // WHEN String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n \"Yoda\"%nnot to match 'green light saber' predicate.")); + then(message).isEqualTo(format("[Test] %nExpecting actual:%n \"Yoda\"%nnot to match 'green light saber' predicate.")); } @Test diff --git a/src/test/java/org/assertj/core/error/ShouldNotStartWith_create_Test.java b/src/test/java/org/assertj/core/error/ShouldNotStartWith_create_Test.java index 5b98e51da38..42e6f5d1f2b 100644 --- a/src/test/java/org/assertj/core/error/ShouldNotStartWith_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldNotStartWith_create_Test.java @@ -46,7 +46,7 @@ void should_create_error_message() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " [\"Yoda\", \"Luke\"]%n" + "not to start with:%n" + " [\"Han\", \"Leia\"]%n")); @@ -61,7 +61,7 @@ void should_create_error_message_with_custom_comparison_strategy() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " [\"Yoda\", \"Luke\"]%n" + "not to start with:%n" + " [\"Han\", \"Leia\"]%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldOnlyHaveElementsOfTypes_create_Test.java b/src/test/java/org/assertj/core/error/ShouldOnlyHaveElementsOfTypes_create_Test.java index ffd96d85282..4caa3b1aba9 100644 --- a/src/test/java/org/assertj/core/error/ShouldOnlyHaveElementsOfTypes_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldOnlyHaveElementsOfTypes_create_Test.java @@ -37,7 +37,7 @@ void should_create_error_message() { String message = factory.create(new TestDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " [\"Yoda\", 42, \"Luke\"]%n" + "to only have instances of:%n" + " [java.lang.Number, java.lang.Long]%n" + diff --git a/src/test/java/org/assertj/core/error/ShouldSatisfy_create_Test.java b/src/test/java/org/assertj/core/error/ShouldSatisfy_create_Test.java index 6ba3987b012..b264e450d4f 100644 --- a/src/test/java/org/assertj/core/error/ShouldSatisfy_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldSatisfy_create_Test.java @@ -39,7 +39,7 @@ void should_create_error_message_if_condition_is_not_satisfied() { String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" - + "Expecting:%n" + + "Expecting actual:%n" + " \"Yoda\"%n" + "to satisfy:%n" + " green lightsaber bearer")); @@ -53,7 +53,7 @@ void should_create_error_message_if_consumers_are_not_all_satisfied() { String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" - + "Expecting:%n" + + "Expecting actual:%n" + " [\"Luke\", \"Leia\", \"Yoda\"]%n" + "to satisfy all the consumers in any order.")); } diff --git a/src/test/java/org/assertj/core/error/ShouldStartWith_create_Test.java b/src/test/java/org/assertj/core/error/ShouldStartWith_create_Test.java index 3202af92409..f580e2bbfe4 100644 --- a/src/test/java/org/assertj/core/error/ShouldStartWith_create_Test.java +++ b/src/test/java/org/assertj/core/error/ShouldStartWith_create_Test.java @@ -44,7 +44,7 @@ void should_create_error_message() { // WHEN String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n [\"Yoda\", \"Luke\"]%nto start with:%n [\"Han\", \"Leia\"]%n")); + then(message).isEqualTo(format("[Test] %nExpecting actual:%n [\"Yoda\", \"Luke\"]%nto start with:%n [\"Han\", \"Leia\"]%n")); } @Test @@ -55,7 +55,7 @@ void should_create_error_message_with_custom_comparison_strategy() { // WHEN String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION); // THEN - then(message).isEqualTo(format("[Test] %nExpecting:%n [\"Yoda\", \"Luke\"]%nto start with:%n [\"Han\", \"Leia\"]%n" + then(message).isEqualTo(format("[Test] %nExpecting actual:%n [\"Yoda\", \"Luke\"]%nto start with:%n [\"Han\", \"Leia\"]%n" + "when comparing values using CaseInsensitiveStringComparator")); } } diff --git a/src/test/java/org/assertj/core/error/uri/ShouldHaveAnchor_create_Test.java b/src/test/java/org/assertj/core/error/uri/ShouldHaveAnchor_create_Test.java index 40ba2e0032c..76f2a8085e4 100644 --- a/src/test/java/org/assertj/core/error/uri/ShouldHaveAnchor_create_Test.java +++ b/src/test/java/org/assertj/core/error/uri/ShouldHaveAnchor_create_Test.java @@ -47,7 +47,7 @@ void should_create_error_message_for_has_no_anchor() throws Exception { String error = shouldHaveAnchor(uri, null).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "not to have an anchor but had:%n" + " <\"print\">")); diff --git a/src/test/java/org/assertj/core/error/uri/ShouldHaveParameter_create_Test.java b/src/test/java/org/assertj/core/error/uri/ShouldHaveParameter_create_Test.java index cbfeebe39c4..402500fb841 100644 --- a/src/test/java/org/assertj/core/error/uri/ShouldHaveParameter_create_Test.java +++ b/src/test/java/org/assertj/core/error/uri/ShouldHaveParameter_create_Test.java @@ -34,7 +34,7 @@ void should_create_error_message_for_missing_uri_parameter() { String error = shouldHaveParameter(uri, "article").create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "to have parameter:%n" + " <\"article\">%n" + @@ -49,7 +49,7 @@ void should_create_error_message_for_uri_parameter_without_value_that_is_missing String error = shouldHaveParameter(uri, "article", null).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "to have parameter:%n" + " <\"article\">%n" + @@ -64,7 +64,7 @@ void should_create_error_message_for_missing_uri_parameter_with_an_expected_valu String error = shouldHaveParameter(uri, "article", "10").create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "to have parameter:%n" + " <\"article\">%n" + @@ -81,7 +81,7 @@ void should_create_error_message_for_uri_parameter_without_value_that_has_one() String error = shouldHaveParameter(uri, "article", null, list("10")).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "to have parameter:%n" + " <\"article\">%n" + @@ -98,7 +98,7 @@ void should_create_error_message_for_uri_parameter_without_value_that_has_multip list("10", "11")).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "to have parameter:%n" + " <\"article\">%n" + @@ -115,7 +115,7 @@ void should_create_error_message_for_uri_parameter_with_value_that_has_no_value( list((String) null)).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "to have parameter:%n" + " <\"article\">%n" + @@ -132,7 +132,7 @@ void should_create_error_message_for_uri_with_wrong_parameter_value() { String error = shouldHaveParameter(uri, "article", "10", list("11")).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "to have parameter:%n" + " <\"article\">%n" + @@ -151,7 +151,7 @@ void should_create_error_message_for_uri_with_wrong_parameter_values() { list("11", "12")).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "to have parameter:%n" + " <\"article\">%n" + @@ -169,7 +169,7 @@ void should_create_error_message_for_uri_with_no_parameter_that_has_one_even_wit String error = shouldHaveNoParameter(uri, "article", null).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "not to have parameter:%n" + " <\"article\">%n" + @@ -184,7 +184,7 @@ void should_create_error_message_for_uri_with_no_parameter_that_has_one_with_val String error = shouldHaveNoParameter(uri, "article", list("10")).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "not to have parameter:%n" + " <\"article\">%n" + @@ -200,7 +200,7 @@ void should_create_error_message_for_uri_with_no_parameter_that_has_one_with_mul String error = shouldHaveNoParameter(uri, "article", list("10", "11")).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "not to have parameter:%n" + " <\"article\">%n" + @@ -216,7 +216,7 @@ void should_create_error_message_for_uri_with_no_parameter_that_has_one_without_ String error = shouldHaveNoParameter(uri, "article", null, null).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "not to have parameter:%n" + " <\"article\">%n" + @@ -231,7 +231,7 @@ void should_create_error_message_for_uri_no_parameter_value_but_found() { String error = shouldHaveNoParameter(uri, "article", "10", list("10")).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "not to have parameter:%n" + " <\"article\">%n" + @@ -250,7 +250,7 @@ void should_create_error_message_for_missing_url_parameter() throws Exception { String error = shouldHaveParameter(url, "article").create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "to have parameter:%n" + " <\"article\">%n" + @@ -265,7 +265,7 @@ void should_create_error_message_for_url_parameter_without_value_that_is_missing String error = shouldHaveParameter(url, "article", null).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "to have parameter:%n" + " <\"article\">%n" + @@ -280,7 +280,7 @@ void should_create_error_message_for_missing_url_parameter_with_an_expected_valu String error = shouldHaveParameter(url, "article", "10").create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "to have parameter:%n" + " <\"article\">%n" + @@ -297,7 +297,7 @@ void should_create_error_message_for_url_parameter_without_value_that_has_one() String error = shouldHaveParameter(url, "article", null, list("10")).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "to have parameter:%n" + " <\"article\">%n" + @@ -314,7 +314,7 @@ void should_create_error_message_for_url_parameter_without_value_that_has_multip list("10", "11")).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "to have parameter:%n" + " <\"article\">%n" + @@ -331,7 +331,7 @@ void should_create_error_message_for_url_parameter_with_value_that_has_no_value( list((String) null)).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "to have parameter:%n" + " <\"article\">%n" + @@ -348,7 +348,7 @@ void should_create_error_message_for_url_with_wrong_parameter_value() throws Exc String error = shouldHaveParameter(url, "article", "10", list("11")).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "to have parameter:%n" + " <\"article\">%n" + @@ -367,7 +367,7 @@ void should_create_error_message_for_url_with_wrong_parameter_values() throws Ex list("11", "12")).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "to have parameter:%n" + " <\"article\">%n" + @@ -385,7 +385,7 @@ void should_create_error_message_for_url_with_no_parameter_that_has_one_even_wit String error = shouldHaveNoParameter(url, "article", list((String) null)).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "not to have parameter:%n" + " <\"article\">%n" + @@ -400,7 +400,7 @@ void should_create_error_message_for_url_with_no_parameter_that_has_one_with_val String error = shouldHaveNoParameter(url, "article", list("10")).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "not to have parameter:%n" + " <\"article\">%n" + @@ -416,7 +416,7 @@ void should_create_error_message_for_url_with_no_parameter_that_has_one_with_mul String error = shouldHaveNoParameter(url, "article", list("10", "11")).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "not to have parameter:%n" + " <\"article\">%n" + @@ -432,7 +432,7 @@ void should_create_error_message_for_url_with_no_parameter_that_has_one_without_ String error = shouldHaveNoParameter(url, "article", null, null).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "not to have parameter:%n" + " <\"article\">%n" + @@ -447,7 +447,7 @@ void should_create_error_message_for_url_no_parameter_value_but_found() throws E String error = shouldHaveNoParameter(url, "article", "10", list("10")).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "not to have parameter:%n" + " <\"article\">%n" + diff --git a/src/test/java/org/assertj/core/error/uri/ShouldHavePath_create_Test.java b/src/test/java/org/assertj/core/error/uri/ShouldHavePath_create_Test.java index 45ea71c75b9..a7a52e7ef66 100644 --- a/src/test/java/org/assertj/core/error/uri/ShouldHavePath_create_Test.java +++ b/src/test/java/org/assertj/core/error/uri/ShouldHavePath_create_Test.java @@ -60,7 +60,7 @@ void should_create_error_message_for_uri_has_no_path() { String error = shouldHavePath(uri, null).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "not to have a path but had:%n" + " <\"/news\">")); @@ -74,7 +74,7 @@ void should_create_error_message_for_url_has_no_path() throws Exception { String error = shouldHavePath(url, null).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "not to have a path but had:%n" + " <\"/news\">")); @@ -82,7 +82,7 @@ void should_create_error_message_for_url_has_no_path() throws Exception { error = shouldHavePath(url, "").create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "not to have a path but had:%n" + " <\"/news\">")); diff --git a/src/test/java/org/assertj/core/error/uri/ShouldHavePort_create_Test.java b/src/test/java/org/assertj/core/error/uri/ShouldHavePort_create_Test.java index da1e3fd1afe..c8667c8d259 100644 --- a/src/test/java/org/assertj/core/error/uri/ShouldHavePort_create_Test.java +++ b/src/test/java/org/assertj/core/error/uri/ShouldHavePort_create_Test.java @@ -46,7 +46,7 @@ void should_create_error_message_for_uri_has_no_port() { String error = shouldHavePort(uri, -1).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "not to have a port but had:%n" + " <8080>")); @@ -74,7 +74,7 @@ void should_create_error_message_for_url_has_no_port() throws Exception { String error = shouldHavePort(url, -1).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "not to have a port but had:%n" + " <8080>")); diff --git a/src/test/java/org/assertj/core/error/uri/ShouldHaveQuery_create_Test.java b/src/test/java/org/assertj/core/error/uri/ShouldHaveQuery_create_Test.java index 43b79c346e2..f6446ab47bf 100644 --- a/src/test/java/org/assertj/core/error/uri/ShouldHaveQuery_create_Test.java +++ b/src/test/java/org/assertj/core/error/uri/ShouldHaveQuery_create_Test.java @@ -64,7 +64,7 @@ void should_create_error_message_for_uri_has_no_query() { String error = shouldHaveQuery(uri, null).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "not to have a query but had:%n" + " <\"type=beta\">")); @@ -78,7 +78,7 @@ void should_create_error_message_for_url_has_no_query() throws Exception { String error = shouldHaveQuery(url, null).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "not to have a query but had:%n" + " <\"type=beta\">")); diff --git a/src/test/java/org/assertj/core/error/uri/ShouldHaveUserInfo_create_Test.java b/src/test/java/org/assertj/core/error/uri/ShouldHaveUserInfo_create_Test.java index 13d9c72784c..673f523ae3a 100644 --- a/src/test/java/org/assertj/core/error/uri/ShouldHaveUserInfo_create_Test.java +++ b/src/test/java/org/assertj/core/error/uri/ShouldHaveUserInfo_create_Test.java @@ -48,7 +48,7 @@ void should_create_error_message_for_uri_has_no_user_info() { String error = shouldHaveUserInfo(uri, null).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "not to have user info but had:%n" + " <\"test:pass\">")); @@ -78,7 +78,7 @@ void should_create_error_message_for_url_has_no_user_info() throws Exception { String error = shouldHaveUserInfo(url, null).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " %n" + "not to have user info but had:%n" + " <\"test:pass\">")); diff --git a/src/test/java/org/assertj/core/extractor/ByNameMultipleExtractorTest.java b/src/test/java/org/assertj/core/extractor/ByNameMultipleExtractorTest.java index 39eedfd99f3..ee1d2a0f2ee 100644 --- a/src/test/java/org/assertj/core/extractor/ByNameMultipleExtractorTest.java +++ b/src/test/java/org/assertj/core/extractor/ByNameMultipleExtractorTest.java @@ -99,12 +99,24 @@ void should_throw_exception_when_no_object_is_given() { void should_extract_multiple_values_from_map_by_keys() { // GIVEN Employee luke = new Employee(2L, new Name("Luke"), 22); - Map map = mapOf(entry("key1", YODA), entry("key2", luke)); - ByNameMultipleExtractor underTest = new ByNameMultipleExtractor("key1", "key2", "bad key"); + Map map = mapOf(entry("key1", YODA), entry("key2", luke), entry("key3", null)); + ByNameMultipleExtractor underTest = new ByNameMultipleExtractor("key1", "key2", "key3"); // WHEN Tuple result = underTest.apply(map); // THEN then(result).isEqualTo(tuple(YODA, luke, null)); } + @Test + void should_throw_error_with_map_when_non_existing_key_is_given() { + // GIVEN + Employee luke = new Employee(2L, new Name("Luke"), 22); + Map map = mapOf(entry("key1", YODA), entry("key2", luke)); + ByNameMultipleExtractor underTest = new ByNameMultipleExtractor("key1", "key2", "bad key"); + // WHEN + Throwable thrown = catchThrowable(() -> underTest.apply(YODA)); + // THEN + then(thrown).isInstanceOf(IntrospectionError.class); + } + } diff --git a/src/test/java/org/assertj/core/extractor/ByNameSingleExtractorTest.java b/src/test/java/org/assertj/core/extractor/ByNameSingleExtractorTest.java index acdd435594b..fe2ea7f2468 100644 --- a/src/test/java/org/assertj/core/extractor/ByNameSingleExtractorTest.java +++ b/src/test/java/org/assertj/core/extractor/ByNameSingleExtractorTest.java @@ -164,11 +164,22 @@ void should_extract_single_value_from_map_by_key() { } @Test - void should_extract_null_from_map_by_non_existing_key() { + void should_throw_error_from_map_by_non_existing_key() { // GIVEN Map map = mapOf(entry("key", YODA)); ByNameSingleExtractor underTest = new ByNameSingleExtractor("non-existing"); // WHEN + Throwable thrown = catchThrowable(() -> underTest.apply(map)); + // THEN + then(thrown).isInstanceOf(IntrospectionError.class); + } + + @Test + void should_extract_null_from_map_by_key_with_null_value() { + // GIVEN + Map map = mapOf(entry("key", null)); + ByNameSingleExtractor underTest = new ByNameSingleExtractor("key"); + // WHEN Object result = underTest.apply(map); // THEN then(result).isNull(); diff --git a/src/test/java/org/assertj/core/internal/ExtendedByTypesComparator_compareTo_Test.java b/src/test/java/org/assertj/core/internal/ExtendedByTypesComparator_compareTo_Test.java index a4db29ee2cb..d160eae781f 100644 --- a/src/test/java/org/assertj/core/internal/ExtendedByTypesComparator_compareTo_Test.java +++ b/src/test/java/org/assertj/core/internal/ExtendedByTypesComparator_compareTo_Test.java @@ -24,6 +24,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; +@SuppressWarnings("deprecation") class ExtendedByTypesComparator_compareTo_Test { private static final TypeComparators COMPARATORS_BY_TYPE = new TypeComparators(); diff --git a/src/test/java/org/assertj/core/internal/ExtendedByTypesComparator_toString_Test.java b/src/test/java/org/assertj/core/internal/ExtendedByTypesComparator_toString_Test.java index 38f4fbc913f..faf7ae4a8f6 100644 --- a/src/test/java/org/assertj/core/internal/ExtendedByTypesComparator_toString_Test.java +++ b/src/test/java/org/assertj/core/internal/ExtendedByTypesComparator_toString_Test.java @@ -25,6 +25,7 @@ import org.assertj.core.util.BigDecimalComparator; import org.junit.jupiter.api.Test; +@SuppressWarnings("deprecation") class ExtendedByTypesComparator_toString_Test { @Test @@ -35,8 +36,8 @@ void should_return_description_of_FieldByFieldComparator() { // THEN assertThat(actual).hasToString(format("field/property by field/property comparator on all fields/properties%n" + "Comparators used:%n" - + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}%n" - + "- for elements (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}")); + + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], Path -> lexicographic comparator (Path natural order)}%n" + + "- for elements (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], Path -> lexicographic comparator (Path natural order)}")); } @Test @@ -53,7 +54,7 @@ void should_return_description_of_FieldByFieldComparator_and_extended_types() { assertThat(actual).hasToString(format("field/property by field/property comparator on all fields/properties%n" + "Comparators used:%n" + "- for elements fields (by name): {name -> AlwaysEqualComparator}%n" - + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}%n" + + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], Path -> lexicographic comparator (Path natural order)}%n" + "- for elements (by type): {BigDecimal -> org.assertj.core.util.BigDecimalComparator}")); } } diff --git a/src/test/java/org/assertj/core/internal/FieldByFieldComparator_compareTo_Test.java b/src/test/java/org/assertj/core/internal/FieldByFieldComparator_compareTo_Test.java index 463be1cafd3..8f39f3ec698 100644 --- a/src/test/java/org/assertj/core/internal/FieldByFieldComparator_compareTo_Test.java +++ b/src/test/java/org/assertj/core/internal/FieldByFieldComparator_compareTo_Test.java @@ -17,6 +17,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +@SuppressWarnings("deprecation") class FieldByFieldComparator_compareTo_Test { private FieldByFieldComparator fieldByFieldComparator; diff --git a/src/test/java/org/assertj/core/internal/FieldByFieldComparator_toString_Test.java b/src/test/java/org/assertj/core/internal/FieldByFieldComparator_toString_Test.java index fcd537db9d1..a369e10a88a 100644 --- a/src/test/java/org/assertj/core/internal/FieldByFieldComparator_toString_Test.java +++ b/src/test/java/org/assertj/core/internal/FieldByFieldComparator_toString_Test.java @@ -20,6 +20,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +@SuppressWarnings("deprecation") class FieldByFieldComparator_toString_Test { private FieldByFieldComparator fieldByFieldComparator; @@ -33,7 +34,7 @@ public void setup() { void should_return_description_of_FieldByFieldComparator_without_field_comparators() { assertThat(fieldByFieldComparator).hasToString(format("field/property by field/property comparator on all fields/properties%n" + "Comparators used:%n" - + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}")); + + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], Path -> lexicographic comparator (Path natural order)}")); } @Test @@ -45,7 +46,7 @@ void should_return_description_of_FieldByFieldComparator_with_field_comparators( assertThat(fieldByFieldComparator).hasToString(format("field/property by field/property comparator on all fields/properties%n" + "Comparators used:%n" + "- for elements fields (by name): {name -> AlwaysEqualComparator, weight -> org.assertj.core.util.BigDecimalComparator}%n" - + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}")); + + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], Path -> lexicographic comparator (Path natural order)}")); } } diff --git a/src/test/java/org/assertj/core/internal/IgnoringFieldsComparator_compareTo_Test.java b/src/test/java/org/assertj/core/internal/IgnoringFieldsComparator_compareTo_Test.java index a31bef7e901..7394522c600 100644 --- a/src/test/java/org/assertj/core/internal/IgnoringFieldsComparator_compareTo_Test.java +++ b/src/test/java/org/assertj/core/internal/IgnoringFieldsComparator_compareTo_Test.java @@ -17,6 +17,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +@SuppressWarnings("deprecation") class IgnoringFieldsComparator_compareTo_Test { private IgnoringFieldsComparator ignoringFieldsComparator; @@ -28,29 +29,29 @@ public void setUp() { @Test void should_return_true_if_both_Objects_are_null() { - assertThat(ignoringFieldsComparator.compare(null, null)).isZero(); + assertThat(ignoringFieldsComparator.compare(null, null)).isZero(); } @Test void should_return_are_not_equal_if_first_Object_is_null_and_second_is_not() { - assertThat(ignoringFieldsComparator.compare(null, new DarthVader("I like you", "I'll kill you"))).isNotZero(); + assertThat(ignoringFieldsComparator.compare(null, new DarthVader("I like you", "I'll kill you"))).isNotZero(); } @Test void should_return_are_not_equal_if_second_Object_is_null_and_first_is_not() { - assertThat(ignoringFieldsComparator.compare(new DarthVader("I like you", "I'll kill you"), null)).isNotZero(); + assertThat(ignoringFieldsComparator.compare(new DarthVader("I like you", "I'll kill you"), null)).isNotZero(); } @Test void should_return_true_if_all_but_ignored_fields_are_equal() { - assertThat(ignoringFieldsComparator.compare(new DarthVader("I like you", "I'll kill you"), - new DarthVader("I like you", "I like you"))).isZero(); + assertThat(ignoringFieldsComparator.compare(new DarthVader("I like you", "I'll kill you"), + new DarthVader("I like you", "I like you"))).isZero(); } @Test void should_return_false_if_all_but_ignored_fields_are_not_equal() { - assertThat(ignoringFieldsComparator.compare(new DarthVader("I like you", "I'll kill you"), - new DarthVader("I'll kill you", "I'll kill you"))).isNotZero(); + assertThat(ignoringFieldsComparator.compare(new DarthVader("I like you", "I'll kill you"), + new DarthVader("I'll kill you", "I'll kill you"))).isNotZero(); } @Test @@ -60,13 +61,13 @@ void should_return_false_if_Objects_do_not_have_the_same_properties() { public static class DarthVader { - public final String telling; - public final String thinking; + public final String telling; + public final String thinking; - public DarthVader(String telling, String thinking) { - this.telling = telling; - this.thinking = thinking; - } + public DarthVader(String telling, String thinking) { + this.telling = telling; + this.thinking = thinking; + } } diff --git a/src/test/java/org/assertj/core/internal/IgnoringFieldsComparator_toString_Test.java b/src/test/java/org/assertj/core/internal/IgnoringFieldsComparator_toString_Test.java index 943bec5509a..9aedc7cd100 100644 --- a/src/test/java/org/assertj/core/internal/IgnoringFieldsComparator_toString_Test.java +++ b/src/test/java/org/assertj/core/internal/IgnoringFieldsComparator_toString_Test.java @@ -17,6 +17,7 @@ import org.junit.jupiter.api.Test; +@SuppressWarnings("deprecation") class IgnoringFieldsComparator_toString_Test { @Test @@ -25,8 +26,8 @@ void should_return_description_of_IgnoringFieldsComparator() { IgnoringFieldsComparator actual = new IgnoringFieldsComparator("a", "b"); // THEN assertThat(actual).hasToString(format("field/property by field/property comparator on all fields/properties except [\"a\", \"b\"]%n" - + "Comparators used:%n" - + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}")); + + "Comparators used:%n" + + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], Path -> lexicographic comparator (Path natural order)}")); } } diff --git a/src/test/java/org/assertj/core/internal/IterableDiff_Test.java b/src/test/java/org/assertj/core/internal/IterableDiff_Test.java index b33b57890d9..ca2241d5c58 100644 --- a/src/test/java/org/assertj/core/internal/IterableDiff_Test.java +++ b/src/test/java/org/assertj/core/internal/IterableDiff_Test.java @@ -14,6 +14,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.internal.IterableDiff.diff; +import static org.assertj.core.util.Lists.list; import static org.assertj.core.util.Lists.newArrayList; import java.util.List; @@ -105,7 +106,7 @@ void should_not_report_any_differences_between_two_case_sensitive_iterables_acco expected = newArrayList("A", "B", "C", "D"); // WHEN IterableDiff diff = diff(actual, expected, comparisonStrategy); - // THEN + // THEN6 assertThatNoDiff(diff); } @@ -147,4 +148,60 @@ private static void assertThatNoDiff(IterableDiff diff) { assertThat(diff.unexpected).isEmpty(); } + // issue #2147 + @Test + void should_work_when_comparison_strategy_is_not_symmetrical() { + // GIVEN + Address address1 = new Address(12, "xyz", "abc", "432432", "asdsa"); + Address address2 = new Address(13, "xyzx", "abcds", "32432432", "asdsdfsa"); + Address address3 = new Address(14, "xyzsa", "axbc", "4sd32432", "asdsfsda"); + List addressDtoList = list(AddressDto.from(address1), AddressDto.from(address2), AddressDto.from(address3)); + // WHEN/THEN + assertThat(addressDtoList).usingRecursiveComparison() + .isEqualTo(list(address1, address2, address3)); + assertThat(addressDtoList).asList() + .usingRecursiveFieldByFieldElementComparator() + .containsExactly(address1, address2, address3); + } + + static class Address { + int id; + String randomProperty; + String name; + String secondName; + String street; + String postCode; + + public Address(int id, String name, String secondName, String street, String postCode) { + this.id = id; + this.name = name; + this.secondName = secondName; + this.street = street; + this.postCode = postCode; + } + + } + + @SuppressWarnings("unused") + static class AddressDto { + private final int id; + private final String name; + private final String secondName; + private final String street; + private final String postCode; + + public AddressDto(int id, String name, String secondName, String street, String postCode) { + this.id = id; + this.name = name; + this.secondName = secondName; + this.street = street; + this.postCode = postCode; + } + + static AddressDto from(Address le) { + return new AddressDto(le.id, le.name, le.secondName, le.street, le.postCode); + } + + } + } diff --git a/src/test/java/org/assertj/core/internal/MapsBaseTest.java b/src/test/java/org/assertj/core/internal/MapsBaseTest.java index 91551474714..38f8e14bc60 100644 --- a/src/test/java/org/assertj/core/internal/MapsBaseTest.java +++ b/src/test/java/org/assertj/core/internal/MapsBaseTest.java @@ -24,7 +24,6 @@ import org.assertj.core.test.WithPlayerData; import org.junit.jupiter.api.BeforeEach; - /** * Base class for {@link Maps} unit tests *

    @@ -42,7 +41,7 @@ public class MapsBaseTest extends WithPlayerData { protected AssertionInfo info; @BeforeEach - public void setUp() { + protected void setUp() { actual = mapOf(entry("name", "Yoda"), entry("color", "green")); failures = spy(new Failures()); maps = new Maps(); @@ -54,8 +53,9 @@ public void setUp() { protected static MapEntry[] emptyEntries() { return new MapEntry[0]; } - + protected static String[] emptyKeys() { return new String[0]; } -} \ No newline at end of file + +} diff --git a/src/test/java/org/assertj/core/internal/OnFieldsComparator_compare_Test.java b/src/test/java/org/assertj/core/internal/OnFieldsComparator_compare_Test.java index 977cac519cf..8986d4a0698 100644 --- a/src/test/java/org/assertj/core/internal/OnFieldsComparator_compare_Test.java +++ b/src/test/java/org/assertj/core/internal/OnFieldsComparator_compare_Test.java @@ -17,6 +17,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +@SuppressWarnings("deprecation") class OnFieldsComparator_compare_Test { private OnFieldsComparator onFieldsComparator; @@ -28,31 +29,31 @@ public void setUp() { @Test void should_return_true_if_both_Objects_are_null() { - assertThat(onFieldsComparator.compare(null, null)).isZero(); + assertThat(onFieldsComparator.compare(null, null)).isZero(); } @Test void should_return_are_not_equal_if_first_Object_is_null_and_second_is_not() { - assertThat(onFieldsComparator.compare(null, new DarthVader("I like you", "I'll kill you"))).isNotZero(); + assertThat(onFieldsComparator.compare(null, new DarthVader("I like you", "I'll kill you"))).isNotZero(); } @Test void should_return_are_not_equal_if_second_Object_is_null_and_first_is_not() { - assertThat(onFieldsComparator.compare(new DarthVader("I like you", "I'll kill you"), null)).isNotZero(); + assertThat(onFieldsComparator.compare(new DarthVader("I like you", "I'll kill you"), null)).isNotZero(); } @Test void should_return_true_if_given_fields_are_equal() { - DarthVader actual = new DarthVader("I like you", "I'll kill you"); - DarthVader other = new DarthVader("I like you", "I like you"); - assertThat(onFieldsComparator.compare(actual, other)).isZero(); + DarthVader actual = new DarthVader("I like you", "I'll kill you"); + DarthVader other = new DarthVader("I like you", "I like you"); + assertThat(onFieldsComparator.compare(actual, other)).isZero(); } @Test void should_return_false_if_given_fields_are_not_equal() { - DarthVader actual = new DarthVader("I like you", "I'll kill you"); - DarthVader other = new DarthVader("I'll kill you", "I'll kill you"); - assertThat(onFieldsComparator.compare(actual, other)).isNotZero(); + DarthVader actual = new DarthVader("I like you", "I'll kill you"); + DarthVader other = new DarthVader("I'll kill you", "I'll kill you"); + assertThat(onFieldsComparator.compare(actual, other)).isNotZero(); } @Test @@ -62,13 +63,13 @@ void should_return_false_if_Objects_do_not_have_the_same_properties() { public static class DarthVader { - public final String telling; - public final String thinking; + public final String telling; + public final String thinking; - public DarthVader(String telling, String thinking) { - this.telling = telling; - this.thinking = thinking; - } + public DarthVader(String telling, String thinking) { + this.telling = telling; + this.thinking = thinking; + } } diff --git a/src/test/java/org/assertj/core/internal/OnFieldsComparator_creation_Test.java b/src/test/java/org/assertj/core/internal/OnFieldsComparator_creation_Test.java index 16f8875e718..57402825708 100644 --- a/src/test/java/org/assertj/core/internal/OnFieldsComparator_creation_Test.java +++ b/src/test/java/org/assertj/core/internal/OnFieldsComparator_creation_Test.java @@ -17,6 +17,7 @@ import org.junit.jupiter.api.Test; +@SuppressWarnings("deprecation") class OnFieldsComparator_creation_Test { @Test diff --git a/src/test/java/org/assertj/core/internal/OnFieldsComparator_toString_Test.java b/src/test/java/org/assertj/core/internal/OnFieldsComparator_toString_Test.java index e74ac3aab21..c03a0f00cf7 100644 --- a/src/test/java/org/assertj/core/internal/OnFieldsComparator_toString_Test.java +++ b/src/test/java/org/assertj/core/internal/OnFieldsComparator_toString_Test.java @@ -17,6 +17,7 @@ import org.junit.jupiter.api.Test; +@SuppressWarnings("deprecation") class OnFieldsComparator_toString_Test { @Test @@ -26,7 +27,7 @@ void should_return_description_for_multiple_given_fields() { // THEN assertThat(actual).hasToString(format("field/property by field/property comparator on fields/properties [\"a\", \"b\"]%n" + "Comparators used:%n" - + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}")); + + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], Path -> lexicographic comparator (Path natural order)}")); } @Test @@ -36,7 +37,7 @@ void should_return_description_for_a_single_given_field() { // THEN assertThat(actual).hasToString(format("single field/property comparator on field/property \"a\"%n" + "Comparators used:%n" - + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}")); + + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6], Path -> lexicographic comparator (Path natural order)}")); } } diff --git a/src/test/java/org/assertj/core/internal/RecursiveFieldByFieldComparator_compareTo_Test.java b/src/test/java/org/assertj/core/internal/RecursiveFieldByFieldComparator_compareTo_Test.java deleted file mode 100644 index 259d9d60f52..00000000000 --- a/src/test/java/org/assertj/core/internal/RecursiveFieldByFieldComparator_compareTo_Test.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - * Copyright 2012-2021 the original author or authors. - */ -package org.assertj.core.internal; - -import static java.util.Collections.EMPTY_MAP; -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.jupiter.api.Test; - -class RecursiveFieldByFieldComparator_compareTo_Test { - - private static final RecursiveFieldByFieldComparator RECURSIVE_FIELD_BY_FIELD_COMPARATOR = new RecursiveFieldByFieldComparator(EMPTY_MAP, - new TypeComparators()); - - @Test - void should_return_true_if_Objects_are_equal() { - assertThat(RECURSIVE_FIELD_BY_FIELD_COMPARATOR.compare(new Foo("id", new Bar(1)), - new Foo("id", new Bar(1)))).isZero(); - } - - @Test - void should_return_false_if_Objects_are_not_equal() { - assertThat(RECURSIVE_FIELD_BY_FIELD_COMPARATOR.compare(new Foo("id", new Bar(1)), - new Foo("id", new Bar(2)))).isNotZero(); - } - - @Test - void should_return_are_not_equal_if_first_Object_is_null_and_second_is_not() { - assertThat(RECURSIVE_FIELD_BY_FIELD_COMPARATOR.compare(null, new Foo("id", new Bar(1)))).isNotZero(); - } - - @Test - void should_return_are_not_equal_if_second_Object_is_null_and_first_is_not() { - assertThat(RECURSIVE_FIELD_BY_FIELD_COMPARATOR.compare(new Foo("id", new Bar(1)), null)).isNotZero(); - } - - @Test - void should_return_are_not_equal_if_Objects_do_not_have_the_same_properties() { - assertThat(RECURSIVE_FIELD_BY_FIELD_COMPARATOR.compare(new Foo("id", new Bar(1)), 2)).isNotZero(); - } - - public static class Foo { - public String id; - public Bar bar; - - public Foo(String id, Bar bar) { - this.id = id; - this.bar = bar; - } - } - - public static class Bar { - public int id; - - public Bar(int id) { - this.id = id; - } - } - -} diff --git a/src/test/java/org/assertj/core/internal/RecursiveFieldByFieldComparator_toString_Test.java b/src/test/java/org/assertj/core/internal/RecursiveFieldByFieldComparator_toString_Test.java deleted file mode 100644 index 5688359a102..00000000000 --- a/src/test/java/org/assertj/core/internal/RecursiveFieldByFieldComparator_toString_Test.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - * Copyright 2012-2021 the original author or authors. - */ -package org.assertj.core.internal; - -import static java.lang.String.format; -import static java.util.Collections.EMPTY_MAP; -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.jupiter.api.Test; - -class RecursiveFieldByFieldComparator_toString_Test { - - @Test - void should_return_description_of_RecursiveFieldByFieldComparator() { - // GIVEN - RecursiveFieldByFieldComparator actual = new RecursiveFieldByFieldComparator(EMPTY_MAP, new TypeComparators()); - // THEN - assertThat(actual).hasToString(format("recursive field/property by field/property comparator on all fields/properties%n" - + "Comparators used:%n" - + "- for elements fields (by type): {Double -> DoubleComparator[precision=1.0E-15], Float -> FloatComparator[precision=1.0E-6]}")); - } -} diff --git a/src/test/java/org/assertj/core/internal/StandardComparisonStrategy_areEqual_Test.java b/src/test/java/org/assertj/core/internal/StandardComparisonStrategy_areEqual_Test.java index 0b75f2ef6ac..0d4d14a934c 100644 --- a/src/test/java/org/assertj/core/internal/StandardComparisonStrategy_areEqual_Test.java +++ b/src/test/java/org/assertj/core/internal/StandardComparisonStrategy_areEqual_Test.java @@ -12,78 +12,417 @@ */ package org.assertj.core.internal; -import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.assertj.core.api.BDDAssertions.then; +import static org.junit.jupiter.params.provider.Arguments.arguments; -import org.assertj.core.util.Objects; +import java.util.stream.Stream; + +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; /** - * Tests for {@link StandardComparisonStrategy#areEqual(Object, Object)}.
    - * Conceptually the same as {@link Objects#areEqual(Object, Object)} but I don't know how to verify/test that - * {@link StandardComparisonStrategy#areEqual(Object, Object)} simply calls {@link Objects#areEqual(Object, Object)} + * Tests for {@link StandardComparisonStrategy#areEqual(Object, Object)}. * * @author Joel Costigliola */ +@DisplayName("StandardComparisonStrategy areEqual") class StandardComparisonStrategy_areEqual_Test { - private static StandardComparisonStrategy standardComparisonStrategy = StandardComparisonStrategy.instance(); + private final StandardComparisonStrategy underTest = StandardComparisonStrategy.instance(); + + @Test + void should_return_true_if_both_actual_and_other_are_null() { + // WHEN + boolean result = underTest.areEqual(null, null); + // THEN + then(result).isTrue(); + } + + @Test + void should_return_false_if_actual_is_null_and_other_is_not() { + // GIVEN + Object other = new Object(); + // WHEN + boolean result = underTest.areEqual(null, other); + // THEN + then(result).isFalse(); + } + + @Test + void should_return_true_if_Object_arrays_are_equal() { + // GIVEN + Object[] actual = { "Luke", "Yoda", "Leia" }; + Object[] other = { "Luke", "Yoda", "Leia" }; + // WHEN + boolean result = underTest.areEqual(actual, other); + // THEN + then(result).isTrue(); + } @Test - void should_return_true_if_both_Objects_are_null_with_verify() { - assertThat(standardComparisonStrategy.areEqual(null, null)).isTrue(); + void should_return_false_if_Object_arrays_are_not_equal() { + // GIVEN + Object[] actual = { "Luke", "Leia", "Yoda" }; + Object[] other = { "Luke", "Yoda", "Leia" }; + // WHEN + boolean result = underTest.areEqual(actual, other); + // THEN + then(result).isFalse(); } @Test - void should_return_true_if_both_Objects_are_null() { - assertThat(standardComparisonStrategy.areEqual(null, null)).isTrue(); + void should_return_true_if_byte_arrays_are_equal() { + // GIVEN + byte[] actual = { 1, 2, 3 }; + byte[] other = { 1, 2, 3 }; + // WHEN + boolean result = underTest.areEqual(actual, other); + // THEN + then(result).isTrue(); } @Test - void should_return_true_if_Objects_are_equal() { - assertThat(standardComparisonStrategy.areEqual("Yoda", "Yoda")).isTrue(); + void should_return_false_if_byte_arrays_are_not_equal() { + // GIVEN + byte[] actual = { 1, 2, 3 }; + byte[] other = { 4, 5, 6 }; + // WHEN + boolean result = underTest.areEqual(actual, other); + // THEN + then(result).isFalse(); } @Test - void should_return_are_not_equal_if_first_Object_is_null_and_second_is_not() { - assertThat(standardComparisonStrategy.areEqual(null, "Yoda")).isFalse(); + void should_return_true_if_short_arrays_are_equal() { + // GIVEN + short[] actual = { 1, 2, 3 }; + short[] other = { 1, 2, 3 }; + // WHEN + boolean result = underTest.areEqual(actual, other); + // THEN + then(result).isTrue(); } @Test - void should_return_are_not_equal_if_second_Object_is_null_and_first_is_not() { - assertThat(standardComparisonStrategy.areEqual("Yoda", null)).isFalse(); + void should_return_false_if_short_arrays_are_not_equal() { + // GIVEN + short[] actual = { 1, 2, 3 }; + short[] other = { 4, 5, 6 }; + // WHEN + boolean result = underTest.areEqual(actual, other); + // THEN + then(result).isFalse(); } @Test - void should_return_are_not_equal_if_Objects_are_not_equal() { - assertThat(standardComparisonStrategy.areEqual("Yoda", 2)).isFalse(); + void should_return_true_if_int_arrays_are_equal() { + // GIVEN + int[] actual = { 1, 2, 3 }; + int[] other = { 1, 2, 3 }; + // WHEN + boolean result = underTest.areEqual(actual, other); + // THEN + then(result).isTrue(); } @Test - void should_return_true_if_arrays_of_Objects_are_equal() { - Object[] a1 = { "Luke", "Yoda", "Leia" }; - Object[] a2 = { "Luke", "Yoda", "Leia" }; - assertThat(standardComparisonStrategy.areEqual(a1, a2)).isTrue(); + void should_return_false_if_int_arrays_are_not_equal() { + // GIVEN + int[] actual = { 1, 2, 3 }; + int[] other = { 4, 5, 6 }; + // WHEN + boolean result = underTest.areEqual(actual, other); + // THEN + then(result).isFalse(); } @Test - void should_return_true_if_arrays_of_primitives_are_equal() { - int[] a1 = { 6, 8, 10 }; - int[] a2 = { 6, 8, 10 }; - assertThat(standardComparisonStrategy.areEqual(a1, a2)).isTrue(); + void should_return_true_if_long_arrays_are_equal() { + // GIVEN + long[] actual = { 1L, 2L, 3L }; + long[] other = { 1L, 2L, 3L }; + // WHEN + boolean result = underTest.areEqual(actual, other); + // THEN + then(result).isTrue(); } @Test - void should_return_false_if_arrays_of_Objects_are_not_equal() { - Object[] a1 = { "Luke", "Yoda", "Leia" }; - Object[] a2 = new Object[0]; - assertThat(standardComparisonStrategy.areEqual(a1, a2)).isFalse(); + void should_return_false_if_long_arrays_are_not_equal() { + // GIVEN + long[] actual = { 1L, 2L, 3L }; + long[] other = { 4L, 5L, 6L }; + // WHEN + boolean result = underTest.areEqual(actual, other); + // THEN + then(result).isFalse(); } @Test - void should_return_false_if_arrays_of_primitives_are_not_equal() { - int[] a1 = { 6, 8, 10 }; - boolean[] a2 = { true }; - assertThat(standardComparisonStrategy.areEqual(a1, a2)).isFalse(); + void should_return_true_if_char_arrays_are_equal() { + // GIVEN + char[] actual = { '1', '2', '3' }; + char[] other = { '1', '2', '3' }; + // WHEN + boolean result = underTest.areEqual(actual, other); + // THEN + then(result).isTrue(); + } + + @Test + void should_return_false_if_char_arrays_are_not_equal() { + // GIVEN + char[] actual = { '1', '2', '3' }; + char[] other = { '4', '5', '6' }; + // WHEN + boolean result = underTest.areEqual(actual, other); + // THEN + then(result).isFalse(); + } + + @Test + void should_return_true_if_float_arrays_are_equal() { + // GIVEN + float[] actual = { 1.0f, 2.0f, 3.0f }; + float[] other = { 1.0f, 2.0f, 3.0f }; + // WHEN + boolean result = underTest.areEqual(actual, other); + // THEN + then(result).isTrue(); + } + + @Test + void should_return_false_if_float_arrays_are_not_equal() { + // GIVEN + float[] actual = { 1.0f, 2.0f, 3.0f }; + float[] other = { 4.0f, 5.0f, 6.0f }; + // WHEN + boolean result = underTest.areEqual(actual, other); + // THEN + then(result).isFalse(); + } + + @Test + void should_return_true_if_double_arrays_are_equal() { + // GIVEN + double[] actual = { 1.0, 2.0, 3.0 }; + double[] other = { 1.0, 2.0, 3.0 }; + // WHEN + boolean result = underTest.areEqual(actual, other); + // THEN + then(result).isTrue(); + } + + @Test + void should_return_false_if_double_arrays_are_not_equal() { + // GIVEN + double[] actual = { 1.0, 2.0, 3.0 }; + double[] other = { 4.0, 5.0, 6.0 }; + // WHEN + boolean result = underTest.areEqual(actual, other); + // THEN + then(result).isFalse(); + } + + @Test + void should_return_true_if_boolean_arrays_are_equal() { + // GIVEN + boolean[] actual = { true, false }; + boolean[] other = { true, false }; + // WHEN + boolean result = underTest.areEqual(actual, other); + // THEN + then(result).isTrue(); + } + + @Test + void should_return_false_if_boolean_arrays_are_not_equal() { + // GIVEN + boolean[] actual = { true, false }; + boolean[] other = { false, true }; + // WHEN + boolean result = underTest.areEqual(actual, other); + // THEN + then(result).isFalse(); + } + + @Test + void should_fail_if_equals_implementation_fails() { + // GIVEN + Object actual = new EqualsThrowsException(); + // WHEN + Throwable thrown = catchThrowable(() -> underTest.areEqual(actual, new Object())); + // THEN + then(thrown).isInstanceOf(RuntimeException.class) + .hasMessage("Boom!"); + } + + private static class EqualsThrowsException { + + @Override + public boolean equals(Object obj) { + throw new RuntimeException("Boom!"); + } + + } + + @ParameterizedTest + @MethodSource({ "correctEquals", "contractViolatingEquals" }) + void should_delegate_to_equals_implementation_if_actual_is_not_null(Object actual, Object other, boolean expected) { + // WHEN + boolean result = underTest.areEqual(actual, other); + // THEN + then(result).isEqualTo(expected); + } + + @Test + void should_work_with_inconsistent_equals_methods() { + NonConsistent nonConsistentX = new NonConsistent(); + + boolean firstInvocation = underTest.areEqual(nonConsistentX, nonConsistentX); + then(firstInvocation).isEqualTo(true); + boolean secondInvocation = underTest.areEqual(nonConsistentX, nonConsistentX); + then(secondInvocation).isEqualTo(false); + boolean thirdInvocation = underTest.areEqual(nonConsistentX, nonConsistentX); + then(thirdInvocation).isEqualTo(true); + } + + private static Stream correctEquals() { + Object object = new Object(); + + return Stream.of(arguments(object, null, false), + arguments(object, object, true), + arguments(object, new Object(), false), + arguments("Luke", null, false), + arguments("Luke", "Luke", true), + arguments("Luke", "Yoda", false)); + } + + private static Stream contractViolatingEquals() { + AlwaysTrue alwaysTrue = new AlwaysTrue(); + AlwaysFalse alwaysFalse = new AlwaysFalse(); + + NonReflexive nonReflexiveX = new NonReflexive(); + + NonSymmetric nonSymmetricY = new NonSymmetric(null); + NonSymmetric nonSymmetricX = new NonSymmetric(nonSymmetricY); + + NonTransitive nonTransitiveZ = new NonTransitive(null, null); + NonTransitive nonTransitiveY = new NonTransitive(nonTransitiveZ, null); + NonTransitive nonTransitiveX = new NonTransitive(nonTransitiveY, nonTransitiveZ); + + + return Stream.of(arguments(alwaysTrue, null, true), + arguments(alwaysFalse, alwaysFalse, false), + arguments(nonReflexiveX, nonReflexiveX, false), + arguments(nonSymmetricX, nonSymmetricY, true), + arguments(nonSymmetricY, nonSymmetricX, false), + arguments(nonTransitiveX, nonTransitiveY, true), + arguments(nonTransitiveY, nonTransitiveZ, true), + arguments(nonTransitiveX, nonTransitiveZ, false)); + } + + private static class AlwaysTrue { + + @Override + public boolean equals(Object obj) { + return true; + } + + @Override + public String toString() { + return "always true"; + } + + } + + private static class AlwaysFalse { + + @Override + public boolean equals(Object obj) { + return false; + } + + @Override + public String toString() { + return "always false"; + } + + } + + private static class NonReflexive { + + @Override + public boolean equals(Object obj) { + return this != obj; + } + + @Override + public String toString() { + return "non reflexive"; + } + + } + + private static class NonSymmetric { + + private final Object other; + + NonSymmetric(Object other) { + this.other = other; + } + + @Override + public boolean equals(Object obj) { + return obj == other; + } + + @Override + public String toString() { + return "non symmetric"; + } + + } + + private static class NonTransitive { + + private final Object y, z; + + NonTransitive(Object y, Object z) { + this.y = y; + this.z = z; + } + + @Override + public boolean equals(Object obj) { + return obj == y || obj != z; + } + + @Override + public String toString() { + return "non transitive"; + } + + } + + private static class NonConsistent { + + private int i = 0; + + @Override + public boolean equals(Object obj) { + return (++i % 2) != 0; + } + + @Override + public String toString() { + return "non consistent"; + } + } } diff --git a/src/test/java/org/assertj/core/internal/bigdecimals/BigDecimals_assertIsNotNegative_Test.java b/src/test/java/org/assertj/core/internal/bigdecimals/BigDecimals_assertIsNotNegative_Test.java index 2039288e937..acfa2f7074a 100644 --- a/src/test/java/org/assertj/core/internal/bigdecimals/BigDecimals_assertIsNotNegative_Test.java +++ b/src/test/java/org/assertj/core/internal/bigdecimals/BigDecimals_assertIsNotNegative_Test.java @@ -41,7 +41,7 @@ void should_succeed_since_actual_is_zero() { @Test void should_fail_since_actual_is_negative() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> numbers.assertIsNotNegative(someInfo(), new BigDecimal(-6))) - .withMessage(format("%nExpecting:%n -6%nto be greater than or equal to:%n 0%n")); + .withMessage(format("%nExpecting actual:%n -6%nto be greater than or equal to:%n 0%n")); } @Test diff --git a/src/test/java/org/assertj/core/internal/bigdecimals/BigDecimals_assertIsNotZero_Test.java b/src/test/java/org/assertj/core/internal/bigdecimals/BigDecimals_assertIsNotZero_Test.java index 67988165b25..f07a51585bb 100644 --- a/src/test/java/org/assertj/core/internal/bigdecimals/BigDecimals_assertIsNotZero_Test.java +++ b/src/test/java/org/assertj/core/internal/bigdecimals/BigDecimals_assertIsNotZero_Test.java @@ -40,7 +40,7 @@ void should_succeed_since_actual_is_zero() { @Test void should_fail_since_actual_is_not_zero() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> numbers.assertIsNotZero(someInfo(), BigDecimal.ZERO)) - .withMessage(format("%nExpecting:%n 0%nnot to be equal to:%n 0%n")); + .withMessage(format("%nExpecting actual:%n 0%nnot to be equal to:%n 0%n")); } @Test @@ -51,7 +51,7 @@ void should_succeed_since_actual_is_zero_whatever_custom_comparison_strategy_is( @Test void should_fail_since_actual_is_not_zero_whatever_custom_comparison_strategy_is() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> numbersWithComparatorComparisonStrategy.assertIsNotZero(someInfo(), BigDecimal.ZERO)) - .withMessage(format("%nExpecting:%n 0%nnot to be equal to:%n 0%n")); + .withMessage(format("%nExpecting actual:%n 0%nnot to be equal to:%n 0%n")); } } diff --git a/src/test/java/org/assertj/core/internal/bigdecimals/BigDecimals_assertIsPositive_Test.java b/src/test/java/org/assertj/core/internal/bigdecimals/BigDecimals_assertIsPositive_Test.java index fc51f5fb167..22d93feb2c0 100644 --- a/src/test/java/org/assertj/core/internal/bigdecimals/BigDecimals_assertIsPositive_Test.java +++ b/src/test/java/org/assertj/core/internal/bigdecimals/BigDecimals_assertIsPositive_Test.java @@ -38,13 +38,13 @@ void should_succeed_since_actual_is_positive() { @Test void should_fail_since_actual_is_not_positive() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> numbers.assertIsPositive(someInfo(), BigDecimal.ZERO)) - .withMessage(format("%nExpecting:%n 0%nto be greater than:%n 0%n")); + .withMessage(format("%nExpecting actual:%n 0%nto be greater than:%n 0%n")); } @Test void should_fail_since_actual_is_zero() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> numbers.assertIsPositive(someInfo(), BigDecimal.ZERO)) - .withMessage(format("%nExpecting:%n 0%nto be greater than:%n 0%n")); + .withMessage(format("%nExpecting actual:%n 0%nto be greater than:%n 0%n")); } @Test @@ -56,7 +56,7 @@ void should_succeed_since_actual_is_positive_according_to_custom_comparison_stra void should_fail_since_actual_is_not_positive_according_to_custom_comparison_strategy() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> numbersWithComparatorComparisonStrategy.assertIsPositive(someInfo(), BigDecimal.ZERO)) - .withMessage(format("%nExpecting:%n 0%nto be greater than:%n 0%nwhen comparing values using org.assertj.core.util.BigDecimalComparator")); + .withMessage(format("%nExpecting actual:%n 0%nto be greater than:%n 0%nwhen comparing values using org.assertj.core.util.BigDecimalComparator")); } } diff --git a/src/test/java/org/assertj/core/internal/bigintegers/BigIntegers_assertIsNotNegative_Test.java b/src/test/java/org/assertj/core/internal/bigintegers/BigIntegers_assertIsNotNegative_Test.java index b631df7b10f..58309d7c9da 100644 --- a/src/test/java/org/assertj/core/internal/bigintegers/BigIntegers_assertIsNotNegative_Test.java +++ b/src/test/java/org/assertj/core/internal/bigintegers/BigIntegers_assertIsNotNegative_Test.java @@ -40,7 +40,7 @@ void should_succeed_since_actual_is_zero() { void should_fail_since_actual_is_negative() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> numbers.assertIsNotNegative(someInfo(), new BigInteger("-6"))) - .withMessage(format("%nExpecting:%n -6%nto be greater than or equal to:%n 0%n")); + .withMessage(format("%nExpecting actual:%n -6%nto be greater than or equal to:%n 0%n")); } @Test diff --git a/src/test/java/org/assertj/core/internal/bigintegers/BigIntegers_assertIsNotZero_Test.java b/src/test/java/org/assertj/core/internal/bigintegers/BigIntegers_assertIsNotZero_Test.java index 41a9b0e05e1..ce8f9c838e0 100644 --- a/src/test/java/org/assertj/core/internal/bigintegers/BigIntegers_assertIsNotZero_Test.java +++ b/src/test/java/org/assertj/core/internal/bigintegers/BigIntegers_assertIsNotZero_Test.java @@ -36,7 +36,7 @@ void should_succeed_since_actual_is_zero() { @Test void should_fail_since_actual_is_not_zero() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> numbers.assertIsNotZero(someInfo(), BigInteger.ZERO)) - .withMessage(format("%nExpecting:%n 0%nnot to be equal to:%n 0%n")); + .withMessage(format("%nExpecting actual:%n 0%nnot to be equal to:%n 0%n")); } @Test @@ -47,7 +47,7 @@ void should_succeed_since_actual_is_zero_whatever_custom_comparison_strategy_is( @Test void should_fail_since_actual_is_not_zero_whatever_custom_comparison_strategy_is() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> numbersWithComparatorComparisonStrategy.assertIsNotZero(someInfo(), BigInteger.ZERO)) - .withMessage(format("%nExpecting:%n 0%nnot to be equal to:%n 0%n")); + .withMessage(format("%nExpecting actual:%n 0%nnot to be equal to:%n 0%n")); } } diff --git a/src/test/java/org/assertj/core/internal/bigintegers/BigIntegers_assertIsPositive_Test.java b/src/test/java/org/assertj/core/internal/bigintegers/BigIntegers_assertIsPositive_Test.java index ab8172e374e..621281cb492 100644 --- a/src/test/java/org/assertj/core/internal/bigintegers/BigIntegers_assertIsPositive_Test.java +++ b/src/test/java/org/assertj/core/internal/bigintegers/BigIntegers_assertIsPositive_Test.java @@ -35,13 +35,13 @@ void should_succeed_since_actual_is_positive() { @Test void should_fail_since_actual_is_not_positive() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> numbers.assertIsPositive(someInfo(), BigInteger.ZERO)) - .withMessage(format("%nExpecting:%n 0%nto be greater than:%n 0%n")); + .withMessage(format("%nExpecting actual:%n 0%nto be greater than:%n 0%n")); } @Test void should_fail_since_actual_is_zero() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> numbers.assertIsPositive(someInfo(), BigInteger.ZERO)) - .withMessage(format("%nExpecting:%n 0%nto be greater than:%n 0%n")); + .withMessage(format("%nExpecting actual:%n 0%nto be greater than:%n 0%n")); } @Test @@ -53,7 +53,7 @@ void should_succeed_since_actual_is_positive_according_to_custom_comparison_stra void should_fail_since_actual_is_not_positive_according_to_custom_comparison_strategy() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> numbersWithComparatorComparisonStrategy.assertIsPositive(someInfo(), BigInteger.ZERO)) - .withMessage(format("%nExpecting:%n 0%nto be greater than:%n 0%nwhen comparing values using BigIntegerComparator")); + .withMessage(format("%nExpecting actual:%n 0%nto be greater than:%n 0%nwhen comparing values using BigIntegerComparator")); } } diff --git a/src/test/java/org/assertj/core/internal/bytes/Bytes_assertIsNotNegative_Test.java b/src/test/java/org/assertj/core/internal/bytes/Bytes_assertIsNotNegative_Test.java index 9bec0a6e9d8..229982b2931 100644 --- a/src/test/java/org/assertj/core/internal/bytes/Bytes_assertIsNotNegative_Test.java +++ b/src/test/java/org/assertj/core/internal/bytes/Bytes_assertIsNotNegative_Test.java @@ -40,13 +40,13 @@ void should_succeed_since_actual_is_zero() { @Test void should_fail_since_actual_is_negative() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> bytes.assertIsNotNegative(someInfo(), (byte) -6)) - .withMessage(format("%nExpecting:%n -6%nto be greater than or equal to:%n 0%n")); + .withMessage(format("%nExpecting actual:%n -6%nto be greater than or equal to:%n 0%n")); } @Test void should_fail_since_actual_is_negative_in_hex_representation() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> bytes.assertIsNotNegative(someHexInfo(), (byte) 0xFA)) - .withMessage(format("%nExpecting:%n 0xFA%nto be greater than or equal to:%n 0x00%n")); + .withMessage(format("%nExpecting actual:%n 0xFA%nto be greater than or equal to:%n 0x00%n")); } @Test diff --git a/src/test/java/org/assertj/core/internal/bytes/Bytes_assertIsNotZero_Test.java b/src/test/java/org/assertj/core/internal/bytes/Bytes_assertIsNotZero_Test.java index 03444473d6e..9ac7a947623 100644 --- a/src/test/java/org/assertj/core/internal/bytes/Bytes_assertIsNotZero_Test.java +++ b/src/test/java/org/assertj/core/internal/bytes/Bytes_assertIsNotZero_Test.java @@ -39,13 +39,13 @@ void should_succeed_since_actual_is_not_zero() { @Test void should_fail_since_actual_is_zero() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> bytes.assertIsNotZero(someInfo(), (byte) 0)) - .withMessage(format("%nExpecting:%n 0%nnot to be equal to:%n 0%n")); + .withMessage(format("%nExpecting actual:%n 0%nnot to be equal to:%n 0%n")); } @Test void should_fail_since_actual_is_zero_in_hex_representation() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> bytes.assertIsNotZero(someHexInfo(), (byte) 0x00)) - .withMessage(format("%nExpecting:%n 0x00%nnot to be equal to:%n 0x00%n")); + .withMessage(format("%nExpecting actual:%n 0x00%nnot to be equal to:%n 0x00%n")); } @Test @@ -61,13 +61,13 @@ void should_succeed_since_actual_is_zero_whatever_custom_comparison_strategy_is_ @Test void should_fail_since_actual_is_not_zero_whatever_custom_comparison_strategy_is() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> bytesWithAbsValueComparisonStrategy.assertIsNotZero(someInfo(), (byte) 0)) - .withMessage(format("%nExpecting:%n 0%nnot to be equal to:%n 0%n")); + .withMessage(format("%nExpecting actual:%n 0%nnot to be equal to:%n 0%n")); } @Test void should_fail_since_actual_is_not_zero_whatever_custom_comparison_strategy_is_in_hex_representation() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> bytesWithAbsValueComparisonStrategy.assertIsNotZero(someHexInfo(), (byte) 0x00)) - .withMessage(format("%nExpecting:%n 0x00%nnot to be equal to:%n 0x00%n")); + .withMessage(format("%nExpecting actual:%n 0x00%nnot to be equal to:%n 0x00%n")); } } diff --git a/src/test/java/org/assertj/core/internal/bytes/Bytes_assertIsPositive_Test.java b/src/test/java/org/assertj/core/internal/bytes/Bytes_assertIsPositive_Test.java index 6693e63e8e4..a285f920a1a 100644 --- a/src/test/java/org/assertj/core/internal/bytes/Bytes_assertIsPositive_Test.java +++ b/src/test/java/org/assertj/core/internal/bytes/Bytes_assertIsPositive_Test.java @@ -38,13 +38,13 @@ void should_succeed_since_actual_is_positive() { @Test void should_fail_since_actual_is_not_positive() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> bytes.assertIsPositive(someInfo(), (byte) -1)) - .withMessage(format("%nExpecting:%n -1%nto be greater than:%n 0%n")); + .withMessage(format("%nExpecting actual:%n -1%nto be greater than:%n 0%n")); } @Test void should_fail_since_actual_is_not_positive_in_hex_representation() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> bytes.assertIsPositive(someHexInfo(), (byte) 0xFA)) - .withMessage(format("%nExpecting:%n 0xFA%nto be greater than:%n 0x00%n")); + .withMessage(format("%nExpecting actual:%n 0xFA%nto be greater than:%n 0x00%n")); } @Test @@ -56,13 +56,13 @@ void should_succeed_since_actual_is_positive_according_to_custom_comparison_stra void should_fail_since_actual_is_not_positive_according_to_custom_comparison_strategy() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> bytesWithAbsValueComparisonStrategy.assertIsPositive(someInfo(), (byte) 0)) - .withMessage(format("%nExpecting:%n 0%nto be greater than:%n 0%nwhen comparing values using AbsValueComparator")); + .withMessage(format("%nExpecting actual:%n 0%nto be greater than:%n 0%nwhen comparing values using AbsValueComparator")); } @Test void should_fail_since_actual_is_not_positive_according_to_custom_comparison_strategy_in_hex_representation() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> bytesWithAbsValueComparisonStrategy.assertIsPositive(someHexInfo(), (byte) 0x00)) - .withMessage(format("%nExpecting:%n 0x00%nto be greater than:%n 0x00%nwhen comparing values using AbsValueComparator")); + .withMessage(format("%nExpecting actual:%n 0x00%nto be greater than:%n 0x00%nwhen comparing values using AbsValueComparator")); } } diff --git a/src/test/java/org/assertj/core/internal/classes/Classes_assertContainsAnnotation_Test.java b/src/test/java/org/assertj/core/internal/classes/Classes_assertContainsAnnotation_Test.java index 17a84171c5f..2aa11a7a7e0 100644 --- a/src/test/java/org/assertj/core/internal/classes/Classes_assertContainsAnnotation_Test.java +++ b/src/test/java/org/assertj/core/internal/classes/Classes_assertContainsAnnotation_Test.java @@ -12,11 +12,14 @@ */ package org.assertj.core.internal.classes; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatNullPointerException; +import static org.assertj.core.api.BDDAssertions.then; import static org.assertj.core.error.ShouldHaveAnnotations.shouldHaveAnnotations; import static org.assertj.core.test.TestData.someInfo; +import static org.assertj.core.util.Arrays.array; +import static org.assertj.core.util.AssertionsUtil.expectAssertionError; import static org.assertj.core.util.FailureMessages.actualIsNull; +import static org.assertj.core.util.Sets.newLinkedHashSet; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; @@ -26,12 +29,11 @@ import org.assertj.core.api.AssertionInfo; import org.assertj.core.internal.ClassesBaseTest; -import org.assertj.core.util.Sets; import org.junit.jupiter.api.Test; /** * Tests for {@link org.assertj.core.internal.Classes#assertContainsAnnotations(org.assertj.core.api.AssertionInfo, Class, Class[])}. - * + * * @author William Delanoue */ class Classes_assertContainsAnnotation_Test extends ClassesBaseTest { @@ -46,50 +48,50 @@ class Classes_assertContainsAnnotation_Test extends ClassesBaseTest { private static class AnnotatedClass { } - @SuppressWarnings("unchecked") @Test void should_fail_if_actual_is_null() { + // GIVEN actual = null; - assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> classes.assertContainsAnnotations(someInfo(), actual, - Override.class)) - .withMessage(actualIsNull()); + // WHEN + AssertionError assertionError = expectAssertionError(() -> classes.assertContainsAnnotations(someInfo(), actual, + array(Override.class))); + // THEN + then(assertionError).hasMessage(actualIsNull()); } - @SuppressWarnings("unchecked") @Test void should_fail_if_expected_has_null_value() { + // GIVEN actual = AssertionInfo.class; + // WHEN/THEN assertThatNullPointerException().isThrownBy(() -> classes.assertContainsAnnotations(someInfo(), actual, - Override.class, null, - Deprecated.class)) + array(Override.class, null, + Deprecated.class))) .withMessage("The class to compare actual with should not be null"); } - @SuppressWarnings("unchecked") @Test void should_pass_if_expected_is_empty() { actual = AssertionInfo.class; - classes.assertContainsAnnotations(someInfo(), actual); + classes.assertContainsAnnotations(someInfo(), actual, array()); } - @SuppressWarnings("unchecked") @Test void should_pass_if_actual_have_annotation() { actual = AnnotatedClass.class; - classes.assertContainsAnnotations(someInfo(), actual, MyAnnotation.class); + classes.assertContainsAnnotations(someInfo(), actual, array(MyAnnotation.class)); } @SuppressWarnings("unchecked") @Test void should_fail_if_actual_does_not_contains_an_annotation() { - actual = AnnotatedClass.class; + // GIVEN Class[] expected = new Class[] { Override.class, Deprecated.class, MyAnnotation.class }; - assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> classes.assertContainsAnnotations(someInfo(), - actual, - expected)) - .withMessage(shouldHaveAnnotations(actual, - Sets.newLinkedHashSet(expected), - Sets.newLinkedHashSet(Override.class, - Deprecated.class)).create()); + actual = AnnotatedClass.class; + // WHEN + AssertionError assertionError = expectAssertionError(() -> classes.assertContainsAnnotations(someInfo(), actual, expected)); + // THEN + then(assertionError).hasMessage(shouldHaveAnnotations(actual, newLinkedHashSet(expected), + newLinkedHashSet(Override.class, Deprecated.class)).create()); } } diff --git a/src/test/java/org/assertj/core/internal/comparables/Comparables_isBetween_Test.java b/src/test/java/org/assertj/core/internal/comparables/Comparables_isBetween_Test.java index 337b66fc170..ca2f683f77f 100644 --- a/src/test/java/org/assertj/core/internal/comparables/Comparables_isBetween_Test.java +++ b/src/test/java/org/assertj/core/internal/comparables/Comparables_isBetween_Test.java @@ -50,13 +50,13 @@ void succeeds_if_actual_is_equal_to_end() { @Test void fails_if_actual_is_less_than_start() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> comparables.assertIsBetween(someInfo(), 6, 8, 10, true, true)) - .withMessage(format("%nExpecting:%n 6%nto be between:%n [8, 10]%n")); + .withMessage(format("%nExpecting actual:%n 6%nto be between:%n [8, 10]%n")); } @Test void fails_if_actual_is_greater_than_end() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> comparables.assertIsBetween(someInfo(), 12, 8, 10, true, true)) - .withMessage(format("%nExpecting:%n 12%nto be between:%n [8, 10]%n")); + .withMessage(format("%nExpecting actual:%n 12%nto be between:%n [8, 10]%n")); } @Test diff --git a/src/test/java/org/assertj/core/internal/comparables/Comparables_isStrictlyBetween_Test.java b/src/test/java/org/assertj/core/internal/comparables/Comparables_isStrictlyBetween_Test.java index 64a841c9cd0..bd11fa5ad24 100644 --- a/src/test/java/org/assertj/core/internal/comparables/Comparables_isStrictlyBetween_Test.java +++ b/src/test/java/org/assertj/core/internal/comparables/Comparables_isStrictlyBetween_Test.java @@ -39,25 +39,25 @@ void succeeds_if_actual_is_between_start_and_end() { @Test void fails_if_actual_is_equal_to_start() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> comparables.assertIsBetween(someInfo(), 8, 8, 10, false, false)) - .withMessage(format("%nExpecting:%n 8%nto be between:%n ]8, 10[%n")); + .withMessage(format("%nExpecting actual:%n 8%nto be between:%n ]8, 10[%n")); } @Test void fails_if_actual_is_equal_to_end() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> comparables.assertIsBetween(someInfo(), 10, 8, 10, false, false)) - .withMessage(format("%nExpecting:%n 10%nto be between:%n ]8, 10[%n")); + .withMessage(format("%nExpecting actual:%n 10%nto be between:%n ]8, 10[%n")); } @Test void fails_if_actual_is_less_than_start() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> comparables.assertIsBetween(someInfo(), 6, 8, 10, false, false)) - .withMessage(format("%nExpecting:%n 6%nto be between:%n ]8, 10[%n")); + .withMessage(format("%nExpecting actual:%n 6%nto be between:%n ]8, 10[%n")); } @Test void fails_if_actual_is_greater_than_end() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> comparables.assertIsBetween(someInfo(), 12, 8, 10, false, false)) - .withMessage(format("%nExpecting:%n 12%nto be between:%n ]8, 10[%n")); + .withMessage(format("%nExpecting actual:%n 12%nto be between:%n ]8, 10[%n")); } @Test diff --git a/src/test/java/org/assertj/core/internal/doubles/Doubles_assertIsInfinite_Test.java b/src/test/java/org/assertj/core/internal/doubles/Doubles_assertIsInfinite_Test.java index 91bbe8a5a75..13e202d5629 100644 --- a/src/test/java/org/assertj/core/internal/doubles/Doubles_assertIsInfinite_Test.java +++ b/src/test/java/org/assertj/core/internal/doubles/Doubles_assertIsInfinite_Test.java @@ -19,10 +19,12 @@ import static org.assertj.core.util.FailureMessages.actualIsNull; import org.assertj.core.internal.DoublesBaseTest; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; +@DisplayName("Doubles assertIsInfinite") class Doubles_assertIsInfinite_Test extends DoublesBaseTest { @ParameterizedTest @@ -30,7 +32,8 @@ class Doubles_assertIsInfinite_Test extends DoublesBaseTest { Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY }) - void should_succeed_when_actual_is_finite(double actual) { + void should_succeed_when_actual_is_infinite(double actual) { + // WHEN/THEN doubles.assertIsInfinite(someInfo(), actual); } @@ -39,11 +42,12 @@ void should_succeed_when_actual_is_finite(double actual) { Double.MAX_VALUE, Double.MIN_NORMAL, Double.MIN_VALUE, + Double.NaN, 0.0, 1.0, -1.0, }) - void should_fail_when_actual_is_not_finite(double actual) { + void should_fail_when_actual_is_not_infinite(double actual) { // WHEN AssertionError assertionError = expectAssertionError(() -> doubles.assertIsInfinite(someInfo(), actual)); // THEN diff --git a/src/test/java/org/assertj/core/internal/doubles/Doubles_assertIsNotFinite_Test.java b/src/test/java/org/assertj/core/internal/doubles/Doubles_assertIsNotFinite_Test.java new file mode 100644 index 00000000000..466ba009bd3 --- /dev/null +++ b/src/test/java/org/assertj/core/internal/doubles/Doubles_assertIsNotFinite_Test.java @@ -0,0 +1,67 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.internal.doubles; + +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.error.ShouldNotBeFinite.shouldNotBeFinite; +import static org.assertj.core.test.TestData.someInfo; +import static org.assertj.core.util.AssertionsUtil.expectAssertionError; +import static org.assertj.core.util.FailureMessages.actualIsNull; + +import org.assertj.core.internal.DoublesBaseTest; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +@DisplayName("Doubles assertIsNotFinite") +class Doubles_assertIsNotFinite_Test extends DoublesBaseTest { + + @ParameterizedTest + @ValueSource(doubles = { + Double.POSITIVE_INFINITY, + Double.NEGATIVE_INFINITY, + Double.NaN + }) + void should_succeed_when_actual_is_not_finite(double actual) { + // WHEN/THEN + doubles.assertIsNotFinite(someInfo(), actual); + } + + @ParameterizedTest + @ValueSource(doubles = { + Double.MAX_VALUE, + Double.MIN_NORMAL, + Double.MIN_VALUE, + 0.0, + 1.0, + -1.0, + }) + void should_fail_when_actual_is_finite(double actual) { + // WHEN + AssertionError assertionError = expectAssertionError(() -> doubles.assertIsNotFinite(someInfo(), actual)); + // THEN + then(assertionError).hasMessage(shouldNotBeFinite(actual).create()); + } + + @Test + void should_fail_if_actual_is_null() { + // GIVEN + Double actual = null; + // WHEN + AssertionError assertionError = expectAssertionError(() -> doubles.assertIsNotFinite(someInfo(), actual)); + // THEN + then(assertionError).hasMessage(actualIsNull()); + } + +} diff --git a/src/test/java/org/assertj/core/internal/doubles/Doubles_assertIsNotInfinite_Test.java b/src/test/java/org/assertj/core/internal/doubles/Doubles_assertIsNotInfinite_Test.java new file mode 100644 index 00000000000..835085d7924 --- /dev/null +++ b/src/test/java/org/assertj/core/internal/doubles/Doubles_assertIsNotInfinite_Test.java @@ -0,0 +1,67 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.internal.doubles; + +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.error.ShouldNotBeInfinite.shouldNotBeInfinite; +import static org.assertj.core.test.TestData.someInfo; +import static org.assertj.core.util.AssertionsUtil.expectAssertionError; +import static org.assertj.core.util.FailureMessages.actualIsNull; + +import org.assertj.core.internal.DoublesBaseTest; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +@DisplayName("Doubles assertIsNotInfinite") +class Doubles_assertIsNotInfinite_Test extends DoublesBaseTest { + + @ParameterizedTest + @ValueSource(doubles = { + Double.MAX_VALUE, + Double.MIN_NORMAL, + Double.MIN_VALUE, + Double.NaN, + 0.0, + 1.0, + -1.0, + }) + void should_succeed_when_actual_is_not_infinite(double actual) { + // WHEN/THEN + doubles.assertIsNotInfinite(someInfo(), actual); + } + + @ParameterizedTest + @ValueSource(doubles = { + Double.POSITIVE_INFINITY, + Double.NEGATIVE_INFINITY + }) + void should_fail_when_actual_is_infinite(double actual) { + // WHEN + AssertionError assertionError = expectAssertionError(() -> doubles.assertIsNotInfinite(someInfo(), actual)); + // THEN + then(assertionError).hasMessage(shouldNotBeInfinite(actual).create()); + } + + @Test + void should_fail_if_actual_is_null() { + // GIVEN + Double actual = null; + // WHEN + AssertionError assertionError = expectAssertionError(() -> doubles.assertIsNotInfinite(someInfo(), actual)); + // THEN + then(assertionError).hasMessage(actualIsNull()); + } + +} diff --git a/src/test/java/org/assertj/core/internal/doubles/Doubles_assertIsNotNaN_Test.java b/src/test/java/org/assertj/core/internal/doubles/Doubles_assertIsNotNaN_Test.java index cc223e13616..ad9c66b67e7 100644 --- a/src/test/java/org/assertj/core/internal/doubles/Doubles_assertIsNotNaN_Test.java +++ b/src/test/java/org/assertj/core/internal/doubles/Doubles_assertIsNotNaN_Test.java @@ -38,7 +38,7 @@ void should_succeed_since_actual_is_not_equal_to_NaN() { @Test void should_fail_since_actual_is_equal_to_NaN() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> doubles.assertIsNotNaN(someInfo(), Double.NaN)) - .withMessage(format("%nExpecting:%n NaN%nnot to be equal to:%n NaN%n")); + .withMessage(format("%nExpecting actual:%n NaN%nnot to be equal to:%n NaN%n")); } @Test @@ -49,6 +49,6 @@ void should_succeed_since_actual_is_not_equal_to_NaN_whatever_custom_comparison_ @Test void should_fail_since_actual_is_equal_to_NaN_whatever_custom_comparison_strategy_is() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> doublesWithAbsValueComparisonStrategy.assertIsNotNaN(someInfo(), Double.NaN)) - .withMessage(format("%nExpecting:%n NaN%nnot to be equal to:%n NaN%n")); + .withMessage(format("%nExpecting actual:%n NaN%nnot to be equal to:%n NaN%n")); } } diff --git a/src/test/java/org/assertj/core/internal/doubles/Doubles_assertIsNotNegative_Test.java b/src/test/java/org/assertj/core/internal/doubles/Doubles_assertIsNotNegative_Test.java index df8e6d77bf6..1045d16cb2c 100644 --- a/src/test/java/org/assertj/core/internal/doubles/Doubles_assertIsNotNegative_Test.java +++ b/src/test/java/org/assertj/core/internal/doubles/Doubles_assertIsNotNegative_Test.java @@ -39,7 +39,7 @@ void should_succeed_since_actual_is_zero() { @Test void should_fail_since_actual_is_negative() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> doubles.assertIsNotNegative(someInfo(), -6d)) - .withMessage(format("%nExpecting:%n -6.0%nto be greater than or equal to:%n 0.0%n")); + .withMessage(format("%nExpecting actual:%n -6.0%nto be greater than or equal to:%n 0.0%n")); } @Test diff --git a/src/test/java/org/assertj/core/internal/doubles/Doubles_assertIsNotZero_Test.java b/src/test/java/org/assertj/core/internal/doubles/Doubles_assertIsNotZero_Test.java index ee232936bf2..d551194a841 100644 --- a/src/test/java/org/assertj/core/internal/doubles/Doubles_assertIsNotZero_Test.java +++ b/src/test/java/org/assertj/core/internal/doubles/Doubles_assertIsNotZero_Test.java @@ -38,7 +38,7 @@ void should_succeed_since_actual_is_not_zero() { @Test void should_fail_since_actual_is_zero() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> doubles.assertIsNotZero(someInfo(), 0.0)) - .withMessage(format("%nExpecting:%n 0.0%nnot to be equal to:%n 0.0%n")); + .withMessage(format("%nExpecting actual:%n 0.0%nnot to be equal to:%n 0.0%n")); } @Test @@ -49,7 +49,7 @@ void should_succeed_since_actual_is_not_zero_whatever_custom_comparison_strategy @Test void should_fail_since_actual_is_zero_whatever_custom_comparison_strategy_is() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> doublesWithAbsValueComparisonStrategy.assertIsNotZero(someInfo(), 0.0d)) - .withMessage(format("%nExpecting:%n 0.0%nnot to be equal to:%n 0.0%n")); + .withMessage(format("%nExpecting actual:%n 0.0%nnot to be equal to:%n 0.0%n")); } } diff --git a/src/test/java/org/assertj/core/internal/doubles/Doubles_assertIsPositive_Test.java b/src/test/java/org/assertj/core/internal/doubles/Doubles_assertIsPositive_Test.java index 1fd3b39a0d8..32ddadc6715 100644 --- a/src/test/java/org/assertj/core/internal/doubles/Doubles_assertIsPositive_Test.java +++ b/src/test/java/org/assertj/core/internal/doubles/Doubles_assertIsPositive_Test.java @@ -37,7 +37,7 @@ void should_succeed_since_actual_is_positive() { @Test void should_fail_since_actual_is_not_positive() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> doubles.assertIsPositive(someInfo(), -6.0d)) - .withMessage(format("%nExpecting:%n -6.0%nto be greater than:%n 0.0%n")); + .withMessage(format("%nExpecting actual:%n -6.0%nto be greater than:%n 0.0%n")); } @Test diff --git a/src/test/java/org/assertj/core/internal/floats/Floats_assertIsFinite_Test.java b/src/test/java/org/assertj/core/internal/floats/Floats_assertIsFinite_Test.java index 1a210754312..7b3463e919a 100644 --- a/src/test/java/org/assertj/core/internal/floats/Floats_assertIsFinite_Test.java +++ b/src/test/java/org/assertj/core/internal/floats/Floats_assertIsFinite_Test.java @@ -19,10 +19,12 @@ import static org.assertj.core.util.FailureMessages.actualIsNull; import org.assertj.core.internal.FloatsBaseTest; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; +@DisplayName("Floats assertIsFinite") class Floats_assertIsFinite_Test extends FloatsBaseTest { @ParameterizedTest @@ -35,6 +37,7 @@ class Floats_assertIsFinite_Test extends FloatsBaseTest { -1.0f, }) void should_succeed_when_actual_is_finite(float actual) { + // WHEN/THEN floats.assertIsFinite(someInfo(), actual); } diff --git a/src/test/java/org/assertj/core/internal/floats/Floats_assertIsInfinite_Test.java b/src/test/java/org/assertj/core/internal/floats/Floats_assertIsInfinite_Test.java index 1e64cd192d1..984eab3b523 100644 --- a/src/test/java/org/assertj/core/internal/floats/Floats_assertIsInfinite_Test.java +++ b/src/test/java/org/assertj/core/internal/floats/Floats_assertIsInfinite_Test.java @@ -30,7 +30,7 @@ class Floats_assertIsInfinite_Test extends FloatsBaseTest { Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY }) - void should_succeed_when_actual_is_finite(float actual) { + void should_succeed_when_actual_is_infinite(float actual) { floats.assertIsInfinite(someInfo(), actual); } @@ -39,11 +39,12 @@ void should_succeed_when_actual_is_finite(float actual) { Float.MAX_VALUE, Float.MIN_NORMAL, Float.MIN_VALUE, + Float.NaN, 0.0f, 1.0f, -1.0f, }) - void should_fail_when_actual_is_not_finite(float actual) { + void should_fail_when_actual_is_not_infinite(float actual) { // WHEN AssertionError assertionError = expectAssertionError(() -> floats.assertIsInfinite(someInfo(), actual)); // THEN diff --git a/src/test/java/org/assertj/core/internal/floats/Floats_assertIsNotFinite_Test.java b/src/test/java/org/assertj/core/internal/floats/Floats_assertIsNotFinite_Test.java new file mode 100644 index 00000000000..cbd3b5fd4d5 --- /dev/null +++ b/src/test/java/org/assertj/core/internal/floats/Floats_assertIsNotFinite_Test.java @@ -0,0 +1,67 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.internal.floats; + +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.error.ShouldNotBeFinite.shouldNotBeFinite; +import static org.assertj.core.test.TestData.someInfo; +import static org.assertj.core.util.AssertionsUtil.expectAssertionError; +import static org.assertj.core.util.FailureMessages.actualIsNull; + +import org.assertj.core.internal.FloatsBaseTest; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +@DisplayName("Floats assertIsNotFinite") +class Floats_assertIsNotFinite_Test extends FloatsBaseTest { + + @ParameterizedTest + @ValueSource(floats = { + Float.POSITIVE_INFINITY, + Float.NEGATIVE_INFINITY, + Float.NaN + }) + void should_succeed_when_actual_is_not_finite(float actual) { + // WHEN/THEN + floats.assertIsNotFinite(someInfo(), actual); + } + + @ParameterizedTest + @ValueSource(floats = { + Float.MAX_VALUE, + Float.MIN_NORMAL, + Float.MIN_VALUE, + 0.0f, + 1.0f, + -1.0f, + }) + void should_fail_when_actual_is_finite(float actual) { + // WHEN + AssertionError assertionError = expectAssertionError(() -> floats.assertIsNotFinite(someInfo(), actual)); + // THEN + then(assertionError).hasMessage(shouldNotBeFinite(actual).create()); + } + + @Test + void should_fail_if_actual_is_null() { + // GIVEN + Float actual = null; + // WHEN + AssertionError assertionError = expectAssertionError(() -> floats.assertIsNotFinite(someInfo(), actual)); + // THEN + then(assertionError).hasMessage(actualIsNull()); + } + +} diff --git a/src/test/java/org/assertj/core/internal/floats/Floats_assertIsNotInfinite_Test.java b/src/test/java/org/assertj/core/internal/floats/Floats_assertIsNotInfinite_Test.java new file mode 100644 index 00000000000..b871e8b9487 --- /dev/null +++ b/src/test/java/org/assertj/core/internal/floats/Floats_assertIsNotInfinite_Test.java @@ -0,0 +1,67 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.internal.floats; + +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.error.ShouldNotBeInfinite.shouldNotBeInfinite; +import static org.assertj.core.test.TestData.someInfo; +import static org.assertj.core.util.AssertionsUtil.expectAssertionError; +import static org.assertj.core.util.FailureMessages.actualIsNull; + +import org.assertj.core.internal.FloatsBaseTest; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +@DisplayName("Floats assertIsNotInfinite") +class Floats_assertIsNotInfinite_Test extends FloatsBaseTest { + + @ParameterizedTest + @ValueSource(floats = { + Float.MAX_VALUE, + Float.MIN_NORMAL, + Float.MIN_VALUE, + Float.NaN, + 0.0f, + 1.0f, + -1.0f, + }) + void should_succeed_when_actual_is_not_infinite(float actual) { + // WHEN/THEN + floats.assertIsNotInfinite(someInfo(), actual); + } + + @ParameterizedTest + @ValueSource(floats = { + Float.POSITIVE_INFINITY, + Float.NEGATIVE_INFINITY + }) + void should_fail_when_actual_is_infinite(float actual) { + // WHEN + AssertionError assertionError = expectAssertionError(() -> floats.assertIsNotInfinite(someInfo(), actual)); + // THEN + then(assertionError).hasMessage(shouldNotBeInfinite(actual).create()); + } + + @Test + void should_fail_if_actual_is_null() { + // GIVEN + Float actual = null; + // WHEN + AssertionError assertionError = expectAssertionError(() -> floats.assertIsNotInfinite(someInfo(), actual)); + // THEN + then(assertionError).hasMessage(actualIsNull()); + } + +} diff --git a/src/test/java/org/assertj/core/internal/floats/Floats_assertIsNotNaN_Test.java b/src/test/java/org/assertj/core/internal/floats/Floats_assertIsNotNaN_Test.java index 6e4d3fab4df..6fe7bef38af 100644 --- a/src/test/java/org/assertj/core/internal/floats/Floats_assertIsNotNaN_Test.java +++ b/src/test/java/org/assertj/core/internal/floats/Floats_assertIsNotNaN_Test.java @@ -38,7 +38,7 @@ void should_succeed_since_actual_is_not_equal_to_NaN() { @Test void should_fail_since_actual_is_equal_to_NaN() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> floats.assertIsNotNaN(someInfo(), Float.NaN)) - .withMessage(format("%nExpecting:%n NaNf%nnot to be equal to:%n NaNf%n")); + .withMessage(format("%nExpecting actual:%n NaNf%nnot to be equal to:%n NaNf%n")); } @Test @@ -49,6 +49,6 @@ void should_succeed_since_actual_is_not_equal_to_NaN_whatever_custom_comparison_ @Test void should_fail_since_actual_is_equal_to_NaN_whatever_custom_comparison_strategy_is() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> floatsWithAbsValueComparisonStrategy.assertIsNotNaN(someInfo(), Float.NaN)) - .withMessage(format("%nExpecting:%n NaNf%nnot to be equal to:%n NaNf%n")); + .withMessage(format("%nExpecting actual:%n NaNf%nnot to be equal to:%n NaNf%n")); } } diff --git a/src/test/java/org/assertj/core/internal/floats/Floats_assertIsNotNegative_Test.java b/src/test/java/org/assertj/core/internal/floats/Floats_assertIsNotNegative_Test.java index b0fdcd8f8f6..1be59803c4b 100644 --- a/src/test/java/org/assertj/core/internal/floats/Floats_assertIsNotNegative_Test.java +++ b/src/test/java/org/assertj/core/internal/floats/Floats_assertIsNotNegative_Test.java @@ -39,7 +39,7 @@ void should_succeed_since_actual_is_zero() { @Test void should_fail_since_actual_is_negative() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> floats.assertIsNotNegative(someInfo(), -6f)) - .withMessage(format("%nExpecting:%n -6.0f%nto be greater than or equal to:%n 0.0f%n")); + .withMessage(format("%nExpecting actual:%n -6.0f%nto be greater than or equal to:%n 0.0f%n")); } @Test diff --git a/src/test/java/org/assertj/core/internal/floats/Floats_assertIsNotZero_Test.java b/src/test/java/org/assertj/core/internal/floats/Floats_assertIsNotZero_Test.java index a60d7edeb53..bdde6601b7d 100644 --- a/src/test/java/org/assertj/core/internal/floats/Floats_assertIsNotZero_Test.java +++ b/src/test/java/org/assertj/core/internal/floats/Floats_assertIsNotZero_Test.java @@ -37,7 +37,7 @@ void should_succeed_since_actual_is_not_zero() { @Test void should_fail_since_actual_is_zero() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> floats.assertIsNotZero(someInfo(), 0.0f)) - .withMessage(format("%nExpecting:%n 0.0f%nnot to be equal to:%n 0.0f%n")); + .withMessage(format("%nExpecting actual:%n 0.0f%nnot to be equal to:%n 0.0f%n")); } @Test @@ -48,7 +48,7 @@ void should_succeed_since_actual_is_not_zero_whatever_custom_comparison_strategy @Test void should_fail_since_actual_is_zero_whatever_custom_comparison_strategy_is() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> floatsWithAbsValueComparisonStrategy.assertIsNotZero(someInfo(), 0.0f)) - .withMessage(format("%nExpecting:%n 0.0f%nnot to be equal to:%n 0.0f%n")); + .withMessage(format("%nExpecting actual:%n 0.0f%nnot to be equal to:%n 0.0f%n")); } } diff --git a/src/test/java/org/assertj/core/internal/floats/Floats_assertIsPositive_Test.java b/src/test/java/org/assertj/core/internal/floats/Floats_assertIsPositive_Test.java index f6c493dc9a7..99e6ac5da00 100644 --- a/src/test/java/org/assertj/core/internal/floats/Floats_assertIsPositive_Test.java +++ b/src/test/java/org/assertj/core/internal/floats/Floats_assertIsPositive_Test.java @@ -37,7 +37,7 @@ void should_succeed_since_actual_is_positive() { @Test void should_fail_since_actual_is_not_positive() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> floats.assertIsPositive(someInfo(), -6.0f)) - .withMessage(format("%nExpecting:%n -6.0f%nto be greater than:%n 0.0f%n")); + .withMessage(format("%nExpecting actual:%n -6.0f%nto be greater than:%n 0.0f%n")); } @Test diff --git a/src/test/java/org/assertj/core/internal/integers/Integers_assertIsNotNegative_Test.java b/src/test/java/org/assertj/core/internal/integers/Integers_assertIsNotNegative_Test.java index cfd92548113..2322b1e5e65 100644 --- a/src/test/java/org/assertj/core/internal/integers/Integers_assertIsNotNegative_Test.java +++ b/src/test/java/org/assertj/core/internal/integers/Integers_assertIsNotNegative_Test.java @@ -39,7 +39,7 @@ void should_succeed_since_actual_is_zero() { @Test void should_fail_since_actual_is_negative() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> integers.assertIsNotNegative(someInfo(), -6)) - .withMessage(format("%nExpecting:%n -6%nto be greater than or equal to:%n 0%n")); + .withMessage(format("%nExpecting actual:%n -6%nto be greater than or equal to:%n 0%n")); } @Test diff --git a/src/test/java/org/assertj/core/internal/integers/Integers_assertIsNotZero_Test.java b/src/test/java/org/assertj/core/internal/integers/Integers_assertIsNotZero_Test.java index ec64010546a..187719bc108 100644 --- a/src/test/java/org/assertj/core/internal/integers/Integers_assertIsNotZero_Test.java +++ b/src/test/java/org/assertj/core/internal/integers/Integers_assertIsNotZero_Test.java @@ -38,7 +38,7 @@ void should_succeed_since_actual_is_not_zero() { @Test void should_fail_since_actual_is_zero() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> integers.assertIsNotZero(someInfo(), 0)) - .withMessage(format("%nExpecting:%n 0%nnot to be equal to:%n 0%n")); + .withMessage(format("%nExpecting actual:%n 0%nnot to be equal to:%n 0%n")); } @Test @@ -49,7 +49,7 @@ void should_succeed_since_actual_is_zero_whatever_custom_comparison_strategy_is( @Test void should_fail_since_actual_is_not_zero_whatever_custom_comparison_strategy_is() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> integersWithAbsValueComparisonStrategy.assertIsNotZero(someInfo(), 0)) - .withMessage(format("%nExpecting:%n 0%nnot to be equal to:%n 0%n")); + .withMessage(format("%nExpecting actual:%n 0%nnot to be equal to:%n 0%n")); } } diff --git a/src/test/java/org/assertj/core/internal/integers/Integers_assertIsPositive_Test.java b/src/test/java/org/assertj/core/internal/integers/Integers_assertIsPositive_Test.java index 243f12adf4f..61b24fb8f0b 100644 --- a/src/test/java/org/assertj/core/internal/integers/Integers_assertIsPositive_Test.java +++ b/src/test/java/org/assertj/core/internal/integers/Integers_assertIsPositive_Test.java @@ -37,7 +37,7 @@ void should_succeed_since_actual_is_positive() { @Test void should_fail_since_actual_is_not_positive() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> integers.assertIsPositive(someInfo(), -6)) - .withMessage(format("%nExpecting:%n -6%nto be greater than:%n 0%n")); + .withMessage(format("%nExpecting actual:%n -6%nto be greater than:%n 0%n")); } @Test @@ -49,7 +49,7 @@ void should_succeed_since_actual_is_positive_according_to_custom_comparison_stra void should_fail_since_actual_is_not_positive_according_to_custom_comparison_strategy() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> integersWithAbsValueComparisonStrategy.assertIsPositive(someInfo(), 0)) - .withMessage(format("%nExpecting:%n 0%nto be greater than:%n 0%nwhen comparing values using AbsValueComparator")); + .withMessage(format("%nExpecting actual:%n 0%nto be greater than:%n 0%nwhen comparing values using AbsValueComparator")); } } diff --git a/src/test/java/org/assertj/core/internal/iterables/Iterables_assertAllSatisfy_Test.java b/src/test/java/org/assertj/core/internal/iterables/Iterables_assertAllSatisfy_Test.java index f2f82b3564c..fd01a5051e6 100644 --- a/src/test/java/org/assertj/core/internal/iterables/Iterables_assertAllSatisfy_Test.java +++ b/src/test/java/org/assertj/core/internal/iterables/Iterables_assertAllSatisfy_Test.java @@ -63,7 +63,7 @@ void should_fail_according_to_requirements() { assertThat(error).isNotNull(); List errors = list(new UnsatisfiedRequirement("Yoda", format("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " \"Yoda\"%n" + "to start with:%n" + " \"L\"%n"))); diff --git a/src/test/java/org/assertj/core/internal/iterables/Iterables_assertAnySatisfy_Test.java b/src/test/java/org/assertj/core/internal/iterables/Iterables_assertAnySatisfy_Test.java index d434d2fd1f3..f8adb31cfc9 100644 --- a/src/test/java/org/assertj/core/internal/iterables/Iterables_assertAnySatisfy_Test.java +++ b/src/test/java/org/assertj/core/internal/iterables/Iterables_assertAnySatisfy_Test.java @@ -85,17 +85,17 @@ void should_fail_if_no_elements_satisfy_the_assertions_requirements() { assertThat(error).isInstanceOf(AssertionError.class); List errors = list(unsatisfiedRequirement("Luke", format("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " \"Luke\"%n" + "to contain:%n" + " \"W\" ")), unsatisfiedRequirement("Leia", format("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " \"Leia\"%n" + "to contain:%n" + " \"W\" ")), unsatisfiedRequirement("Yoda", format("%n" + - "Expecting:%n" + + "Expecting actual:%n" + " \"Yoda\"%n" + "to contain:%n" + " \"W\" ")), diff --git a/src/test/java/org/assertj/core/internal/iterables/Iterables_assertContainsAll_Test.java b/src/test/java/org/assertj/core/internal/iterables/Iterables_assertContainsAll_Test.java index df5b5ba4cad..2233db81e88 100644 --- a/src/test/java/org/assertj/core/internal/iterables/Iterables_assertContainsAll_Test.java +++ b/src/test/java/org/assertj/core/internal/iterables/Iterables_assertContainsAll_Test.java @@ -18,7 +18,9 @@ import static org.assertj.core.api.Assertions.catchThrowable; import static org.assertj.core.error.ShouldContain.shouldContain; import static org.assertj.core.internal.ErrorMessages.iterableToLookForIsNull; +import static org.assertj.core.internal.iterables.SinglyIterableFactory.createSinglyIterable; import static org.assertj.core.test.TestData.someInfo; +import static org.assertj.core.util.Arrays.array; import static org.assertj.core.util.FailureMessages.actualIsNull; import static org.assertj.core.util.Lists.newArrayList; import static org.assertj.core.util.Sets.newLinkedHashSet; @@ -56,6 +58,11 @@ void should_pass_if_actual_contains_all_iterable_values_even_if_duplicated() { iterables.assertContainsAll(someInfo(), actual, newArrayList("Luke", "Luke")); } + @Test + void should_pass_if_nonrestartable_actual_contains_given_values() { + iterables.assertContainsAll(someInfo(), createSinglyIterable(actual), newArrayList("Luke", "Luke")); + } + @Test void should_throw_error_if_array_of_values_to_look_for_is_null() { assertThatNullPointerException().isThrownBy(() -> iterables.assertContainsAll(someInfo(), actual, null)) diff --git a/src/test/java/org/assertj/core/internal/iterables/Iterables_assertContains_Test.java b/src/test/java/org/assertj/core/internal/iterables/Iterables_assertContains_Test.java index 4281c3a8537..831b1f9b99f 100644 --- a/src/test/java/org/assertj/core/internal/iterables/Iterables_assertContains_Test.java +++ b/src/test/java/org/assertj/core/internal/iterables/Iterables_assertContains_Test.java @@ -12,30 +12,32 @@ */ package org.assertj.core.internal.iterables; -import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatNullPointerException; -import static org.assertj.core.api.Assertions.catchThrowable; +import static org.assertj.core.api.BDDAssertions.then; import static org.assertj.core.error.ShouldContain.shouldContain; import static org.assertj.core.internal.ErrorMessages.valuesToLookForIsNull; import static org.assertj.core.internal.iterables.SinglyIterableFactory.createSinglyIterable; import static org.assertj.core.test.ObjectArrays.emptyArray; import static org.assertj.core.test.TestData.someInfo; import static org.assertj.core.util.Arrays.array; +import static org.assertj.core.util.AssertionsUtil.expectAssertionError; import static org.assertj.core.util.FailureMessages.actualIsNull; import static org.assertj.core.util.Lists.newArrayList; import static org.assertj.core.util.Sets.newLinkedHashSet; import static org.mockito.Mockito.verify; -import java.util.Collection; +import java.util.HashSet; +import java.util.Set; import org.assertj.core.api.AssertionInfo; import org.assertj.core.internal.Iterables; import org.assertj.core.internal.IterablesBaseTest; +import org.assertj.core.internal.StandardComparisonStrategy; import org.junit.jupiter.api.Test; /** - * Tests for {@link Iterables#assertContains(AssertionInfo, Collection, Object[])}. + * Tests for {@link Iterables#assertContains(AssertionInfo, Iterable, Object[])}. * * @author Alex Ruiz * @author Joel Costigliola @@ -75,7 +77,7 @@ void should_pass_if_actual_and_given_values_are_empty() { } @Test - void should_pass_if_nonrestartable_actual_contains_given_values() { + void should_pass_if_non_restartable_actual_contains_given_values() { iterables.assertContains(someInfo(), createSinglyIterable(actual), array("Luke", "Yoda", "Leia")); } @@ -98,15 +100,30 @@ void should_fail_if_actual_is_null() { @Test void should_fail_if_actual_does_not_contain_values() { + // GIVEN AssertionInfo info = someInfo(); Object[] expected = { "Han", "Luke" }; - - Throwable error = catchThrowable(() -> iterables.assertContains(info, actual, expected)); - - assertThat(error).isInstanceOf(AssertionError.class); + // WHEN + AssertionError error = expectAssertionError(() -> iterables.assertContains(info, actual, expected)); + // THEN + then(error).hasMessageContaining("Expecting ArrayList:"); verify(failures).failure(info, shouldContain(actual, expected, newLinkedHashSet("Han"))); } + @Test + void should_fail_with_the_right_actual_type() { + // GIVEN + AssertionInfo info = someInfo(); + Object[] expected = { "Han", "Luke" }; + Set actualSet = new HashSet<>(actual); + // WHEN + AssertionError error = expectAssertionError(() -> iterables.assertContains(info, actualSet, expected)); + // THEN + then(error).hasMessageContaining("Expecting HashSet:"); + verify(failures).failure(info, shouldContain(HashSet.class, newArrayList(actualSet), expected, newLinkedHashSet("Han"), + StandardComparisonStrategy.instance())); + } + // ------------------------------------------------------------------------------------------------------------------ // tests using a custom comparison strategy // ------------------------------------------------------------------------------------------------------------------ @@ -139,12 +156,14 @@ void should_pass_if_actual_contains_given_values_even_if_duplicated_according_to @Test void should_fail_if_actual_does_not_contain_values_according_to_custom_comparison_strategy() { + // GIVEN AssertionInfo info = someInfo(); Object[] expected = { "Han", "Luke" }; - - Throwable error = catchThrowable(() -> iterablesWithCaseInsensitiveComparisonStrategy.assertContains(info, actual, expected)); - - assertThat(error).isInstanceOf(AssertionError.class); + // WHEN + AssertionError error = expectAssertionError(() -> iterablesWithCaseInsensitiveComparisonStrategy.assertContains(info, actual, + expected)); + // THEN + then(error).hasMessageContaining("Expecting ArrayList:"); verify(failures).failure(info, shouldContain(actual, expected, newLinkedHashSet("Han"), comparisonStrategy)); } diff --git a/src/test/java/org/assertj/core/internal/iterables/Iterables_assertSatisfiesExactlyInAnyOrder_Test.java b/src/test/java/org/assertj/core/internal/iterables/Iterables_assertSatisfiesExactlyInAnyOrder_Test.java index e265035cd3f..f9bfa91d0f9 100644 --- a/src/test/java/org/assertj/core/internal/iterables/Iterables_assertSatisfiesExactlyInAnyOrder_Test.java +++ b/src/test/java/org/assertj/core/internal/iterables/Iterables_assertSatisfiesExactlyInAnyOrder_Test.java @@ -17,6 +17,7 @@ import static org.assertj.core.api.BDDAssertions.then; import static org.assertj.core.error.ShouldHaveSize.shouldHaveSize; import static org.assertj.core.error.ShouldSatisfy.shouldSatisfyExactlyInAnyOrder; +import static org.assertj.core.util.Arrays.array; import static org.assertj.core.util.AssertionsUtil.expectAssertionError; import static org.assertj.core.util.FailureMessages.actualIsNull; import static org.assertj.core.util.Lists.newArrayList; @@ -51,7 +52,7 @@ void should_pass_if_all_consumers_are_satisfied_by_different_elements_in_order() }; // Matches "Yoda" // WHEN/THEN - iterables.assertSatisfiesExactlyInAnyOrder(info, actual, consumer1, consumer2, consumer3); + iterables.assertSatisfiesExactlyInAnyOrder(info, actual, array(consumer1, consumer2, consumer3)); } @Test @@ -62,12 +63,12 @@ void should_pass_if_all_consumers_are_satisfied_by_different_elements_in_any_ord Consumer consumer3 = s -> assertThat(s).doesNotContain("a"); // Matches "Luke" // WHEN/THEN - iterables.assertSatisfiesExactlyInAnyOrder(info, actual, consumer1, consumer2, consumer3); - iterables.assertSatisfiesExactlyInAnyOrder(info, actual, consumer1, consumer3, consumer2); - iterables.assertSatisfiesExactlyInAnyOrder(info, actual, consumer2, consumer1, consumer3); - iterables.assertSatisfiesExactlyInAnyOrder(info, actual, consumer2, consumer3, consumer1); - iterables.assertSatisfiesExactlyInAnyOrder(info, actual, consumer3, consumer2, consumer1); - iterables.assertSatisfiesExactlyInAnyOrder(info, actual, consumer3, consumer1, consumer2); + iterables.assertSatisfiesExactlyInAnyOrder(info, actual, array(consumer1, consumer2, consumer3)); + iterables.assertSatisfiesExactlyInAnyOrder(info, actual, array(consumer1, consumer3, consumer2)); + iterables.assertSatisfiesExactlyInAnyOrder(info, actual, array(consumer2, consumer1, consumer3)); + iterables.assertSatisfiesExactlyInAnyOrder(info, actual, array(consumer2, consumer3, consumer1)); + iterables.assertSatisfiesExactlyInAnyOrder(info, actual, array(consumer3, consumer2, consumer1)); + iterables.assertSatisfiesExactlyInAnyOrder(info, actual, array(consumer3, consumer1, consumer2)); } @Test @@ -77,8 +78,11 @@ void should_fail_if_one_of_the_consumer_cannot_be_satisfied() { Consumer consumer2 = s -> assertThat(s).hasSize(4); Consumer consumer3 = s -> assertThat(s).hasSize(4); // WHEN - AssertionError assertionError = expectAssertionError(() -> iterables.assertSatisfiesExactlyInAnyOrder(info, actual, consumer1, - consumer2, consumer3)); + AssertionError assertionError = expectAssertionError(() -> iterables.assertSatisfiesExactlyInAnyOrder(info, actual, + array(consumer1, + consumer2, + consumer3))); + // THEN then(assertionError).hasMessage(shouldSatisfyExactlyInAnyOrder(actual).create()); } @@ -90,8 +94,10 @@ void should_fail_if_no_combination_of_consumers_can_be_satisfied() { Consumer consumer2 = s -> assertThat(s).contains("o"); // Matches "Yoda" Consumer consumer3 = s -> assertThat(s).contains("L"); // Matches "Luke" or "Leia" // WHEN - AssertionError assertionError = expectAssertionError(() -> iterables.assertSatisfiesExactlyInAnyOrder(info, actual, consumer1, - consumer2, consumer3)); + AssertionError assertionError = expectAssertionError(() -> iterables.assertSatisfiesExactlyInAnyOrder(info, actual, + array(consumer1, + consumer2, + consumer3))); // THEN then(assertionError).hasMessage(shouldSatisfyExactlyInAnyOrder(actual).create()); } @@ -103,8 +109,10 @@ void should_fail_if_one_of_the_requirements_cannot_be_satisfied() { Consumer consumer2 = s -> assertThat(s).isNotEmpty(); // all elements satisfy this Consumer consumer3 = s -> assertThat(s).isBlank(); // no elements satisfy this // WHEN - AssertionError assertionError = expectAssertionError(() -> iterables.assertSatisfiesExactlyInAnyOrder(info, actual, consumer1, - consumer2, consumer3)); + AssertionError assertionError = expectAssertionError(() -> iterables.assertSatisfiesExactlyInAnyOrder(info, actual, + array(consumer1, + consumer2, + consumer3))); // THEN then(assertionError).hasMessage(shouldSatisfyExactlyInAnyOrder(actual).create()); } @@ -117,19 +125,19 @@ void should_pass_if_iterable_contains_multiple_equal_elements() { Consumer consumer2 = s -> assertThat(s).contains("u"); // WHEN/THEN - iterables.assertSatisfiesExactlyInAnyOrder(info, names, consumer1, consumer2); + iterables.assertSatisfiesExactlyInAnyOrder(info, names, array(consumer1, consumer2)); } @Test void should_pass_if_both_are_empty() { // WHEN/THEN - iterables.assertSatisfiesExactlyInAnyOrder(info, newArrayList()); + iterables.assertSatisfiesExactlyInAnyOrder(info, newArrayList(), array()); } @Test void should_fail_if_there_are_too_few_consumers() { // WHEN - AssertionError assertionError = expectAssertionError(() -> iterables.assertSatisfiesExactlyInAnyOrder(info, actual)); + AssertionError assertionError = expectAssertionError(() -> iterables.assertSatisfiesExactlyInAnyOrder(info, actual, array())); // THEN then(assertionError).hasMessage(shouldHaveSize(actual, 3, 0).create()); } @@ -169,9 +177,11 @@ void should_fail_if_there_are_too_many_consumers() { // GIVEN Consumer consumer = s -> assertThat(s).doesNotContain("z"); // WHEN - AssertionError assertionError = expectAssertionError(() -> iterables.assertSatisfiesExactlyInAnyOrder(info, actual, consumer, - consumer, consumer, - consumer)); + AssertionError assertionError = expectAssertionError(() -> iterables.assertSatisfiesExactlyInAnyOrder(info, actual, + array(consumer, + consumer, + consumer, + consumer))); // THEN then(assertionError).hasMessage(shouldHaveSize(actual, 3, 4).create()); } diff --git a/src/test/java/org/assertj/core/internal/longs/Longs_assertIsNotNegative_Test.java b/src/test/java/org/assertj/core/internal/longs/Longs_assertIsNotNegative_Test.java index 2a28542b1a9..4c566662d1a 100644 --- a/src/test/java/org/assertj/core/internal/longs/Longs_assertIsNotNegative_Test.java +++ b/src/test/java/org/assertj/core/internal/longs/Longs_assertIsNotNegative_Test.java @@ -39,7 +39,7 @@ void should_succeed_since_actual_is_zero() { @Test void should_fail_since_actual_is_negative() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> longs.assertIsNotNegative(someInfo(), -6L)) - .withMessage(format("%nExpecting:%n -6L%nto be greater than or equal to:%n 0L%n")); + .withMessage(format("%nExpecting actual:%n -6L%nto be greater than or equal to:%n 0L%n")); } @Test diff --git a/src/test/java/org/assertj/core/internal/longs/Longs_assertIsNotZero_Test.java b/src/test/java/org/assertj/core/internal/longs/Longs_assertIsNotZero_Test.java index 579eab33993..90a14e991bc 100644 --- a/src/test/java/org/assertj/core/internal/longs/Longs_assertIsNotZero_Test.java +++ b/src/test/java/org/assertj/core/internal/longs/Longs_assertIsNotZero_Test.java @@ -38,7 +38,7 @@ void should_succeed_since_actual_is_not_zero() { @Test void should_fail_since_actual_is_zero() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> longs.assertIsNotZero(someInfo(), 0L)) - .withMessage(format("%nExpecting:%n 0L%nnot to be equal to:%n 0L%n")); + .withMessage(format("%nExpecting actual:%n 0L%nnot to be equal to:%n 0L%n")); } @Test @@ -49,7 +49,7 @@ void should_succeed_since_actual_is_zero_whatever_custom_comparison_strategy_is( @Test void should_fail_since_actual_is_not_zero_whatever_custom_comparison_strategy_is() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> longsWithAbsValueComparisonStrategy.assertIsNotZero(someInfo(), 0L)) - .withMessage(format("%nExpecting:%n 0L%nnot to be equal to:%n 0L%n")); + .withMessage(format("%nExpecting actual:%n 0L%nnot to be equal to:%n 0L%n")); } } diff --git a/src/test/java/org/assertj/core/internal/longs/Longs_assertIsPositive_Test.java b/src/test/java/org/assertj/core/internal/longs/Longs_assertIsPositive_Test.java index 71ea4721590..77436bdd255 100644 --- a/src/test/java/org/assertj/core/internal/longs/Longs_assertIsPositive_Test.java +++ b/src/test/java/org/assertj/core/internal/longs/Longs_assertIsPositive_Test.java @@ -37,7 +37,7 @@ void should_succeed_since_actual_is_positive() { @Test void should_fail_since_actual_is_not_positive() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> longs.assertIsPositive(someInfo(), -6L)) - .withMessage(format("%nExpecting:%n -6L%nto be greater than:%n 0L%n")); + .withMessage(format("%nExpecting actual:%n -6L%nto be greater than:%n 0L%n")); } @Test @@ -49,6 +49,6 @@ void should_succeed_since_actual_is_positive_according_to_custom_comparison_stra void should_fail_since_actual_is_not_positive_according_to_custom_comparison_strategy() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> longsWithAbsValueComparisonStrategy.assertIsPositive(someInfo(), 0L)) - .withMessage(format("%nExpecting:%n 0L%nto be greater than:%n 0L%nwhen comparing values using AbsValueComparator")); + .withMessage(format("%nExpecting actual:%n 0L%nto be greater than:%n 0L%nwhen comparing values using AbsValueComparator")); } } diff --git a/src/test/java/org/assertj/core/internal/maps/Maps_assertAllSatisfyingConsumer_Test.java b/src/test/java/org/assertj/core/internal/maps/Maps_assertAllSatisfyingConsumer_Test.java index 46d1033bd2f..7c1628bf1c0 100644 --- a/src/test/java/org/assertj/core/internal/maps/Maps_assertAllSatisfyingConsumer_Test.java +++ b/src/test/java/org/assertj/core/internal/maps/Maps_assertAllSatisfyingConsumer_Test.java @@ -105,7 +105,7 @@ void should_fail_if_given_requirements_are_null() { private static UnsatisfiedRequirement failOnPpgGreaterThanEqual(String team, Player player, int requiredScore) { SimpleEntry entry = new AbstractMap.SimpleEntry<>(team, player); String message = format("[" + player.getName().getName() + " ppg] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " " + player.getPointsPerGame() + "%n" + "to be greater than or equal to:%n" + " " + requiredScore + "%n"); @@ -115,7 +115,7 @@ private static UnsatisfiedRequirement failOnPpgGreaterThanEqual(String team, Pla private static UnsatisfiedRequirement failOnPpgLessThan(String team, Player player, int requiredScore) { SimpleEntry entry = new AbstractMap.SimpleEntry<>(team, player); String message = format("[" + player.getName().getName() + " ppg] %n" + - "Expecting:%n" + + "Expecting actual:%n" + " " + player.getPointsPerGame() + "%n" + "to be less than:%n" + " " + requiredScore + " "); diff --git a/src/test/java/org/assertj/core/internal/maps/Maps_assertContainsAllEntriesOf_Test.java b/src/test/java/org/assertj/core/internal/maps/Maps_assertContainsAllEntriesOf_Test.java new file mode 100644 index 00000000000..b5be90115e8 --- /dev/null +++ b/src/test/java/org/assertj/core/internal/maps/Maps_assertContainsAllEntriesOf_Test.java @@ -0,0 +1,92 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.internal.maps; + +import static java.util.Collections.emptyMap; +import static org.assertj.core.api.Assertions.catchThrowableOfType; +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.data.MapEntry.entry; +import static org.assertj.core.error.ShouldContain.shouldContain; +import static org.assertj.core.internal.ErrorMessages.mapOfEntriesToLookForIsNull; +import static org.assertj.core.test.Maps.mapOf; +import static org.assertj.core.test.TestData.someInfo; +import static org.assertj.core.util.AssertionsUtil.expectAssertionError; +import static org.assertj.core.util.FailureMessages.actualIsNull; + +import java.util.LinkedHashMap; +import java.util.Map; + +import org.assertj.core.internal.MapsBaseTest; +import org.junit.jupiter.api.Test; + +class Maps_assertContainsAllEntriesOf_Test extends MapsBaseTest { + + @Test + void should_pass_if_actual_contains_given_map_entries() { + maps.assertContainsAllEntriesOf(someInfo(), actual, mapOf(entry("name", "Yoda"))); + } + + @Test + void should_pass_if_actual_contains_given_map_entries_in_different_order() { + maps.assertContainsAllEntriesOf(someInfo(), actual, mapOf(entry("color", "green"), entry("name", "Yoda"))); + } + + @Test + void should_pass_if_actual_contains_all_given_map_entries() { + maps.assertContainsAllEntriesOf(someInfo(), actual, mapOf(entry("name", "Yoda"), entry("color", "green"))); + } + + @Test + void should_pass_if_actual_and_given_map_are_empty() { + actual = emptyMap(); + maps.assertContainsAllEntriesOf(someInfo(), actual, mapOf()); + } + + @Test + void should_pass_if_actual_is_not_empty_and_given_map_is_empty() { + maps.assertContainsAllEntriesOf(someInfo(), actual, emptyMap()); + } + + @Test + void should_throw_error_if_map_of_entries_to_look_for_is_null() { + // GIVEN + Map other = null; + // WHEN + NullPointerException npe = catchThrowableOfType(() -> maps.assertContainsAllEntriesOf(someInfo(), actual, other), + NullPointerException.class); + // THEN + then(npe).isNotNull() + .hasMessage(mapOfEntriesToLookForIsNull()); + } + + @Test + void should_fail_if_actual_is_null() { + // GIVEN + Map actual = null; + // WHEN + AssertionError assertionError = expectAssertionError(() -> maps.assertContainsAllEntriesOf(someInfo(), actual, + mapOf(entry("name", "Yoda")))); + // THEN + then(assertionError).hasMessage(actualIsNull()); + } + + @Test + void should_fail_if_actual_does_not_contain_map_entries() { + // GIVEN + LinkedHashMap other = mapOf(entry("name", "Yoda"), entry("job", "Jedi")); + // WHEN + AssertionError assertionError = expectAssertionError(() -> maps.assertContainsAllEntriesOf(info, actual, other)); + // THEN + then(assertionError).hasMessage(shouldContain(actual, other.entrySet(), mapOf(entry("job", "Jedi")).entrySet()).create()); + } +} diff --git a/src/test/java/org/assertj/core/internal/maps/Maps_assertContainsAnyOf_Test.java b/src/test/java/org/assertj/core/internal/maps/Maps_assertContainsAnyOf_Test.java index ce3fbd878da..29e31651bf1 100644 --- a/src/test/java/org/assertj/core/internal/maps/Maps_assertContainsAnyOf_Test.java +++ b/src/test/java/org/assertj/core/internal/maps/Maps_assertContainsAnyOf_Test.java @@ -12,16 +12,16 @@ */ package org.assertj.core.internal.maps; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatNullPointerException; -import static org.assertj.core.api.Assertions.catchThrowable; +import static org.assertj.core.api.BDDAssertions.then; import static org.assertj.core.data.MapEntry.entry; +import static org.assertj.core.error.ShouldBeEmpty.shouldBeEmpty; import static org.assertj.core.error.ShouldContainAnyOf.shouldContainAnyOf; import static org.assertj.core.internal.ErrorMessages.entriesToLookForIsNull; import static org.assertj.core.internal.ErrorMessages.entryToLookForIsNull; import static org.assertj.core.test.TestData.someInfo; import static org.assertj.core.util.Arrays.array; +import static org.assertj.core.util.AssertionsUtil.expectAssertionError; import static org.assertj.core.util.FailureMessages.actualIsNull; import static org.mockito.Mockito.verify; @@ -56,40 +56,55 @@ void should_pass_if_actual_and_given_entries_are_empty() { maps.assertContainsAnyOf(someInfo(), actual, new MapEntry[0]); } - @SuppressWarnings("unchecked") @Test - void should_throw_error_if_array_of_entries_to_look_for_is_empty_and_the_map_under_test_is_not() { - assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> maps.assertContainsAnyOf(someInfo(), actual, new MapEntry[0])); + void should_fail_if_array_of_entries_to_look_for_is_empty_and_the_map_under_test_is_not() { + // GIVEN + AssertionInfo info = someInfo(); + MapEntry[] expected = emptyEntries(); + // WHEN + expectAssertionError(() -> maps.assertContainsAnyOf(info, actual, expected)); + // THEN + verify(failures).failure(info, shouldBeEmpty(actual)); } @Test void should_throw_error_if_array_of_entries_to_look_for_is_null() { - assertThatNullPointerException().isThrownBy(() -> maps.assertContainsAnyOf(someInfo(), actual, null)) + // GIVEN + MapEntry[] entries = null; + // WHEN/THEN + assertThatNullPointerException().isThrownBy(() -> maps.assertContainsAnyOf(someInfo(), actual, entries)) .withMessage(entriesToLookForIsNull()); } - @SuppressWarnings("unchecked") @Test void should_throw_error_if_entry_is_null() { - MapEntry[] entries = new MapEntry[] { null }; + // GIVEN + MapEntry nullEntry = null; + MapEntry[] entries = array(nullEntry); + // WHEN/THEN assertThatNullPointerException().isThrownBy(() -> maps.assertContainsAnyOf(someInfo(), actual, entries)) .withMessage(entryToLookForIsNull()); } @Test void should_fail_if_actual_is_null() { - assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> maps.assertContainsAnyOf(someInfo(), null, array(entry("name", "Yoda")))) - .withMessage(actualIsNull()); + // GIVEN + actual = null; + MapEntry[] expected = array(entry("name", "Yoda")); + // WHEN + AssertionError assertionError = expectAssertionError(() -> maps.assertContainsAnyOf(someInfo(), actual, expected)); + // THEN + then(assertionError).hasMessage(actualIsNull()); } @Test void should_fail_if_actual_does_not_contain_any_of_the_given_entries() { + // GIVEN AssertionInfo info = someInfo(); MapEntry[] expected = array(entry("name", "Vador"), entry("job", "Jedi")); - - Throwable error = catchThrowable(() -> maps.assertContainsAnyOf(info, actual, expected)); - - assertThat(error).isInstanceOf(AssertionError.class); + // WHEN + expectAssertionError(() -> maps.assertContainsAnyOf(info, actual, expected)); + // THEN verify(failures).failure(info, shouldContainAnyOf(actual, expected)); } } diff --git a/src/test/java/org/assertj/core/internal/maps/Maps_assertContainsExactly_Test.java b/src/test/java/org/assertj/core/internal/maps/Maps_assertContainsExactly_Test.java index 2117caf2fac..0394f43f658 100644 --- a/src/test/java/org/assertj/core/internal/maps/Maps_assertContainsExactly_Test.java +++ b/src/test/java/org/assertj/core/internal/maps/Maps_assertContainsExactly_Test.java @@ -13,14 +13,13 @@ package org.assertj.core.internal.maps; import static java.util.Collections.emptyMap; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatNullPointerException; +import static org.assertj.core.api.BDDAssertions.then; import static org.assertj.core.data.MapEntry.entry; +import static org.assertj.core.error.ShouldBeEmpty.shouldBeEmpty; import static org.assertj.core.error.ShouldContainExactly.elementsDifferAtIndex; import static org.assertj.core.error.ShouldContainExactly.shouldContainExactly; import static org.assertj.core.error.ShouldHaveSameSizeAs.shouldHaveSameSizeAs; -import static org.assertj.core.internal.ErrorMessages.entriesToLookForIsEmpty; import static org.assertj.core.internal.ErrorMessages.entriesToLookForIsNull; import static org.assertj.core.test.TestData.someInfo; import static org.assertj.core.util.Arrays.array; @@ -61,49 +60,54 @@ void initLinkedHashMap() { linkedActual.put("color", "green"); } - @SuppressWarnings("unchecked") @Test void should_fail_if_actual_is_null() { - assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> maps.assertContainsExactly(someInfo(), null, - entry("name", "Yoda"))) - .withMessage(actualIsNull()); + // GIVEN + actual = null; + MapEntry[] expected = array(entry("name", "Yoda")); + // WHEN + AssertionError assertionError = expectAssertionError(() -> maps.assertContainsExactly(someInfo(), actual, expected)); + // THEN + then(assertionError).hasMessage(actualIsNull()); } - @SuppressWarnings("unchecked") @Test void should_fail_if_given_entries_array_is_null() { - assertThatNullPointerException().isThrownBy(() -> maps.assertContainsExactly(someInfo(), linkedActual, - (MapEntry[]) null)) + // GIVEN + MapEntry[] entries = null; + // WHEN/THEN + assertThatNullPointerException().isThrownBy(() -> maps.assertContainsExactly(someInfo(), linkedActual, entries)) .withMessage(entriesToLookForIsNull()); } - @SuppressWarnings("unchecked") @Test void should_fail_if_given_entries_array_is_empty() { - assertThatIllegalArgumentException().isThrownBy(() -> maps.assertContainsExactly(someInfo(), linkedActual, - emptyEntries())) - .withMessage(entriesToLookForIsEmpty()); + // GIVEN + AssertionInfo info = someInfo(); + MapEntry[] expected = emptyEntries(); + // WHEN + expectAssertionError(() -> maps.assertContainsExactly(info, actual, expected)); + // THEN + verify(failures).failure(info, shouldBeEmpty(actual)); } - @SuppressWarnings("unchecked") @Test void should_pass_if_actual_and_entries_are_empty() { - maps.assertContainsExactly(someInfo(), emptyMap(), emptyEntries()); + maps.assertContainsExactly(someInfo(), emptyMap(), array()); } - @SuppressWarnings("unchecked") @Test void should_pass_if_actual_contains_given_entries_in_order() { - maps.assertContainsExactly(someInfo(), linkedActual, entry("name", "Yoda"), entry("color", "green")); + maps.assertContainsExactly(someInfo(), linkedActual, array(entry("name", "Yoda"), entry("color", "green"))); } - @SuppressWarnings("unchecked") @Test void should_fail_if_actual_contains_given_entries_in_disorder() { // GIVEN AssertionInfo info = someInfo(); // WHEN - expectAssertionError(() -> maps.assertContainsExactly(info, linkedActual, entry("color", "green"), entry("name", "Yoda"))); + expectAssertionError(() -> maps.assertContainsExactly(info, linkedActual, + array(entry("color", "green"), entry("name", "Yoda")))); // THEN verify(failures).failure(info, elementsDifferAtIndex(entry("name", "Yoda"), entry("color", "green"), 0)); } diff --git a/src/test/java/org/assertj/core/internal/maps/Maps_assertContainsKey_Test.java b/src/test/java/org/assertj/core/internal/maps/Maps_assertContainsKey_Test.java index 379e1744041..ea6ff6f45db 100644 --- a/src/test/java/org/assertj/core/internal/maps/Maps_assertContainsKey_Test.java +++ b/src/test/java/org/assertj/core/internal/maps/Maps_assertContainsKey_Test.java @@ -32,8 +32,8 @@ import org.junit.jupiter.api.Test; /** - * Tests for {@link Maps#assertContainsKeys(AssertionInfo, Map, Object[])}. - * + * Tests for {@link Maps#assertContainsKey(AssertionInfo, Map, Object)}. + * * @author Nicolas François * @author Joel Costigliola */ @@ -48,18 +48,18 @@ public void setUp() { @Test void should_pass_if_actual_contains_given_key() { - maps.assertContainsKeys(someInfo(), actual, "name"); + maps.assertContainsKey(someInfo(), actual, "name"); } @Test void should_fail_if_actual_is_null() { - assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> maps.assertContainsKeys(someInfo(), null, "name")) + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> maps.assertContainsKey(someInfo(), null, "name")) .withMessage(actualIsNull()); } @Test void should_success_if_key_is_null() { - maps.assertContainsKeys(someInfo(), actual, (String) null); + maps.assertContainsKey(someInfo(), actual, null); } @Test @@ -67,9 +67,10 @@ void should_fail_if_actual_does_not_contain_key() { AssertionInfo info = someInfo(); String key = "power"; - Throwable error = catchThrowable(() -> maps.assertContainsKeys(info, actual, key)); + Throwable error = catchThrowable(() -> maps.assertContainsKey(info, actual, key)); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldContainKeys(actual, newLinkedHashSet(key))); } + } diff --git a/src/test/java/org/assertj/core/internal/maps/Maps_assertContainsKeys_Test.java b/src/test/java/org/assertj/core/internal/maps/Maps_assertContainsKeys_Test.java index db8ef2923bd..3e28868274b 100644 --- a/src/test/java/org/assertj/core/internal/maps/Maps_assertContainsKeys_Test.java +++ b/src/test/java/org/assertj/core/internal/maps/Maps_assertContainsKeys_Test.java @@ -12,13 +12,13 @@ */ package org.assertj.core.internal.maps; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.assertj.core.api.Assertions.catchThrowable; +import static org.assertj.core.api.BDDAssertions.then; import static org.assertj.core.data.MapEntry.entry; import static org.assertj.core.error.ShouldContainKeys.shouldContainKeys; import static org.assertj.core.test.Maps.mapOf; import static org.assertj.core.test.TestData.someInfo; +import static org.assertj.core.util.Arrays.array; +import static org.assertj.core.util.AssertionsUtil.expectAssertionError; import static org.assertj.core.util.FailureMessages.actualIsNull; import static org.assertj.core.util.Sets.newLinkedHashSet; import static org.mockito.Mockito.verify; @@ -32,8 +32,8 @@ import org.junit.jupiter.api.Test; /** - * Tests for {@link Maps#assertContainsKeys(AssertionInfo, Map, Object...)}. - * + * Tests for {@link Maps#assertContainsKeys(AssertionInfo, Map, Object[])}. + * * @author William Delanoue */ class Maps_assertContainsKeys_Test extends MapsBaseTest { @@ -47,40 +47,44 @@ public void setUp() { @Test void should_pass_if_actual_contains_given_key() { - maps.assertContainsKeys(someInfo(), actual, "name"); + maps.assertContainsKeys(someInfo(), actual, array("name")); } @Test void should_fail_if_actual_is_null() { - assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> maps.assertContainsKeys(someInfo(), null, "name")) - .withMessage(actualIsNull()); + // GIVEN + actual = null; + // WHEN + AssertionError assertionError = expectAssertionError(() -> maps.assertContainsKey(someInfo(), null, array("name"))); + // THEN + then(assertionError).hasMessage(actualIsNull()); } @Test void should_success_if_key_is_null() { - maps.assertContainsKeys(someInfo(), actual, (String) null); + maps.assertContainsKeys(someInfo(), actual, new String[] { null }); } @Test void should_fail_if_actual_does_not_contain_key() { + // GIVEN AssertionInfo info = someInfo(); String key = "power"; - - Throwable error = catchThrowable(() -> maps.assertContainsKeys(info, actual, key)); - - assertThat(error).isInstanceOf(AssertionError.class); + // WHEN + expectAssertionError(() -> maps.assertContainsKeys(info, actual, array(key))); + // THEN verify(failures).failure(info, shouldContainKeys(actual, newLinkedHashSet(key))); } @Test void should_fail_if_actual_does_not_contain_keys() { + // GIVEN AssertionInfo info = someInfo(); String key1 = "power"; String key2 = "rangers"; - - Throwable error = catchThrowable(() -> maps.assertContainsKeys(info, actual, key1, key2)); - - assertThat(error).isInstanceOf(AssertionError.class); + // WHEN + expectAssertionError(() -> maps.assertContainsKeys(info, actual, array(key1, key2))); + // THEN verify(failures).failure(info, shouldContainKeys(actual, newLinkedHashSet(key1, key2))); } } diff --git a/src/test/java/org/assertj/core/internal/maps/Maps_assertContainsOnlyKeys_Test.java b/src/test/java/org/assertj/core/internal/maps/Maps_assertContainsOnlyKeys_Test.java index 18292aa286b..c0226dd5a11 100644 --- a/src/test/java/org/assertj/core/internal/maps/Maps_assertContainsOnlyKeys_Test.java +++ b/src/test/java/org/assertj/core/internal/maps/Maps_assertContainsOnlyKeys_Test.java @@ -12,111 +12,223 @@ */ package org.assertj.core.internal.maps; +import static java.lang.String.CASE_INSENSITIVE_ORDER; import static java.util.Collections.emptyMap; import static java.util.Collections.emptySet; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.assertj.core.api.Assertions.assertThatNullPointerException; +import static java.util.Collections.singletonMap; +import static java.util.Collections.unmodifiableMap; +import static org.assertj.core.api.Assertions.assertThatNoException; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.assertj.core.api.BDDAssertions.then; import static org.assertj.core.data.MapEntry.entry; import static org.assertj.core.error.ShouldContainOnlyKeys.shouldContainOnlyKeys; import static org.assertj.core.internal.ErrorMessages.keysToLookForIsEmpty; import static org.assertj.core.internal.ErrorMessages.keysToLookForIsNull; import static org.assertj.core.test.Maps.mapOf; import static org.assertj.core.test.TestData.someInfo; -import static org.assertj.core.util.AssertionsUtil.assertThatAssertionErrorIsThrownBy; +import static org.assertj.core.util.Arrays.array; import static org.assertj.core.util.AssertionsUtil.expectAssertionError; import static org.assertj.core.util.FailureMessages.actualIsNull; -import static org.mockito.Mockito.verify; +import static org.assertj.core.util.Sets.set; +import static org.junit.jupiter.params.provider.Arguments.arguments; -import java.util.HashSet; +import java.util.HashMap; +import java.util.IdentityHashMap; +import java.util.LinkedHashMap; import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.function.Supplier; +import java.util.stream.Stream; +import org.apache.commons.collections4.map.CaseInsensitiveMap; +import org.apache.commons.collections4.map.SingletonMap; +import org.apache.commons.lang3.ArrayUtils; import org.assertj.core.api.AssertionInfo; -import org.assertj.core.api.ThrowableAssert.ThrowingCallable; +import org.assertj.core.internal.Maps; import org.assertj.core.internal.MapsBaseTest; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.springframework.util.LinkedCaseInsensitiveMap; + +import com.google.common.collect.ImmutableMap; /** - * Tests for - * {@link org.assertj.core.internal.Maps#assertContainsOnlyKeys(org.assertj.core.api.AssertionInfo, java.util.Map, java.lang.Object...)} - * . + * Tests for {@link Maps#assertContainsOnlyKeys(AssertionInfo, Map, Object[])}. * * @author Christopher Arnott */ +@DisplayName("Maps assertContainsOnlyKeys(Object[])") class Maps_assertContainsOnlyKeys_Test extends MapsBaseTest { + private static final Supplier> CASE_INSENSITIVE_TREE_MAP = () -> new TreeMap<>(CASE_INSENSITIVE_ORDER); + + @SuppressWarnings("unchecked") + private static final Supplier>[] CASE_INSENSITIVE_MAPS = new Supplier[] { + // org.apache.commons.collections4.map.CaseInsensitiveMap not included due to slightly different behavior + LinkedCaseInsensitiveMap::new, + CASE_INSENSITIVE_TREE_MAP + }; + + @SuppressWarnings("unchecked") + private static final Supplier>[] MODIFIABLE_MAPS = ArrayUtils.addAll(CASE_INSENSITIVE_MAPS, + CaseInsensitiveMap::new, + HashMap::new, + IdentityHashMap::new, + LinkedHashMap::new); + private static final String ARRAY_OF_KEYS = "array of keys"; @Test void should_fail_if_actual_is_null() { // GIVEN - actual = null; + String[] keys = { "name" }; // WHEN - ThrowingCallable code = () -> maps.assertContainsOnlyKeys(someInfo(), null, "name"); + AssertionError error = expectAssertionError(() -> maps.assertContainsOnlyKeys(someInfo(), null, keys)); // THEN - assertThatAssertionErrorIsThrownBy(code).withMessage(actualIsNull()); + then(error).hasMessage(actualIsNull()); } @Test void should_fail_if_given_keys_array_is_null() { - assertThatNullPointerException().isThrownBy(() -> maps.assertContainsOnlyKeys(someInfo(), actual, (String[]) null)) - .withMessage(keysToLookForIsNull(ARRAY_OF_KEYS)); + // GIVEN + String[] keys = null; + // WHEN + Throwable thrown = catchThrowable(() -> maps.assertContainsOnlyKeys(someInfo(), actual, keys)); + // THEN + then(thrown).isInstanceOf(NullPointerException.class).hasMessage(keysToLookForIsNull(ARRAY_OF_KEYS)); } @Test void should_fail_if_given_keys_array_is_empty() { - assertThatIllegalArgumentException().isThrownBy(() -> maps.assertContainsOnlyKeys(someInfo(), actual, emptyKeys())) - .withMessage(keysToLookForIsEmpty(ARRAY_OF_KEYS)); + // GIVEN + String[] keys = emptyKeys(); + // WHEN + Throwable thrown = catchThrowable(() -> maps.assertContainsOnlyKeys(someInfo(), actual, keys)); + // THEN + then(thrown).isInstanceOf(IllegalArgumentException.class).hasMessage(keysToLookForIsEmpty(ARRAY_OF_KEYS)); } - @Test - void should_pass_if_actual_and_given_keys_are_empty() { - maps.assertContainsOnlyKeys(someInfo(), emptyMap(), emptyKeys()); + @ParameterizedTest + @MethodSource({ + "unmodifiableMapsSuccessfulTestCases", + "modifiableMapsSuccessfulTestCases", + "caseInsensitiveMapsSuccessfulTestCases", + }) + void should_pass(Map actual, String[] expected) { + // WHEN/THEN + assertThatNoException().as(actual.getClass().getName()) + .isThrownBy(() -> maps.assertContainsOnlyKeys(info, actual, expected)); } - @Test - void should_pass_if_actual_contains_only_expected_keys() { - maps.assertContainsOnlyKeys(someInfo(), actual, "color", "name"); - maps.assertContainsOnlyKeys(someInfo(), actual, "name", "color"); + private static Stream unmodifiableMapsSuccessfulTestCases() { + return Stream.of(arguments(emptyMap(), emptyKeys()), + arguments(singletonMap("name", "Yoda"), array("name")), + arguments(new SingletonMap<>("name", "Yoda"), array("name")), + arguments(unmodifiableMap(mapOf(entry("name", "Yoda"), entry("job", "Jedi"))), array("name", "job")), + arguments(unmodifiableMap(mapOf(entry("name", "Yoda"), entry("job", "Jedi"))), array("job", "name")), + arguments(ImmutableMap.of("name", "Yoda", "job", "Jedi"), array("name", "job")), + arguments(ImmutableMap.of("name", "Yoda", "job", "Jedi"), array("job", "name"))); } - @Test - void should_fail_if_actual_contains_an_unexpected_key() { - // GIVEN - AssertionInfo info = someInfo(); - String[] expectedKeys = { "name" }; - // WHEN - expectAssertionError(() -> maps.assertContainsOnlyKeys(info, actual, expectedKeys)); - // THEN - verify(failures).failure(info, shouldContainOnlyKeys(actual, expectedKeys, emptySet(), set("color"))); + private static Stream modifiableMapsSuccessfulTestCases() { + return Stream.of(MODIFIABLE_MAPS) + .flatMap(supplier -> Stream.of(arguments(mapOf(supplier, entry("name", "Yoda"), entry("job", "Jedi")), + array("name", "job")), + arguments(mapOf(supplier, entry("name", "Yoda"), entry("job", "Jedi")), + array("job", "name")))); } - @Test - void should_fail_if_actual_does_not_contains_all_expected_keys() { - // GIVEN - AssertionInfo info = someInfo(); - String[] expectedKeys = { "name", "color" }; - Map underTest = mapOf(entry("name", "Yoda")); - // WHEN - expectAssertionError(() -> maps.assertContainsOnlyKeys(info, underTest, expectedKeys)); - // THEN - verify(failures).failure(info, shouldContainOnlyKeys(underTest, expectedKeys, set("color"), emptySet())); + private static Stream caseInsensitiveMapsSuccessfulTestCases() { + return Stream.of(ArrayUtils.add(CASE_INSENSITIVE_MAPS, CaseInsensitiveMap::new)) + .flatMap(supplier -> Stream.of(arguments(mapOf(supplier, entry("NAME", "Yoda"), entry("Job", "Jedi")), + array("name", "job")), + arguments(mapOf(supplier, entry("NAME", "Yoda"), entry("Job", "Jedi")), + array("job", "name")), + arguments(mapOf(supplier, entry("NAME", "Yoda"), entry("Job", "Jedi")), + array("Name", "Job")), + arguments(mapOf(supplier, entry("NAME", "Yoda"), entry("Job", "Jedi")), + array("Job", "Name")))); } - @Test - void should_fail_if_actual_does_not_contains_all_expected_keys_and_contains_unexpected_one() { - // GIVEN - AssertionInfo info = someInfo(); - String[] expectedKeys = { "name", "color" }; - Map underTest = mapOf(entry("name", "Yoda"), entry("job", "Jedi")); + @ParameterizedTest + @MethodSource({ + "unmodifiableMapsFailureTestCases", + "modifiableMapsFailureTestCases", + "caseInsensitiveMapsFailureTestCases", + "commonsCollectionsCaseInsensitiveMapFailureTestCases", + }) + void should_fail(Map actual, String[] expected, Set notFound, Set notExpected) { // WHEN - expectAssertionError(() -> maps.assertContainsOnlyKeys(info, underTest, expectedKeys)); + AssertionError error = expectAssertionError(() -> maps.assertContainsOnlyKeys(info, actual, expected)); // THEN - verify(failures).failure(info, shouldContainOnlyKeys(underTest, expectedKeys, set("color"), set("job"))); + then(error).as(actual.getClass().getName()) + .hasMessage(shouldContainOnlyKeys(actual, expected, notFound, notExpected).create()); } - private static HashSet set(String entry) { - HashSet set = new HashSet<>(); - set.add(entry); - return set; + private static Stream unmodifiableMapsFailureTestCases() { + return Stream.of(arguments(emptyMap(), + array("name"), + set("name"), + emptySet()), + arguments(singletonMap("name", "Yoda"), + array("color"), + set("color"), + set("name")), + arguments(new SingletonMap<>("name", "Yoda"), + array("color"), + set("color"), + set("name")), + arguments(unmodifiableMap(mapOf(entry("name", "Yoda"), entry("job", "Jedi"))), + array("name", "color"), + set("color"), + set("job")), + arguments(ImmutableMap.of("name", "Yoda", "job", "Jedi"), + array("name", "color"), + set("color"), + set("job"))); } + + private static Stream modifiableMapsFailureTestCases() { + return Stream.of(MODIFIABLE_MAPS) + .flatMap(supplier -> Stream.of(arguments(mapOf(supplier, entry("name", "Yoda")), + array("name", "color"), + set("color"), + emptySet()), + arguments(mapOf(supplier, entry("name", "Yoda"), entry("job", "Jedi")), + array("name"), + emptySet(), + set("job")), + arguments(mapOf(supplier, entry("name", "Yoda"), entry("job", "Jedi")), + array("name", "color"), + set("color"), + set("job")))); + } + + private static Stream caseInsensitiveMapsFailureTestCases() { + return Stream.of(CASE_INSENSITIVE_MAPS) + .flatMap(supplier -> Stream.of(arguments(mapOf(supplier, entry("NAME", "Yoda"), entry("Job", "Jedi")), + array("name", "color"), + set("color"), + set("Job")), + arguments(mapOf(supplier, entry("NAME", "Yoda"), entry("Job", "Jedi")), + array("Name", "Color"), + set("Color"), + set("Job")))); + } + + private static Stream commonsCollectionsCaseInsensitiveMapFailureTestCases() { + return Stream.of(arguments(mapOf(CaseInsensitiveMap::new, entry("NAME", "Yoda"), entry("Job", "Jedi")), + array("name", "color"), + set("color"), + set("job")), // internal keys are always lowercase + arguments(mapOf(CaseInsensitiveMap::new, entry("NAME", "Yoda"), entry("Job", "Jedi")), + array("Name", "Color"), + set("Color"), + set("job"))); // internal keys are always lowercase + } + } diff --git a/src/test/java/org/assertj/core/internal/maps/Maps_assertContainsOnly_Test.java b/src/test/java/org/assertj/core/internal/maps/Maps_assertContainsOnly_Test.java index d9ee49a955d..e0a2edc6c09 100644 --- a/src/test/java/org/assertj/core/internal/maps/Maps_assertContainsOnly_Test.java +++ b/src/test/java/org/assertj/core/internal/maps/Maps_assertContainsOnly_Test.java @@ -12,129 +12,235 @@ */ package org.assertj.core.internal.maps; +import static java.lang.String.CASE_INSENSITIVE_ORDER; import static java.util.Collections.emptyMap; import static java.util.Collections.emptySet; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.assertj.core.api.Assertions.assertThatNullPointerException; +import static java.util.Collections.singletonMap; +import static java.util.Collections.unmodifiableMap; +import static org.assertj.core.api.Assertions.assertThatNoException; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.assertj.core.api.BDDAssertions.then; import static org.assertj.core.data.MapEntry.entry; +import static org.assertj.core.error.ShouldBeEmpty.shouldBeEmpty; import static org.assertj.core.error.ShouldContainOnly.shouldContainOnly; -import static org.assertj.core.internal.ErrorMessages.entriesToLookForIsEmpty; import static org.assertj.core.internal.ErrorMessages.entriesToLookForIsNull; +import static org.assertj.core.test.Maps.mapOf; import static org.assertj.core.test.TestData.someInfo; import static org.assertj.core.util.Arrays.array; -import static org.assertj.core.util.AssertionsUtil.assertThatAssertionErrorIsThrownBy; import static org.assertj.core.util.AssertionsUtil.expectAssertionError; import static org.assertj.core.util.FailureMessages.actualIsNull; -import static org.mockito.Mockito.verify; +import static org.assertj.core.util.Sets.set; +import static org.junit.jupiter.params.provider.Arguments.arguments; -import java.util.HashSet; +import java.util.HashMap; +import java.util.IdentityHashMap; +import java.util.LinkedHashMap; import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.TreeMap; +import java.util.function.Supplier; +import java.util.stream.Stream; +import org.apache.commons.collections4.map.CaseInsensitiveMap; +import org.apache.commons.collections4.map.SingletonMap; +import org.apache.commons.lang3.ArrayUtils; import org.assertj.core.api.AssertionInfo; -import org.assertj.core.api.ThrowableAssert.ThrowingCallable; -import org.assertj.core.data.MapEntry; import org.assertj.core.internal.MapsBaseTest; -import org.assertj.core.test.Maps; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.springframework.util.LinkedCaseInsensitiveMap; + +import com.google.common.collect.ImmutableMap; /** - * Tests for - * {@link org.assertj.core.internal.Maps#assertContainsOnly(org.assertj.core.api.AssertionInfo, java.util.Map, org.assertj.core.data.MapEntry...)} - * . + * Tests for {@link org.assertj.core.internal.Maps#assertContainsOnly(AssertionInfo, Map, Entry[])}. * * @author Jean-Christophe Gay */ class Maps_assertContainsOnly_Test extends MapsBaseTest { + private static final Supplier> CASE_INSENSITIVE_TREE_MAP = () -> new TreeMap<>(CASE_INSENSITIVE_ORDER); + @SuppressWarnings("unchecked") + private static final Supplier>[] CASE_INSENSITIVE_MAPS = new Supplier[] { + // org.apache.commons.collections4.map.CaseInsensitiveMap not included due to slightly different behavior + LinkedCaseInsensitiveMap::new, + CASE_INSENSITIVE_TREE_MAP + }; + + @SuppressWarnings("unchecked") + private static final Supplier>[] MODIFIABLE_MAPS = ArrayUtils.addAll(CASE_INSENSITIVE_MAPS, + CaseInsensitiveMap::new, + HashMap::new, + IdentityHashMap::new, + LinkedHashMap::new); + @Test void should_fail_if_actual_is_null() { // GIVEN - actual = null; + Entry[] entries = array(entry("name", "Yoda")); // WHEN - ThrowingCallable code = () -> maps.assertContainsOnly(someInfo(), actual, entry("name", "Yoda")); + AssertionError assertionError = expectAssertionError(() -> maps.assertContainsOnly(someInfo(), null, entries)); // THEN - assertThatAssertionErrorIsThrownBy(code).withMessage(actualIsNull()); + then(assertionError).hasMessage(actualIsNull()); } - @SuppressWarnings("unchecked") @Test void should_fail_if_given_entries_array_is_null() { - assertThatNullPointerException().isThrownBy(() -> maps.assertContainsOnly(someInfo(), actual, (MapEntry[]) null)) - .withMessage(entriesToLookForIsNull()); + // GIVEN + Entry[] entries = null; + // WHEN + Throwable thrown = catchThrowable(() -> maps.assertContainsOnly(someInfo(), actual, entries)); + // THEN + then(thrown).isInstanceOf(NullPointerException.class).hasMessage(entriesToLookForIsNull()); } @SuppressWarnings("unchecked") @Test void should_fail_if_given_entries_array_is_empty() { - assertThatIllegalArgumentException().isThrownBy(() -> maps.assertContainsOnly(someInfo(), actual, emptyEntries())) - .withMessage(entriesToLookForIsEmpty()); + // GIVEN + Entry[] entries = emptyEntries(); + // WHEN + AssertionError error = expectAssertionError(() -> maps.assertContainsOnly(someInfo(), actual, entries)); + // THEN + then(error).hasMessage(shouldBeEmpty(actual).create()); } - @SuppressWarnings("unchecked") - @Test - void should_pass_if_actual_and_entries_are_empty() { - maps.assertContainsOnly(someInfo(), emptyMap(), emptyEntries()); + @ParameterizedTest + @MethodSource({ + "unmodifiableMapsSuccessfulTestCases", + "modifiableMapsSuccessfulTestCases", + "caseInsensitiveMapsSuccessfulTestCases", + }) + void should_pass(Map actual, Entry[] expected) { + // WHEN/THEN + assertThatNoException().as(actual.getClass().getName()) + .isThrownBy(() -> maps.assertContainsOnly(info, actual, expected)); } - @SuppressWarnings("unchecked") - @Test - void should_pass_if_actual_contains_only_expected_entries() { - maps.assertContainsOnly(someInfo(), actual, entry("name", "Yoda"), entry("color", "green")); + private static Stream unmodifiableMapsSuccessfulTestCases() { + return Stream.of(arguments(emptyMap(), emptyEntries()), + arguments(singletonMap("name", "Yoda"), + array(entry("name", "Yoda"))), + arguments(new SingletonMap<>("name", "Yoda"), + array(entry("name", "Yoda"))), + arguments(unmodifiableMap(mapOf(entry("name", "Yoda"), entry("job", "Jedi"))), + array(entry("name", "Yoda"), entry("job", "Jedi"))), + arguments(unmodifiableMap(mapOf(entry("name", "Yoda"), entry("job", "Jedi"))), + array(entry("job", "Jedi"), entry("name", "Yoda"))), + arguments(ImmutableMap.of("name", "Yoda", "job", "Jedi"), + array(entry("name", "Yoda"), entry("job", "Jedi"))), + arguments(ImmutableMap.of("name", "Yoda", "job", "Jedi"), + array(entry("job", "Jedi"), entry("name", "Yoda")))); } - @Test - void should_fail_if_actual_contains_unexpected_entry() { - // GIVEN - AssertionInfo info = someInfo(); - MapEntry[] expected = array(entry("name", "Yoda")); - // WHEN - expectAssertionError(() -> maps.assertContainsOnly(info, actual, expected)); - // THEN - verify(failures).failure(info, shouldContainOnly(actual, expected, emptySet(), set(entry("color", "green")))); + private static Stream modifiableMapsSuccessfulTestCases() { + return Stream.of(MODIFIABLE_MAPS) + .flatMap(supplier -> Stream.of(arguments(mapOf(supplier, entry("name", "Yoda"), entry("job", "Jedi")), + array(entry("name", "Yoda"), entry("job", "Jedi"))), + arguments(mapOf(supplier, entry("name", "Yoda"), entry("job", "Jedi")), + array(entry("job", "Jedi"), entry("name", "Yoda"))))); } - @Test - void should_fail_if_actual_does_not_contains_every_expected_entries() { - // GIVEN - AssertionInfo info = someInfo(); - MapEntry[] expected = array(entry("name", "Yoda"), entry("color", "green")); - Map underTest = Maps.mapOf(entry("name", "Yoda")); - // WHEN - expectAssertionError(() -> maps.assertContainsOnly(info, underTest, expected)); - // THEN - verify(failures).failure(info, shouldContainOnly(underTest, expected, set(entry("color", "green")), emptySet())); + private static Stream caseInsensitiveMapsSuccessfulTestCases() { + return Stream.of(ArrayUtils.add(CASE_INSENSITIVE_MAPS, CaseInsensitiveMap::new)) + .flatMap(supplier -> Stream.of(arguments(mapOf(supplier, entry("NAME", "Yoda"), entry("Job", "Jedi")), + array(entry("name", "Yoda"), entry("job", "Jedi"))), + arguments(mapOf(supplier, entry("NAME", "Yoda"), entry("Job", "Jedi")), + array(entry("job", "Jedi"), entry("name", "Yoda"))), + arguments(mapOf(supplier, entry("NAME", "Yoda"), entry("Job", "Jedi")), + array(entry("Name", "Yoda"), entry("Job", "Jedi"))), + arguments(mapOf(supplier, entry("NAME", "Yoda"), entry("Job", "Jedi")), + array(entry("Job", "Jedi"), entry("Name", "Yoda"))))); } - @Test - void should_fail_if_actual_does_not_contains_every_expected_entries_and_contains_unexpected_one() { - // GIVEN - AssertionInfo info = someInfo(); - MapEntry[] expected = array(entry("name", "Yoda"), entry("color", "green")); - Map underTest = Maps.mapOf(entry("name", "Yoda"), entry("job", "Jedi")); + @ParameterizedTest + @MethodSource({ + "unmodifiableMapsFailureTestCases", + "modifiableMapsFailureTestCases", + "caseInsensitiveMapsFailureTestCases", + "commonsCollectionsCaseInsensitiveMapFailureTestCases", + "orderDependentFailureTestCases", + }) + void should_fail(Map actual, Entry[] expected, + Set> notFound, Set> notExpected) { // WHEN - expectAssertionError(() -> maps.assertContainsOnly(info, underTest, expected)); + AssertionError error = expectAssertionError(() -> maps.assertContainsOnly(info, actual, expected)); // THEN - verify(failures).failure(info, - shouldContainOnly(underTest, expected, set(entry("color", "green")), set(entry("job", "Jedi")))); + then(error).as(actual.getClass().getName()) + .hasMessage(shouldContainOnly(actual, expected, notFound, notExpected).create()); } - @Test - void should_fail_if_actual_contains_entry_key_with_different_value() { - // GIVEN - AssertionInfo info = someInfo(); - MapEntry[] expectedEntries = array(entry("name", "Yoda"), entry("color", "yellow")); - // WHEN - expectAssertionError(() -> maps.assertContainsOnly(info, actual, expectedEntries)); - // THEN - verify(failures).failure(info, shouldContainOnly(actual, expectedEntries, set(entry("color", "yellow")), - set(entry("color", "green")))); + private static Stream unmodifiableMapsFailureTestCases() { + return Stream.of(arguments(emptyMap(), + array(entry("name", "Yoda")), + set(entry("name", "Yoda")), + emptySet()), + arguments(singletonMap("name", "Yoda"), + array(entry("color", "Green")), + set(entry("color", "Green")), + set(entry("name", "Yoda"))), + arguments(new SingletonMap<>("name", "Yoda"), + array(entry("color", "Green")), + set(entry("color", "Green")), + set(entry("name", "Yoda"))), + arguments(unmodifiableMap(mapOf(entry("name", "Yoda"), entry("job", "Jedi"))), + array(entry("name", "Yoda"), entry("color", "Green")), + set(entry("color", "Green")), + set(entry("job", "Jedi"))), + arguments(ImmutableMap.of("name", "Yoda", "job", "Jedi"), + array(entry("name", "Yoda"), entry("color", "Green")), + set(entry("color", "Green")), + set(entry("job", "Jedi")))); + } + + private static Stream modifiableMapsFailureTestCases() { + return Stream.of(MODIFIABLE_MAPS) + .flatMap(supplier -> Stream.of(arguments(mapOf(supplier, entry("name", "Yoda")), + array(entry("name", "Yoda"), entry("color", "Green")), + set(entry("color", "Green")), + emptySet()), + arguments(mapOf(supplier, entry("name", "Yoda"), entry("job", "Jedi")), + array(entry("name", "Yoda")), + emptySet(), + set(entry("job", "Jedi"))), + arguments(mapOf(supplier, entry("name", "Yoda"), entry("job", "Jedi")), + array(entry("name", "Yoda"), entry("color", "Green")), + set(entry("color", "Green")), + set(entry("job", "Jedi"))))); + } + + private static Stream caseInsensitiveMapsFailureTestCases() { + return Stream.of(CASE_INSENSITIVE_MAPS) + .flatMap(supplier -> Stream.of(arguments(mapOf(supplier, entry("NAME", "Yoda"), entry("Job", "Jedi")), + array(entry("name", "Yoda"), entry("color", "Green")), + set(entry("color", "Green")), + set(entry("Job", "Jedi"))), + arguments(mapOf(supplier, entry("NAME", "Yoda"), entry("Job", "Jedi")), + array(entry("Name", "Yoda"), entry("Color", "Green")), + set(entry("Color", "Green")), + set(entry("Job", "Jedi"))))); + } + + private static Stream commonsCollectionsCaseInsensitiveMapFailureTestCases() { + return Stream.of(arguments(mapOf(CaseInsensitiveMap::new, entry("NAME", "Yoda"), entry("Job", "Jedi")), + array(entry("name", "Yoda"), entry("color", "Green")), + set(entry("color", "Green")), + set(entry("job", "Jedi"))), // internal keys are always lowercase + arguments(mapOf(CaseInsensitiveMap::new, entry("NAME", "Yoda"), entry("Job", "Jedi")), + array(entry("Name", "Yoda"), entry("Color", "Green")), + set(entry("Color", "Green")), + set(entry("job", "Jedi")))); // internal keys are always lowercase } - private static HashSet> set(MapEntry entry) { - HashSet> set = new HashSet<>(); - set.add(entry); - return set; + private static Stream orderDependentFailureTestCases() { + return Stream.of(arguments(mapOf(LinkedHashMap::new, entry("name", "Yoda"), entry("job", "Jedi")), + array(entry("name", "Jedi"), entry("job", "Yoda")), + set(entry("name", "Jedi"), entry("job", "Yoda")), + set(entry("name", "Yoda"), entry("job", "Jedi")))); } } diff --git a/src/test/java/org/assertj/core/internal/maps/Maps_assertContainsValues_Test.java b/src/test/java/org/assertj/core/internal/maps/Maps_assertContainsValues_Test.java index f46b19a8242..b5ea3718536 100644 --- a/src/test/java/org/assertj/core/internal/maps/Maps_assertContainsValues_Test.java +++ b/src/test/java/org/assertj/core/internal/maps/Maps_assertContainsValues_Test.java @@ -20,6 +20,7 @@ import static org.assertj.core.error.ShouldContainValues.shouldContainValues; import static org.assertj.core.test.Maps.mapOf; import static org.assertj.core.test.TestData.someInfo; +import static org.assertj.core.util.Arrays.array; import static org.assertj.core.util.FailureMessages.actualIsNull; import static org.assertj.core.util.Sets.newLinkedHashSet; import static org.mockito.Mockito.verify; @@ -32,7 +33,7 @@ import org.junit.jupiter.api.Test; /** - * Tests for {@link org.assertj.core.internal.Maps#assertContainsValue(org.assertj.core.api.AssertionInfo, java.util.Map, Object)}. + * Tests for {@link org.assertj.core.internal.Maps#assertContainsValues(org.assertj.core.api.AssertionInfo, java.util.Map, Object[])}. * * @author Nicolas François * @author Joel Costigliola @@ -49,12 +50,12 @@ public void setUp() { @Test void should_pass_if_actual_contains_given_values() { - maps.assertContainsValues(someInfo(), actual, "Yoda", "Jedi"); + maps.assertContainsValues(someInfo(), actual, new String[] { "Yoda", "Jedi" }); } @Test void should_fail_if_actual_is_null() { - assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> maps.assertContainsValues(someInfo(), null, "Yoda")) + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> maps.assertContainsValues(someInfo(), null, array("Yoda"))) .withMessage(actualIsNull()); } @@ -67,12 +68,12 @@ void should_fail_if_value_is_null() { @Test void should_pass_if_actual_and_given_values_are_empty() { actual = new HashMap<>(); - maps.assertContainsValues(someInfo(), actual); + maps.assertContainsValues(someInfo(), actual, array()); } - + @Test void should_success_if_values_contains_null() { - maps.assertContainsValues(someInfo(), actual, "Yoda", null); + maps.assertContainsValues(someInfo(), actual, array("Yoda", null)); } @Test @@ -81,7 +82,7 @@ void should_fail_if_actual_does_not_contain_value() { String value = "veryOld"; String value2 = "veryOld2"; - Throwable error = catchThrowable(() -> maps.assertContainsValues(info, actual, value, value2)); + Throwable error = catchThrowable(() -> maps.assertContainsValues(info, actual, array(value, value2))); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldContainValues(actual, newLinkedHashSet(value, value2))); diff --git a/src/test/java/org/assertj/core/internal/maps/Maps_assertContains_Test.java b/src/test/java/org/assertj/core/internal/maps/Maps_assertContains_Test.java index a0fa5adad1c..74be1bba4ee 100644 --- a/src/test/java/org/assertj/core/internal/maps/Maps_assertContains_Test.java +++ b/src/test/java/org/assertj/core/internal/maps/Maps_assertContains_Test.java @@ -12,16 +12,16 @@ */ package org.assertj.core.internal.maps; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatNullPointerException; -import static org.assertj.core.api.Assertions.catchThrowable; +import static org.assertj.core.api.BDDAssertions.then; import static org.assertj.core.data.MapEntry.entry; +import static org.assertj.core.error.ShouldBeEmpty.shouldBeEmpty; import static org.assertj.core.error.ShouldContain.shouldContain; import static org.assertj.core.internal.ErrorMessages.entriesToLookForIsNull; import static org.assertj.core.internal.ErrorMessages.entryToLookForIsNull; import static org.assertj.core.test.TestData.someInfo; import static org.assertj.core.util.Arrays.array; +import static org.assertj.core.util.AssertionsUtil.expectAssertionError; import static org.assertj.core.util.FailureMessages.actualIsNull; import static org.assertj.core.util.Sets.newLinkedHashSet; import static org.mockito.Mockito.verify; @@ -29,16 +29,15 @@ import java.util.HashMap; import java.util.Map; -import org.junit.jupiter.api.Test; import org.assertj.core.api.AssertionInfo; import org.assertj.core.data.MapEntry; import org.assertj.core.internal.Maps; import org.assertj.core.internal.MapsBaseTest; - +import org.junit.jupiter.api.Test; /** * Tests for {@link Maps#assertContains(AssertionInfo, Map, Map.Entry[])}. - * + * * @author Alex Ruiz * @author Joel Costigliola */ @@ -63,43 +62,58 @@ void should_pass_if_actual_contains_all_given_entries() { @Test void should_pass_if_actual_and_given_entries_are_empty() { actual = new HashMap<>(); - maps.assertContains(someInfo(), actual, new MapEntry[0]); + maps.assertContains(someInfo(), actual, emptyEntries()); } - @SuppressWarnings("unchecked") @Test - void should_throw_error_if_array_of_entries_to_look_for_is_empty() { - assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> maps.assertContains(someInfo(), actual, new MapEntry[0])); + void should_fail_if_array_of_entries_to_look_for_is_empty_and_the_map_under_test_is_not() { + // GIVEN + AssertionInfo info = someInfo(); + MapEntry[] expected = emptyEntries(); + // WHEN + expectAssertionError(() -> maps.assertContains(info, actual, expected)); + // THEN + verify(failures).failure(info, shouldBeEmpty(actual)); } @Test void should_throw_error_if_array_of_entries_to_look_for_is_null() { - assertThatNullPointerException().isThrownBy(() -> maps.assertContains(someInfo(), actual, null)) + // GIVEN + MapEntry[] entries = null; + // WHEN/THEN + assertThatNullPointerException().isThrownBy(() -> maps.assertContains(someInfo(), actual, entries)) .withMessage(entriesToLookForIsNull()); } - @SuppressWarnings("unchecked") @Test void should_throw_error_if_entry_is_null() { - MapEntry[] entries = new MapEntry[]{null}; + // GIVEN + MapEntry nullEntry = null; + MapEntry[] entries = array(nullEntry); + // WHEN/THEN assertThatNullPointerException().isThrownBy(() -> maps.assertContains(someInfo(), actual, entries)) .withMessage(entryToLookForIsNull()); } @Test void should_fail_if_actual_is_null() { - assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> maps.assertContains(someInfo(), null, array(entry("name", "Yoda")))) - .withMessage(actualIsNull()); + // GIVEN + actual = null; + MapEntry[] expected = array(entry("name", "Yoda")); + // WHEN + AssertionError assertionError = expectAssertionError(() -> maps.assertContains(someInfo(), actual, expected)); + // THEN + then(assertionError).hasMessage(actualIsNull()); } @Test void should_fail_if_actual_does_not_contain_entries() { + // GIVEN AssertionInfo info = someInfo(); MapEntry[] expected = array(entry("name", "Yoda"), entry("job", "Jedi")); - - Throwable error = catchThrowable(() -> maps.assertContains(info, actual, expected)); - - assertThat(error).isInstanceOf(AssertionError.class); + // WHEN + expectAssertionError(() -> maps.assertContains(info, actual, expected)); + // THEN verify(failures).failure(info, shouldContain(actual, expected, newLinkedHashSet(entry("job", "Jedi")))); } } diff --git a/src/test/java/org/assertj/core/internal/maps/Maps_assertDoesNotContainKeys_Test.java b/src/test/java/org/assertj/core/internal/maps/Maps_assertDoesNotContainKeys_Test.java index 21b4614ecdd..78700178705 100644 --- a/src/test/java/org/assertj/core/internal/maps/Maps_assertDoesNotContainKeys_Test.java +++ b/src/test/java/org/assertj/core/internal/maps/Maps_assertDoesNotContainKeys_Test.java @@ -12,70 +12,90 @@ */ package org.assertj.core.internal.maps; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.catchThrowable; +import static org.assertj.core.api.BDDAssertions.then; import static org.assertj.core.error.ShouldNotContainKeys.shouldNotContainKeys; +import static org.assertj.core.internal.ErrorMessages.keysToLookForIsNull; import static org.assertj.core.test.TestData.someInfo; +import static org.assertj.core.util.Arrays.array; +import static org.assertj.core.util.AssertionsUtil.expectAssertionError; import static org.assertj.core.util.FailureMessages.actualIsNull; -import static org.assertj.core.util.Sets.newLinkedHashSet; -import static org.mockito.Mockito.verify; +import static org.assertj.core.util.Sets.set; + +import java.util.Map; import org.assertj.core.api.AssertionInfo; +import org.assertj.core.internal.Maps; import org.assertj.core.internal.MapsBaseTest; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; /** - * Tests for {@link org.assertj.core.internal.Maps#assertDoesNotContainKeys(org.assertj.core.api.AssertionInfo, java.util.Map, Object...)}. + * Tests for {@link Maps#assertDoesNotContainKeys(AssertionInfo, Map, Object[])}. * * @author dorzey */ +@DisplayName("Maps assertDoesNotContainKeys") class Maps_assertDoesNotContainKeys_Test extends MapsBaseTest { + private static final String ARRAY_OF_KEYS = "array of keys"; + @Override @BeforeEach - public void setUp() { + protected void setUp() { super.setUp(); actual.put(null, null); } @Test void should_pass_if_actual_does_not_contain_given_keys() { - maps.assertDoesNotContainKeys(someInfo(), actual, "age"); + maps.assertDoesNotContainKeys(someInfo(), actual, array("age")); } @Test void should_fail_if_actual_is_null() { - assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> maps.assertDoesNotContainKeys(someInfo(), null, "name", "color")) - .withMessage(actualIsNull()); + // GIVEN + String[] keys = { "name" }; + // WHEN + AssertionError error = expectAssertionError(() -> maps.assertDoesNotContainKeys(someInfo(), null, keys)); + // THEN + then(error).hasMessage(actualIsNull()); } @Test - void should_pass_if_key_is_null() { - maps.assertDoesNotContainKeys(someInfo(), actual, (String) null); + void should_fail_if_given_keys_array_is_null() { + // GIVEN + String[] keys = null; + // WHEN + Throwable thrown = catchThrowable(() -> maps.assertDoesNotContainKeys(someInfo(), actual, keys)); + // THEN + then(thrown).isInstanceOf(NullPointerException.class).hasMessage(keysToLookForIsNull(ARRAY_OF_KEYS)); } - @Test - void should_fail_if_actual_contains_key() { - AssertionInfo info = someInfo(); - String key = "name"; - - Throwable error = catchThrowable(() -> maps.assertDoesNotContainKeys(info, actual, key)); - - assertThat(error).isInstanceOf(AssertionError.class); - verify(failures).failure(info, shouldNotContainKeys(actual, newLinkedHashSet(key))); + @ParameterizedTest + @NullSource + @ValueSource(strings = { "name", "color" }) + void should_fail_if_actual_contains_key(String key) { + // GIVEN + String[] keys = { key }; + // WHEN + AssertionError error = expectAssertionError(() -> maps.assertDoesNotContainKeys(someInfo(), actual, keys)); + // THEN + then(error).hasMessage(shouldNotContainKeys(actual, set(key)).create()); } @Test void should_fail_if_actual_contains_keys() { - AssertionInfo info = someInfo(); - String key1 = "name"; - String key2 = "color"; - - Throwable error = catchThrowable(() -> maps.assertDoesNotContainKeys(info, actual, key1, key2)); - - assertThat(error).isInstanceOf(AssertionError.class); - verify(failures).failure(info, shouldNotContainKeys(actual, newLinkedHashSet(key1, key2))); + // GIVEN + String[] keys = { "name", "color" }; + // WHEN + AssertionError error = expectAssertionError(() -> maps.assertDoesNotContainKeys(someInfo(), actual, keys)); + // THEN + then(error).hasMessage(shouldNotContainKeys(actual, set("name", "color")).create()); } + } diff --git a/src/test/java/org/assertj/core/internal/objectarrays/ObjectArrays_assertHasExactlyElementsOfTypes_Test.java b/src/test/java/org/assertj/core/internal/objectarrays/ObjectArrays_assertHasExactlyElementsOfTypes_Test.java new file mode 100644 index 00000000000..8a5340421dc --- /dev/null +++ b/src/test/java/org/assertj/core/internal/objectarrays/ObjectArrays_assertHasExactlyElementsOfTypes_Test.java @@ -0,0 +1,134 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.internal.objectarrays; + +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.error.ShouldHaveExactlyTypes.elementsTypesDifferAtIndex; +import static org.assertj.core.error.ShouldHaveExactlyTypes.shouldHaveTypes; +import static org.assertj.core.test.TestData.someInfo; +import static org.assertj.core.util.AssertionsUtil.expectAssertionError; +import static org.assertj.core.util.FailureMessages.actualIsNull; +import static org.assertj.core.util.Lists.list; + +import java.util.LinkedList; + +import org.assertj.core.api.WritableAssertionInfo; +import org.assertj.core.internal.ObjectArraysBaseTest; +import org.junit.jupiter.api.Test; + +class ObjectArrays_assertHasExactlyElementsOfTypes_Test extends ObjectArraysBaseTest { + + private static final WritableAssertionInfo INFO = someInfo(); + + private static final Object[] ACTUAL = { "a", new LinkedList<>(), 10L }; + + @Test + void should_pass_if_actual_has_exactly_elements_of_the_expected_types_in_order() { + arrays.assertHasExactlyElementsOfTypes(INFO, ACTUAL, String.class, LinkedList.class, Long.class); + } + + @Test + void should_fail_if_actual_is_null() { + // GIVEN + Object[] array = null; + // WHEN + AssertionError error = expectAssertionError(() -> arrays.assertHasExactlyElementsOfTypes(INFO, array, String.class)); + // THEN + then(error).hasMessage(actualIsNull()); + } + + @Test + void should_fail_if_one_element_in_actual_does_not_have_the_expected_type() { + // GIVEN + Class[] expected = { String.class, LinkedList.class, Double.class }; + // WHEN + AssertionError error = expectAssertionError(() -> arrays.assertHasExactlyElementsOfTypes(INFO, ACTUAL, expected)); + // THEN + then(error).hasMessage(shouldHaveTypes(ACTUAL, list(expected), list(Double.class), list(Long.class)).create()); + } + + @Test + void should_fail_if_types_of_elements_are_not_in_the_same_order_as_expected() { + // GIVEN + Class[] expected = { LinkedList.class, String.class, Long.class }; + // WHEN + AssertionError error = expectAssertionError(() -> arrays.assertHasExactlyElementsOfTypes(INFO, ACTUAL, expected)); + // THEN + then(error).hasMessage(elementsTypesDifferAtIndex(ACTUAL[0], LinkedList.class, 0).create()); + } + + @Test + void should_fail_if_actual_has_more_elements_than_expected() { + // GIVEN + Class[] expected = { String.class }; + // WHEN + AssertionError error = expectAssertionError(() -> arrays.assertHasExactlyElementsOfTypes(INFO, ACTUAL, expected)); + // THEN + then(error).hasMessage(shouldHaveTypes(ACTUAL, list(expected), list(), list(LinkedList.class, Long.class)).create()); + } + + @Test + void should_fail_if_actual_elements_types_are_found_but_there_are_not_enough_expected_type_elements() { + // GIVEN + Class[] expected = { String.class, LinkedList.class, Long.class, Long.class }; + // WHEN + AssertionError error = expectAssertionError(() -> arrays.assertHasExactlyElementsOfTypes(INFO, ACTUAL, expected)); + // THEN + then(error).hasMessage(shouldHaveTypes(ACTUAL, list(expected), list(Long.class), list()).create()); + } + + // ------------------------------------------------------------------------------------------------------------------ + // tests using a custom comparison strategy + // ------------------------------------------------------------------------------------------------------------------ + + @Test + void should_pass_if_actual_has_exactly_elements_of_the_expected_types_whatever_the_custom_comparison_strategy_is() { + arraysWithCustomComparisonStrategy.assertHasExactlyElementsOfTypes(INFO, ACTUAL, String.class, LinkedList.class, Long.class); + } + + @Test + void should_fail_if_one_element_in_actual_does_not_have_the_expected_type_whatever_the_custom_comparison_strategy_is() { + // GIVEN + Class[] expected = { String.class, LinkedList.class, Double.class }; + // WHEN + AssertionError error = expectAssertionError(() -> arraysWithCustomComparisonStrategy.assertHasExactlyElementsOfTypes(INFO, + ACTUAL, + expected)); + // THEN + then(error).hasMessage(shouldHaveTypes(ACTUAL, list(expected), list(Double.class), list(Long.class)).create()); + } + + @Test + void should_fail_if_types_of_elements_are_not_in_the_same_order_as_expected_whatever_the_custom_comparison_strategy_is() { + // GIVEN + Class[] expected = { LinkedList.class, String.class, Long.class }; + // WHEN + AssertionError error = expectAssertionError(() -> arraysWithCustomComparisonStrategy.assertHasExactlyElementsOfTypes(INFO, + ACTUAL, + expected)); + // THEN + then(error).hasMessage(elementsTypesDifferAtIndex(ACTUAL[0], LinkedList.class, 0).create()); + } + + @Test + void should_fail_if_actual_elements_types_are_found_but_there_are_not_enough_expected_type_elements_whatever_the_custom_comparison_strategy_is() { + // GIVEN + Class[] expected = { String.class, LinkedList.class, Long.class, Long.class }; + // WHEN + AssertionError error = expectAssertionError(() -> arraysWithCustomComparisonStrategy.assertHasExactlyElementsOfTypes(INFO, + ACTUAL, + expected)); + // THEN + then(error).hasMessage(shouldHaveTypes(ACTUAL, list(expected), list(Long.class), list()).create()); + } +} diff --git a/src/test/java/org/assertj/core/internal/objects/Objects_assertEqual_Test.java b/src/test/java/org/assertj/core/internal/objects/Objects_assertEqual_Test.java index a6355b10be7..fa4f6089b86 100644 --- a/src/test/java/org/assertj/core/internal/objects/Objects_assertEqual_Test.java +++ b/src/test/java/org/assertj/core/internal/objects/Objects_assertEqual_Test.java @@ -83,7 +83,7 @@ void should_fail_if_objects_are_not_equal_according_to_custom_comparison_strateg void should_fail_if_compared_with_null() { Throwable error = catchThrowable(() -> objects.assertEqual(someInfo(), new MyObject(), null)); - assertThat(error).isInstanceOf(AssertionError.class); + assertThat(error).isInstanceOf(MyObject.NullEqualsException.class); } @Test @@ -94,6 +94,7 @@ void should_fail_with_my_exception_if_compared_with_other_object() { } private static class MyObject { + private final int anInt = 0; @Override @@ -105,12 +106,14 @@ public boolean equals(Object o) { return anInt == myObject.anInt; } - private class NullEqualsException extends RuntimeException { + private static class NullEqualsException extends RuntimeException { private static final long serialVersionUID = 6906581676690444515L; } - private class DifferentClassesException extends RuntimeException { + private static class DifferentClassesException extends RuntimeException { private static final long serialVersionUID = -7330747471795712311L; } + } + } diff --git a/src/test/java/org/assertj/core/internal/objects/Objects_assertHasOnlyFields_Test.java b/src/test/java/org/assertj/core/internal/objects/Objects_assertHasOnlyFields_Test.java index c002022aa96..d0a4664306d 100644 --- a/src/test/java/org/assertj/core/internal/objects/Objects_assertHasOnlyFields_Test.java +++ b/src/test/java/org/assertj/core/internal/objects/Objects_assertHasOnlyFields_Test.java @@ -33,11 +33,11 @@ class Objects_assertHasOnlyFields_Test extends ObjectsBaseTest { "fields"); @Test - void should_pass_if_actual_has_all_given_fields_and_nothing_else() { + void should_pass_if_actual_has_all_given_instance_level_fields_and_nothing_else() { // GIVEN Object actual = new Data(); // WHEN/THEN - objects.assertHasOnlyFields(INFO, actual, "field1", "field2"); + objects.assertHasOnlyFields(INFO, actual, "field1", "field2"); // static fields ignored } @Test @@ -97,6 +97,8 @@ void should_fail_if_given_field_names_are_null() { @SuppressWarnings("unused") private static class Data { + public static Object publicStaticField; + private static Object privateStaticField; private Object field1; private Object field2; diff --git a/src/test/java/org/assertj/core/internal/paths/MockPathsBaseTest.java b/src/test/java/org/assertj/core/internal/paths/MockPathsBaseTest.java index ece6f9d2901..11d4b5e59da 100644 --- a/src/test/java/org/assertj/core/internal/paths/MockPathsBaseTest.java +++ b/src/test/java/org/assertj/core/internal/paths/MockPathsBaseTest.java @@ -21,9 +21,6 @@ import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willAnswer; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.mockingDetails; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; import java.io.ByteArrayInputStream; import java.io.File; diff --git a/src/test/java/org/assertj/core/internal/shorts/Shorts_assertIsNotNegative_Test.java b/src/test/java/org/assertj/core/internal/shorts/Shorts_assertIsNotNegative_Test.java index 9448edccc8e..1c2a3426bb2 100644 --- a/src/test/java/org/assertj/core/internal/shorts/Shorts_assertIsNotNegative_Test.java +++ b/src/test/java/org/assertj/core/internal/shorts/Shorts_assertIsNotNegative_Test.java @@ -41,7 +41,7 @@ void should_succeed_since_actual_is_zero() { @Test void should_fail_since_actual_is_negative() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> shorts.assertIsNotNegative(someInfo(), (short) -6)) - .withMessage(format("%nExpecting:%n -6%nto be greater than or equal to:%n 0%n")); + .withMessage(format("%nExpecting actual:%n -6%nto be greater than or equal to:%n 0%n")); } @Test diff --git a/src/test/java/org/assertj/core/internal/shorts/Shorts_assertIsNotZero_Test.java b/src/test/java/org/assertj/core/internal/shorts/Shorts_assertIsNotZero_Test.java index 88c2c9d13fe..0b3f1fd9fb1 100644 --- a/src/test/java/org/assertj/core/internal/shorts/Shorts_assertIsNotZero_Test.java +++ b/src/test/java/org/assertj/core/internal/shorts/Shorts_assertIsNotZero_Test.java @@ -38,7 +38,7 @@ void should_succeed_since_actual_is_not_zero() { @Test void should_fail_since_actual_is_zero() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> shorts.assertIsNotZero(someInfo(), (short) 0)) - .withMessage(format("%nExpecting:%n 0%nnot to be equal to:%n 0%n")); + .withMessage(format("%nExpecting actual:%n 0%nnot to be equal to:%n 0%n")); } @Test @@ -49,7 +49,7 @@ void should_succeed_since_actual_is_zero_whatever_custom_comparison_strategy_is( @Test void should_fail_since_actual_is_not_zero_whatever_custom_comparison_strategy_is() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> shortsWithAbsValueComparisonStrategy.assertIsNotZero(someInfo(), (short) 0)) - .withMessage(format("%nExpecting:%n 0%nnot to be equal to:%n 0%n")); + .withMessage(format("%nExpecting actual:%n 0%nnot to be equal to:%n 0%n")); } } diff --git a/src/test/java/org/assertj/core/internal/shorts/Shorts_assertIsPositive_Test.java b/src/test/java/org/assertj/core/internal/shorts/Shorts_assertIsPositive_Test.java index 3702f8cea3e..ecd37ee864e 100644 --- a/src/test/java/org/assertj/core/internal/shorts/Shorts_assertIsPositive_Test.java +++ b/src/test/java/org/assertj/core/internal/shorts/Shorts_assertIsPositive_Test.java @@ -37,7 +37,7 @@ void should_succeed_since_actual_is_positive() { @Test void should_fail_since_actual_is_not_positive() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> shorts.assertIsPositive(someInfo(), (short) -6)) - .withMessage(format("%nExpecting:%n -6%nto be greater than:%n 0%n")); + .withMessage(format("%nExpecting actual:%n -6%nto be greater than:%n 0%n")); } @Test @@ -49,6 +49,6 @@ void should_succeed_since_actual_is_positive_according_to_custom_comparison_stra void should_fail_since_actual_is_not_positive_according_to_custom_comparison_strategy() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> shortsWithAbsValueComparisonStrategy.assertIsPositive(someInfo(), (short) 0)) - .withMessage(format("%nExpecting:%n 0%nto be greater than:%n 0%nwhen comparing values using AbsValueComparator")); + .withMessage(format("%nExpecting actual:%n 0%nto be greater than:%n 0%nwhen comparing values using AbsValueComparator")); } } diff --git a/src/test/java/org/assertj/core/internal/strings/Strings_assertContainsIgnoringWhitespaces_Test.java b/src/test/java/org/assertj/core/internal/strings/Strings_assertContainsIgnoringWhitespaces_Test.java new file mode 100644 index 00000000000..39998615801 --- /dev/null +++ b/src/test/java/org/assertj/core/internal/strings/Strings_assertContainsIgnoringWhitespaces_Test.java @@ -0,0 +1,172 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.internal.strings; + +import static org.assertj.core.api.Assertions.assertThatNullPointerException; +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.error.ShouldContainCharSequence.shouldContainIgnoringWhitespaces; +import static org.assertj.core.internal.ErrorMessages.charSequenceToLookForIsNull; +import static org.assertj.core.test.TestData.someInfo; +import static org.assertj.core.util.Arrays.array; +import static org.assertj.core.util.AssertionsUtil.expectAssertionError; +import static org.assertj.core.util.FailureMessages.actualIsNull; +import static org.assertj.core.util.Sets.newLinkedHashSet; + +import org.assertj.core.api.AssertionInfo; +import org.assertj.core.api.WritableAssertionInfo; +import org.assertj.core.internal.StandardComparisonStrategy; +import org.assertj.core.internal.Strings; +import org.assertj.core.internal.StringsBaseTest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +/** + * Tests for {@link Strings#assertContainsIgnoringWhitespaces(AssertionInfo, CharSequence, CharSequence...)} . + * + * @author Johannes Becker + */ +public class Strings_assertContainsIgnoringWhitespaces_Test extends StringsBaseTest { + + private static final WritableAssertionInfo INFO = someInfo(); + + @ParameterizedTest + @ValueSource(strings = { "Yo", "a n dLuke", "YodaandLuke", "Yoda\tand\nLuke" }) + void should_pass_if_actual_contains_value_when_whitespaces_are_ignored(String value) { + // GIVEN + String actual = "Yoda and Luke"; + // WHEN / THEN + strings.assertContainsIgnoringWhitespaces(INFO, actual, value); + } + + @Test + void should_pass_if_actual_contains_all_given_strings() { + // GIVEN + String actual = "Yoda and Luke"; + String[] values = array("Yo", "da", "a n d", "L u k e"); + // WHEN / THEN + strings.assertContainsIgnoringWhitespaces(INFO, actual, values); + } + + @Test + void should_fail_if_actual_does_not_contain_value() { + // GIVEN + String actual = "Yoda"; + String value = "Luke"; + // WHEN + AssertionError assertionError = expectAssertionError(() -> strings.assertContainsIgnoringWhitespaces(INFO, actual, value)); + // THEN + then(assertionError).hasMessage(shouldContainIgnoringWhitespaces("Yoda", "Luke", StandardComparisonStrategy.instance()).create()); + } + + @Test + void should_fail_if_actual_contains_value_but_in_different_case() { + // GIVEN + String actual = "Yoda"; + String value = "yo"; + // WHEN + AssertionError assertionError = expectAssertionError(() -> strings.assertContainsIgnoringWhitespaces(INFO, actual, value)); + // THEN + then(assertionError).hasMessage(shouldContainIgnoringWhitespaces("Yoda", "yo", StandardComparisonStrategy.instance()).create()); + } + + @Test + void should_fail_if_actual_contains_value_with_whitespaces_but_in_different_case() { + // GIVEN + String actual = "Yoda and Luke"; + String value = "a n dluke"; + // WHEN + AssertionError assertionError = expectAssertionError(() -> strings.assertContainsIgnoringWhitespaces(INFO, actual, value)); + // THEN + then(assertionError).hasMessage(shouldContainIgnoringWhitespaces("Yoda and Luke", "a n dluke", StandardComparisonStrategy.instance()).create()); + } + + @Test + void should_throw_error_if_value_is_null() { + // GIVEN + String actual = "Yoda"; + String value = null; + // WHEN / THEN + assertThatNullPointerException().isThrownBy(() -> strings.assertContainsIgnoringWhitespaces(INFO, actual, value)) + .withMessage(charSequenceToLookForIsNull()); + } + + @Test + void should_fail_if_actual_is_null() { + // GIVEN + String actual = null; + String value = "Yoda"; + // WHEN + AssertionError assertionError = expectAssertionError(() -> strings.assertContainsIgnoringWhitespaces(INFO, actual, value)); + // THEN + then(assertionError).hasMessage(actualIsNull()); + } + + @Test + void should_fail_if_actual_does_not_contain_all_given_strings() { + // GIVEN + String actual = "Yoda"; + String[] values = array("Yo", "da", "Han"); + // WHEN + AssertionError assertionError = expectAssertionError(() -> strings.assertContainsIgnoringWhitespaces(INFO, actual, values)); + // THEN + then(assertionError).hasMessage(shouldContainIgnoringWhitespaces(actual, values, newLinkedHashSet("Han"), + StandardComparisonStrategy.instance()).create()); + } + + @ParameterizedTest + @ValueSource(strings = { "Yo", "yo", "YO", "a n dluke", "A N Dluke", "and L u k" }) + void should_pass_if_actual_contains_value_according_to_custom_comparison_strategy(String value) { + // GIVEN + String actual = "Yoda and Luke"; + // WHEN / THEN + stringsWithCaseInsensitiveComparisonStrategy.assertContainsIgnoringWhitespaces(INFO, actual, value); + } + + @Test + void should_pass_if_actual_contains_all_given_strings_according_to_custom_comparison_strategy() { + // GIVEN + String actual = "Yoda and Luke"; + String[] values = array("YO", "dA", "Aa", " n d l"); + // WHEN / THEN + stringsWithCaseInsensitiveComparisonStrategy.assertContainsIgnoringWhitespaces(INFO, actual, values); + } + + @Test + void should_fail_if_actual_does_not_contain_value_according_to_custom_comparison_strategy() { + // GIVEN + String actual = "Yoda"; + String value = "Luke"; + // WHEN + AssertionError assertionError = expectAssertionError(() -> stringsWithCaseInsensitiveComparisonStrategy.assertContainsIgnoringWhitespaces(INFO, + actual, + value)); + // THEN + then(assertionError).hasMessage(shouldContainIgnoringWhitespaces("Yoda", "Luke", comparisonStrategy).create()); + } + + @Test + void should_fail_if_actual_does_not_contain_all_given_strings_according_to_custom_comparison_strategy() { + // GIVEN + String actual = "Yoda"; + String[] values = array("Yo", "da", "Han"); + + // WHEN + AssertionError assertionError = expectAssertionError(() -> stringsWithCaseInsensitiveComparisonStrategy.assertContainsIgnoringWhitespaces(INFO, + actual, + values)); + // THEN + then(assertionError).hasMessage(shouldContainIgnoringWhitespaces(actual, values, newLinkedHashSet("Han"), + comparisonStrategy).create()); + } +} diff --git a/src/test/java/org/assertj/core/internal/strings/Strings_assertContainsSubsequence_Test.java b/src/test/java/org/assertj/core/internal/strings/Strings_assertContainsSubsequence_Test.java index 03694e50344..e1ccf106e93 100644 --- a/src/test/java/org/assertj/core/internal/strings/Strings_assertContainsSubsequence_Test.java +++ b/src/test/java/org/assertj/core/internal/strings/Strings_assertContainsSubsequence_Test.java @@ -12,109 +12,140 @@ */ package org.assertj.core.internal.strings; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatNullPointerException; +import static org.assertj.core.api.BDDAssertions.then; import static org.assertj.core.error.ShouldContainCharSequence.shouldContain; import static org.assertj.core.error.ShouldContainSubsequenceOfCharSequence.shouldContainSubsequence; import static org.assertj.core.internal.ErrorMessages.arrayOfValuesToLookForIsEmpty; import static org.assertj.core.internal.ErrorMessages.arrayOfValuesToLookForIsNull; import static org.assertj.core.test.TestData.someInfo; import static org.assertj.core.util.Arrays.array; +import static org.assertj.core.util.AssertionsUtil.expectAssertionError; import static org.assertj.core.util.FailureMessages.actualIsNull; import static org.assertj.core.util.Sets.newLinkedHashSet; +import static org.mockito.Mockito.verify; +import org.assertj.core.api.WritableAssertionInfo; import org.assertj.core.internal.StringsBaseTest; import org.junit.jupiter.api.Test; class Strings_assertContainsSubsequence_Test extends StringsBaseTest { + private static final WritableAssertionInfo INFO = someInfo(); + @Test void should_pass_if_actual_contains_subsequence() { - strings.assertContainsSubsequence(someInfo(), "Yoda", array("Yo", "da")); + strings.assertContainsSubsequence(INFO, "Yoda", array("Yo", "da")); } @Test void should_pass_if_actual_contains_subsequence_with_values_between() { String actual = "{ 'title':'A Game of Thrones', 'author':'George Martin'}"; - String[] sequenceValues = { "{", "title", "A Game of Thrones", "}" }; - strings.assertContainsSubsequence(someInfo(), actual, sequenceValues); + String[] subsequence = { "{", "title", "A Game of Thrones", "}" }; + strings.assertContainsSubsequence(INFO, actual, subsequence); } @Test void should_fail_if_actual_does_not_contain_all_given_strings() { - assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> strings.assertContainsSubsequence(someInfo(), "Yoda", array("Yo", "da", "Han"))) - .withMessage(shouldContain("Yoda", array("Yo", "da", "Han"), newLinkedHashSet("Han")).create()); + // GIVEN + String actual = "Yoda"; + String[] subsequence = { "Yo", "da", "Han" }; + // WHEN + expectAssertionError(() -> strings.assertContainsSubsequence(INFO, actual, subsequence)); + // THEN + verify(failures).failure(INFO, shouldContain(actual, subsequence, newLinkedHashSet("Han"))); } @Test void should_fail_if_actual_contains_values_but_not_in_given_order() { + // GIVEN String actual = "{ 'title':'A Game of Thrones', 'author':'George Martin'}"; - String[] sequenceValues = { "{", "author", "A Game of Thrones", "}" }; - assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> strings.assertContainsSubsequence(someInfo(), actual, sequenceValues)) - .withMessage(shouldContainSubsequence(actual, sequenceValues, 1).create()); + String[] subsequence = { "{", "author", "A Game of Thrones", "}" }; + // WHEN + expectAssertionError(() -> strings.assertContainsSubsequence(INFO, actual, subsequence)); + // THEN + verify(failures).failure(INFO, shouldContainSubsequence(actual, subsequence, 1)); } @Test void should_throw_error_if_subsequence_is_null() { - assertThatNullPointerException().isThrownBy(() -> strings.assertContainsSubsequence(someInfo(), "Yoda", null)) + assertThatNullPointerException().isThrownBy(() -> strings.assertContainsSubsequence(INFO, "Yoda", null)) .withMessage(arrayOfValuesToLookForIsNull()); } @Test void should_throw_error_if_any_value_of_subsequence_is_null() { - String[] sequenceValues = { "author", null }; - assertThatNullPointerException().isThrownBy(() -> strings.assertContainsSubsequence(someInfo(), - "'author':'George Martin'", - sequenceValues)) + // GIVEN + String actual = "'author':'George Martin'"; + String[] subsequence = { "author", null }; + // WHEN/THEN + assertThatNullPointerException().isThrownBy(() -> strings.assertContainsSubsequence(INFO, actual, subsequence)) .withMessage("Expecting CharSequence elements not to be null but found one at index 1"); } @Test void should_throw_error_if_subsequence_values_is_empty() { - assertThatIllegalArgumentException().isThrownBy(() -> strings.assertContainsSubsequence(someInfo(), "Yoda", - new String[0])) + // GIVEN + String actual = "Yoda"; + String[] emptySubsequence = {}; + // WHEN/THEN + assertThatIllegalArgumentException().isThrownBy(() -> strings.assertContainsSubsequence(INFO, actual, emptySubsequence)) .withMessage(arrayOfValuesToLookForIsEmpty()); } @Test void should_fail_if_actual_is_null() { - assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> strings.assertContainsSubsequence(someInfo(), null, array("Yo", "da"))) - .withMessage(actualIsNull()); + // GIVEN + String actual = null; + // WHEN + AssertionError assertionError = expectAssertionError(() -> strings.assertContainsSubsequence(INFO, actual, array("a", "b"))); + // THEN + then(assertionError).hasMessage(actualIsNull()); } @Test void should_pass_if_actual_contains_subsequence_that_specifies_multiple_times_the_same_value_bug_544() { - strings.assertContainsSubsequence(someInfo(), "a-b-c-", array("a", "-", "b", "-", "c")); - strings.assertContainsSubsequence(someInfo(), "{ 'title':'A Game of Thrones', 'author':'George Martin'}", + strings.assertContainsSubsequence(INFO, "a-b-c-", array("a", "-", "b", "-", "c")); + strings.assertContainsSubsequence(INFO, "{ 'title':'A Game of Thrones', 'author':'George Martin'}", array("George", " ", "Martin")); } @Test void should_pass_if_actual_contains_subsequence_according_to_custom_comparison_strategy() { - stringsWithCaseInsensitiveComparisonStrategy.assertContainsSubsequence(someInfo(), "Yoda", array("Yo", "da")); - stringsWithCaseInsensitiveComparisonStrategy.assertContainsSubsequence(someInfo(), "Yoda", array("Yo", "DA")); - stringsWithCaseInsensitiveComparisonStrategy.assertContainsSubsequence(someInfo(), "Yoda", array("YO", "dA")); + stringsWithCaseInsensitiveComparisonStrategy.assertContainsSubsequence(INFO, "Yoda", array("Yo", "da")); + stringsWithCaseInsensitiveComparisonStrategy.assertContainsSubsequence(INFO, "Yoda", array("Yo", "DA")); + stringsWithCaseInsensitiveComparisonStrategy.assertContainsSubsequence(INFO, "Yoda", array("YO", "dA")); } @Test void should_fail_if_actual_does_not_contain_subsequence_according_to_custom_comparison_strategy() { - assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> stringsWithCaseInsensitiveComparisonStrategy.assertContainsSubsequence(someInfo(), - "Yoda", - array("Yo", - "da", - "Han"))) - .withMessage(shouldContain("Yoda", array("Yo", "da", "Han"), - newLinkedHashSet("Han"), - comparisonStrategy).create()); + // GIVEN + String actual = "Yoda"; + String[] subsequence = { "Yo", "da", "Han" }; + // WHEN + expectAssertionError(() -> stringsWithCaseInsensitiveComparisonStrategy.assertContainsSubsequence(INFO, actual, subsequence)); + // THEN + verify(failures).failure(INFO, shouldContain(actual, subsequence, newLinkedHashSet("Han"), comparisonStrategy)); } @Test void should_fail_if_actual_contains_values_but_not_in_given_order_according_to_custom_comparison_strategy() { + // GIVEN String actual = "{ 'title':'A Game of Thrones', 'author':'George Martin'}"; - String[] sequenceValues = { "{", "author", "A Game of Thrones", "}" }; - assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> stringsWithCaseInsensitiveComparisonStrategy.assertContainsSubsequence(someInfo(), actual, sequenceValues)) - .withMessage(shouldContainSubsequence(actual, sequenceValues, 1, comparisonStrategy).create()); + String[] subsequence = { "{", "author", "A Game of Thrones", "}" }; + // WHEN + expectAssertionError(() -> stringsWithCaseInsensitiveComparisonStrategy.assertContainsSubsequence(INFO, actual, subsequence)); + // THEN + verify(failures).failure(INFO, shouldContainSubsequence(actual, subsequence, 1, comparisonStrategy)); + } + + @Test + void should_pass_if_empty_string_contains_multiple_empty_subsequence_bug_2158() { + strings.assertContainsSubsequence(INFO, "", array("")); + strings.assertContainsSubsequence(INFO, "", array("", "")); + strings.assertContainsSubsequence(INFO, "", array("", "", "")); + strings.assertContainsSubsequence(INFO, "", array("", "", "", "")); } } diff --git a/src/test/java/org/assertj/core/matcher/AssertionMatcher_matches_Test.java b/src/test/java/org/assertj/core/matcher/AssertionMatcher_matches_Test.java index c60baf58ba5..509cbdb6b32 100644 --- a/src/test/java/org/assertj/core/matcher/AssertionMatcher_matches_Test.java +++ b/src/test/java/org/assertj/core/matcher/AssertionMatcher_matches_Test.java @@ -94,7 +94,7 @@ void matcher_should_fill_description_when_assertion_fails() { verify(description).appendText(argThat(new ArgumentMatcher() { @Override public boolean matches(String s) { - return s.contains(format("%nexpected: 0%nbut was : 1")) + return s.contains(format("%nexpected: 0%n but was: 1")) && s.contains("at org.assertj.core.matcher.AssertionMatcher_matches_Test$1.assertion(AssertionMatcher_matches_Test.java:") && s.contains("at org.assertj.core.matcher.AssertionMatcher.matches(AssertionMatcher.java:") && s.contains("at org.assertj.core.matcher.AssertionMatcher_matches_Test.matcher_should_fill_description_when_assertion_fails(AssertionMatcher_matches_Test.java:"); diff --git a/src/test/java/org/assertj/core/osgi/soft/CustomSoftAssertionTest.java b/src/test/java/org/assertj/core/osgi/soft/CustomSoftAssertionTest.java index 823f6c5d7d0..66edb12848d 100644 --- a/src/test/java/org/assertj/core/osgi/soft/CustomSoftAssertionTest.java +++ b/src/test/java/org/assertj/core/osgi/soft/CustomSoftAssertionTest.java @@ -22,8 +22,8 @@ import org.assertj.core.api.AbstractMapAssert; import org.assertj.core.api.AbstractSoftAssertions; import org.assertj.core.api.Assertions; +import org.assertj.core.api.ListAssert; import org.assertj.core.api.ObjectAssert; -import org.assertj.core.api.ProxyableListAssert; import org.junit.jupiter.api.Test; public class CustomSoftAssertionTest { @@ -76,7 +76,7 @@ public TestProxyableMapAssert(Map actual) { @Override protected AbstractListAssert, ELEMENT, ObjectAssert> newListAssertInstance(List newActual) { - return new ProxyableListAssert<>(newActual); + return new ListAssert<>(newActual); } } diff --git a/src/test/java/org/assertj/core/perf/SoftAssertionsPerfTest.java b/src/test/java/org/assertj/core/perf/SoftAssertionsPerfTest.java index 8e7adb9655c..53b8a185bcf 100644 --- a/src/test/java/org/assertj/core/perf/SoftAssertionsPerfTest.java +++ b/src/test/java/org/assertj/core/perf/SoftAssertionsPerfTest.java @@ -171,7 +171,6 @@ void should_return_failure_of_last_assertion_with_nested_calls() { assertThat(softly.wasSuccess()).isFalse(); } - @SuppressWarnings("unchecked") @Test void should_be_able_to_catch_exceptions_thrown_by_map_assertions() { // GIVEN @@ -183,7 +182,6 @@ void should_be_able_to_catch_exceptions_thrown_by_map_assertions() { assertThat(errors).hasSize(2); } - @SuppressWarnings("unchecked") @Test void should_be_able_to_catch_exceptions_thrown_by_all_proxied_methods() { // perform a bunch of soft assertions diff --git a/src/test/java/org/assertj/core/presentation/StandardRepresentation_throwable_format_Test.java b/src/test/java/org/assertj/core/presentation/StandardRepresentation_throwable_format_Test.java index 3d561b52a57..3c2858845d5 100644 --- a/src/test/java/org/assertj/core/presentation/StandardRepresentation_throwable_format_Test.java +++ b/src/test/java/org/assertj/core/presentation/StandardRepresentation_throwable_format_Test.java @@ -13,10 +13,14 @@ package org.assertj.core.presentation; import static java.lang.String.format; -import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.configuration.Configuration.DEFAULT_CONFIGURATION; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import org.assertj.core.configuration.Configuration; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; /** @@ -25,6 +29,7 @@ * @author XiaoMingZHM Eveneko */ class StandardRepresentation_throwable_format_Test { + private static final Representation REPRESENTATION = new StandardRepresentation(); // Just to make sure the stack trace is long enough. @@ -41,6 +46,12 @@ static void boom() { } } + @AfterEach + void afterEach() { + // Restore default configuration after each test + DEFAULT_CONFIGURATION.apply(); + } + @Test void should_not_display_stacktrace_if_maxStackTraceElementsDisplayed_is_zero() { // GIVEN @@ -48,9 +59,9 @@ void should_not_display_stacktrace_if_maxStackTraceElementsDisplayed_is_zero() { configuration.setMaxStackTraceElementsDisplayed(0); configuration.apply(); // WHEN - String toString = REPRESENTATION.toStringOf(catchThrowable(() -> Test1.boom())); + String toString = REPRESENTATION.toStringOf(catchThrowable(Test1::boom)); // THEN - assertThat(toString).isEqualTo("java.lang.RuntimeException"); + then(toString).isEqualTo("java.lang.RuntimeException"); } @Test @@ -60,13 +71,16 @@ void should_display_the_configured_number_of_stacktrace_elements() { // configuration.setMaxStackTraceElementsDisplayed(3); configuration.apply(); // WHEN - String toString = REPRESENTATION.toStringOf(catchThrowable(() -> Test1.boom())); + String toString = REPRESENTATION.toStringOf(catchThrowable(Test1::boom)); // THEN - assertThat(toString).containsSubsequence(format("java.lang.RuntimeException%n"), - format("\tat org.assertj.core.presentation.StandardRepresentation_throwable_format_Test$Test1$Test2.boom2(StandardRepresentation_throwable_format_Test.java:"), - format("\tat org.assertj.core.presentation.StandardRepresentation_throwable_format_Test$Test1.boom(StandardRepresentation_throwable_format_Test.java"), - format("\tat org.assertj.core.presentation.StandardRepresentation_throwable_format_Test.lambda"), - format("\t...(69 remaining lines not displayed - this can be changed with Assertions.setMaxStackTraceElementsDisplayed)")); + then(toString).matches("java\\.lang\\.RuntimeException\\R" + + "\\tat org\\.assertj\\.core\\.presentation\\.StandardRepresentation_throwable_format_Test\\$Test1\\$Test2\\.boom2\\(StandardRepresentation_throwable_format_Test\\.java:\\d+\\)\\R" + + + "\\tat org\\.assertj\\.core\\.presentation\\.StandardRepresentation_throwable_format_Test\\$Test1\\.boom\\(StandardRepresentation_throwable_format_Test\\.java:\\d+\\)\\R" + + + "\\tat org\\.assertj\\.core\\.api\\.ThrowableAssert\\.catchThrowable\\(ThrowableAssert\\.java:\\d+\\)\\R" + + + "\\t\\.{3}\\(\\d+ remaining lines not displayed - this can be changed with Assertions\\.setMaxStackTraceElementsDisplayed\\)"); } @Test @@ -76,11 +90,21 @@ void should_display_the_full_stacktrace() { configuration.setMaxStackTraceElementsDisplayed(100); configuration.apply(); // WHEN - String toString = REPRESENTATION.toStringOf(catchThrowable(() -> Test1.boom())); + String toString = REPRESENTATION.toStringOf(catchThrowable(Test1::boom)); // THEN - assertThat(toString).startsWith(format("java.lang.RuntimeException%n" - + "\tat org.assertj.core.presentation.StandardRepresentation_throwable_format_Test$Test1$Test2.boom2(StandardRepresentation_throwable_format_Test.java")) - .doesNotContain("remaining lines not displayed"); + then(toString).startsWith(format("java.lang.RuntimeException%n" + + "\tat org.assertj.core.presentation.StandardRepresentation_throwable_format_Test$Test1$Test2.boom2(StandardRepresentation_throwable_format_Test.java")) + .doesNotContain("remaining lines not displayed"); } + @Test + void should_display_toString_when_null_stack() { + // GIVEN + Throwable throwable = mock(Throwable.class); + when(throwable.toString()).thenReturn("throwable string"); + // WHEN + String actual = REPRESENTATION.toStringOf(throwable); + // THEN + then(actual).isEqualTo("throwable string"); + } } diff --git a/src/test/java/org/assertj/core/presentation/StandardRepresentation_toStringOf_AtomicReferences_Test.java b/src/test/java/org/assertj/core/presentation/StandardRepresentation_toStringOf_AtomicReferences_Test.java new file mode 100644 index 00000000000..a7db765cee6 --- /dev/null +++ b/src/test/java/org/assertj/core/presentation/StandardRepresentation_toStringOf_AtomicReferences_Test.java @@ -0,0 +1,303 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.presentation; + +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.presentation.StandardRepresentation.STANDARD_REPRESENTATION; +import static org.assertj.core.util.Lists.list; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.atomic.AtomicMarkableReference; +import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.atomic.AtomicStampedReference; + +import org.junit.Test; + +@SuppressWarnings({ "serial", "unused" }) +public class StandardRepresentation_toStringOf_AtomicReferences_Test { + + @Test + public void should_use_assertj_representation_for_AtomicReference() { + // GIVEN + Object myData = new AtomicReference("value"); + // WHEN + String stringOf = STANDARD_REPRESENTATION.toStringOf(myData); + // THEN + then(stringOf).isEqualTo("AtomicReference[\"value\"]"); + } + + @Test + public void should_use_overridden_toString_in_AtomicReference_subclass() { + class MyData extends AtomicReference { + private String description; + + MyData(String description) { + this.description = description; + } + + @Override + public String toString() { + return "MyData[" + description + "]"; + } + } + // GIVEN + Object myData = new MyData("Description"); + // WHEN + String stringOf = STANDARD_REPRESENTATION.toStringOf(myData); + // THEN + then(stringOf).isEqualTo("MyData[Description]"); + } + + @Test + public void should_use_the_last_overridden_toString_in_AtomicReference_subclasses() { + class MyData extends AtomicReference { + protected String description; + + MyData(String description) { + this.description = description; + } + + @Override + public String toString() { + return "MyData[" + description + "]"; + } + } + class MySubData extends MyData { + + MySubData(String description) { + super(description); + } + + @Override + public String toString() { + return "SubMyData[" + description + "]"; + } + } + // GIVEN + Object myData = new MySubData("Description"); + // WHEN + String stringOf = STANDARD_REPRESENTATION.toStringOf(myData); + // THEN + then(stringOf).isEqualTo("SubMyData[Description]"); + } + + @Test + public void should_use_overridden_toString_in_AtomicReference_intermediate_subclass() { + class MyData extends AtomicReference { + protected String description; + + MyData(String description) { + this.description = description; + } + + @Override + public String toString() { + return "MyData[" + description + "]"; + } + } + class MySubData extends MyData { + + MySubData(String description) { + super(description); + } + + // no toString => use MyData.toString + } + // GIVEN + Object myData = new MySubData("Description"); + // WHEN + String stringOf = STANDARD_REPRESENTATION.toStringOf(myData); + // THEN + then(stringOf).isEqualTo("MyData[Description]"); + } + + @Test + public void should_use_assertj_AtomicReference_representation_as_toString_was_not_overridden_in_AtomicReference_subclass() { + class MyData extends AtomicReference { + + MyData(String value) { + super(value); + } + + // no overridden toString => use assertj representation + } + // GIVEN + Object myData = new MyData("value"); + // WHEN + String stringOf = STANDARD_REPRESENTATION.toStringOf(myData); + // THEN + then(stringOf).isEqualTo("MyData[\"value\"]"); + } + + @Test + public void should_use_assertj_representation_for_AtomicMarkableReference() { + // GIVEN + Object myData = new AtomicMarkableReference("value", true); + // WHEN + String stringOf = STANDARD_REPRESENTATION.toStringOf(myData); + // THEN + then(stringOf).isEqualTo("AtomicMarkableReference[marked=true, reference=\"value\"]"); + } + + @Test + public void should_use_overridden_toString_in_AtomicMarkableReference_subclass() { + class MyData extends AtomicMarkableReference { + private String description; + + MyData(String description) { + super(description, true); + this.description = description; + } + + @Override + public String toString() { + return "MyData[" + description + "]"; + } + } + // GIVEN + Object myData = new MyData("Description"); + // WHEN + String stringOf = STANDARD_REPRESENTATION.toStringOf(myData); + // THEN + then(stringOf).isEqualTo("MyData[Description]"); + } + + @Test + public void should_use_assertj_AtomicMarkableReference_representation_as_toString_was_not_overridden_in_AtomicMarkableReference_subclass() { + class MyData extends AtomicMarkableReference { + private String description; + + MyData(String description) { + super(description, true); + this.description = description; + } + + // has no overridden toString, use the predefined one which gives "%s[marked=%s, reference=%s]" + } + // GIVEN + Object myData = new MyData("Description"); + // WHEN + String stringOf = STANDARD_REPRESENTATION.toStringOf(myData); + // THEN + then(stringOf).isEqualTo("MyData[marked=true, reference=\"Description\"]"); + } + + @Test + public void should_use_assertj_representation_for_AtomicStampedReference() { + // GIVEN + Object myData = new AtomicStampedReference("value", 1); + // WHEN + String stringOf = STANDARD_REPRESENTATION.toStringOf(myData); + // THEN + then(stringOf).isEqualTo("AtomicStampedReference[stamp=1, reference=\"value\"]"); + } + + @Test + public void should_use_overridden_toString_AtomicStampedReference() { + class MyData extends AtomicStampedReference { + private String description; + + MyData(String description) { + super(description, 0); + this.description = description; + } + + @Override + public String toString() { + return "MyData[" + description + "]"; + } + } + // GIVEN + Object myData = new MyData("Description"); + // WHEN + String stringOf = STANDARD_REPRESENTATION.toStringOf(myData); + // THEN + then(stringOf).isEqualTo("MyData[Description]"); + } + + @Test + public void should_use_predefined_toString_AtomicStampedReference() { + class MyData extends AtomicStampedReference { + private String description; + + MyData(String description) { + super(description, 0); + this.description = description; + } + + // has no overridden toString, use the predefined one which gives "%s[stamp=%s, reference=%s]" + } + // GIVEN + Object myData = new MyData("Description"); + // WHEN + String stringOf = STANDARD_REPRESENTATION.toStringOf(myData); + // THEN + then(stringOf).isEqualTo("MyData[stamp=0, reference=\"Description\"]"); + } + + @Test + public void should_use_smartFormat() { + class MyIterable implements Iterable { + ArrayList arrayList; + + public MyIterable(String[] strings) { + arrayList = new ArrayList<>(Arrays.asList(strings)); + } + + @Override + public Iterator iterator() { + return arrayList.iterator(); + } + + // has no overridden toString + } + // GIVEN + String[] strings = { "A", "B", "C" }; + MyIterable myIterable = new MyIterable(strings); + // WHEN + String stringOf = STANDARD_REPRESENTATION.toStringOf(myIterable); + // THEN + then(stringOf).isEqualTo("[\"A\", \"B\", \"C\"]"); + } + + @Test + public void should_use_overridden_toString() { + class MyIterable implements Iterable { + List arrayList; + + public MyIterable(String[] strings) { + arrayList = list(strings); + } + + @Override + public Iterator iterator() { + return arrayList.iterator(); + } + + @Override + public String toString() { + return "MyIterable: " + arrayList; + } + } + // GIVEN + String[] strings = { "A", "B", "C" }; + MyIterable myIterable = new MyIterable(strings); + // WHEN + String stringOf = STANDARD_REPRESENTATION.toStringOf(myIterable); + // THEN + then(stringOf).isEqualTo("MyIterable: [A, B, C]"); + } +} diff --git a/src/test/java/org/assertj/core/test/ErrorMessagesForTest.java b/src/test/java/org/assertj/core/test/ErrorMessagesForTest.java index e0a33857933..cae5b82feb7 100644 --- a/src/test/java/org/assertj/core/test/ErrorMessagesForTest.java +++ b/src/test/java/org/assertj/core/test/ErrorMessagesForTest.java @@ -17,11 +17,11 @@ public class ErrorMessagesForTest { public static String shouldBeEqualMessage(String actual, String expected) { - return format("%nexpected: " + expected + "%nbut was : " + actual); + return format("%nexpected: " + expected + "%n but was: " + actual); } public static String shouldBeEqualMessage(String description, String actual, String expected) { - return format("[" + description + "] %nexpected: " + expected + "%nbut was : " + actual); + return format("[" + description + "] %nexpected: " + expected + "%n but was: " + actual); } } diff --git a/src/test/java/org/assertj/core/test/Maps.java b/src/test/java/org/assertj/core/test/Maps.java index d02a1ce189a..485866643d8 100644 --- a/src/test/java/org/assertj/core/test/Maps.java +++ b/src/test/java/org/assertj/core/test/Maps.java @@ -13,7 +13,9 @@ package org.assertj.core.test; import java.util.LinkedHashMap; +import java.util.Map; import java.util.TreeMap; +import java.util.function.Supplier; import org.assertj.core.data.MapEntry; @@ -24,18 +26,19 @@ public final class Maps { @SafeVarargs public static LinkedHashMap mapOf(MapEntry... entries) { - LinkedHashMap map = new LinkedHashMap<>(); - for (MapEntry entry : entries) { - map.put(entry.key, entry.value); - } - return map; + return mapOf(LinkedHashMap::new, entries); } @SafeVarargs public static , V> TreeMap treeMapOf(MapEntry... entries) { - TreeMap map = new TreeMap<>(); - for (MapEntry entry : entries) { - map.put(entry.key, entry.value); + return mapOf(TreeMap::new, entries); + } + + @SafeVarargs + public static > M mapOf(Supplier supplier, Map.Entry... entries) { + M map = supplier.get(); + for (Map.Entry entry : entries) { + map.put(entry.getKey(), entry.getValue()); } return map; } diff --git a/src/test/java/org/assertj/core/util/NaturalOrderComparatorTest.java b/src/test/java/org/assertj/core/util/NaturalOrderComparatorTest.java new file mode 100644 index 00000000000..976c26e31d1 --- /dev/null +++ b/src/test/java/org/assertj/core/util/NaturalOrderComparatorTest.java @@ -0,0 +1,40 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.util; + +import static org.assertj.core.api.BDDAssertions.then; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +@DisplayName("NaturalOrderComparator") +class NaturalOrderComparatorTest { + + private static final NaturalOrderComparator NATURAL_ORDER_COMPARATOR = new NaturalOrderComparator<>(String.class); + + @Test + public void should_compare_instances_according_to_their_natural_order() { + // GIVEN + String s1 = "aaa"; + String s2 = "bbb"; + // WHEN + int less = NATURAL_ORDER_COMPARATOR.compareNonNull(s1, s2); + int equal = NATURAL_ORDER_COMPARATOR.compareNonNull(s1, s1); + int greater = NATURAL_ORDER_COMPARATOR.compareNonNull(s2, s1); + // THEN + then(less).isNegative(); + then(equal).isZero(); + then(greater).isPositive(); + } + +} diff --git a/src/test/java/org/assertj/core/util/NullSafeComparatorTest.java b/src/test/java/org/assertj/core/util/NullSafeComparatorTest.java new file mode 100644 index 00000000000..e0f603976fe --- /dev/null +++ b/src/test/java/org/assertj/core/util/NullSafeComparatorTest.java @@ -0,0 +1,65 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.assertj.core.util; + +import static org.assertj.core.api.BDDAssertions.then; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +@DisplayName("NullSafeComparator") +class NullSafeComparatorTest { + + private static final NullSafeComparator NULL_SAFE_COMPARATOR = new NullSafeComparator() { + + @Override + protected int compareNonNull(Object o1, Object o2) { + return 0; + } + + }; + + @Test + public void should_evaluate_null_instance_as_less_than_non_null_instance() { + // GIVEN + Object o1 = null; + Object o2 = "foo"; + // WHEN + int compare = NULL_SAFE_COMPARATOR.compare(o1, o2); + // THEN + then(compare).isNegative(); + } + + @Test + public void should_evaluate_non_null_instance_as_greater_than_null_instance() { + // GIVEN + Object o1 = "foo"; + Object o2 = null; + // WHEN + int compare = NULL_SAFE_COMPARATOR.compare(o1, o2); + // THEN + then(compare).isPositive(); + } + + @Test + public void should_evaluate_null_instances_as_equal() { + // GIVEN + Object o1 = null; + Object o2 = null; + // WHEN + int compare = NULL_SAFE_COMPARATOR.compare(o1, o2); + // THEN + then(compare).isZero(); + } + +} diff --git a/src/main/java/org/assertj/core/api/ProxyablePredicateAssert.java b/src/test/java/org/assertj/core/util/PathNaturalOrderComparatorTest.java similarity index 59% rename from src/main/java/org/assertj/core/api/ProxyablePredicateAssert.java rename to src/test/java/org/assertj/core/util/PathNaturalOrderComparatorTest.java index 929b1c51403..6762b5f221d 100644 --- a/src/main/java/org/assertj/core/api/ProxyablePredicateAssert.java +++ b/src/test/java/org/assertj/core/util/PathNaturalOrderComparatorTest.java @@ -10,20 +10,19 @@ * * Copyright 2012-2021 the original author or authors. */ -package org.assertj.core.api; +package org.assertj.core.util; -import java.util.function.Predicate; +import static org.assertj.core.api.BDDAssertions.then; -/** - * Concrete assertions for {@link Predicate}s without any final methods to allow proxying. - * - * @author Gaël LHEZ - * @since 3.5.2 - */ -public class ProxyablePredicateAssert extends AbstractPredicateAssert, T> { +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +@DisplayName("PathNaturalOrderComparator") +class PathNaturalOrderComparatorTest { - public ProxyablePredicateAssert(Predicate actual) { - super(actual, ProxyablePredicateAssert.class); + @Test + public void should_return_a_user_friendly_description() { + then(PathNaturalOrderComparator.INSTANCE).hasToString("lexicographic comparator (Path natural order)"); } } diff --git a/src/test/java/org/assertj/core/util/introspection/PropertyOrFieldSupport_getSimpleValue_with_Map_input_Test.java b/src/test/java/org/assertj/core/util/introspection/PropertyOrFieldSupport_getSimpleValue_with_Map_input_Test.java index 3417e442276..69f6987c128 100644 --- a/src/test/java/org/assertj/core/util/introspection/PropertyOrFieldSupport_getSimpleValue_with_Map_input_Test.java +++ b/src/test/java/org/assertj/core/util/introspection/PropertyOrFieldSupport_getSimpleValue_with_Map_input_Test.java @@ -12,6 +12,7 @@ */ package org.assertj.core.util.introspection; +import static org.assertj.core.api.Assertions.catchThrowable; import static org.assertj.core.api.BDDAssertions.then; import java.util.AbstractMap; @@ -20,12 +21,14 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; /** * Tests for {@link PropertyOrFieldSupport#getSimpleValue(String, Object)} with {@code Map} input. - * - * @author Stefano Cordio - */ + * + * @author Stefano Cordio + */ @DisplayName("PropertyOrFieldSupport getSimpleValue(String, Map)") class PropertyOrFieldSupport_getSimpleValue_with_Map_input_Test { @@ -52,22 +55,26 @@ void should_extract_field_value_even_if_map_key_matches_given_name() { then(value).isInstanceOf(Collection.class); } - @Test - void should_extract_map_value_when_no_property_or_field_matches_given_name() { + @ParameterizedTest + @CsvSource({ + "key, value", + "key, ", + }) + void should_extract_map_value_when_no_property_or_field_matches_given_name(String key, String expected) { // GIVEN - map.put("key", "value"); + map.put(key, expected); // WHEN - Object value = underTest.getSimpleValue("key", map); + Object value = underTest.getSimpleValue(key, map); // THEN - then(value).isEqualTo("value"); + then(value).isEqualTo(expected); } @Test - void should_extract_null_when_given_name_is_not_found() { + void should_fail_when_given_name_is_not_found() { // WHEN - Object value = underTest.getSimpleValue("unknown", map); + Throwable thrown = catchThrowable(() -> underTest.getSimpleValue("unknown", map)); // THEN - then(value).isNull(); + then(thrown).isInstanceOf(IntrospectionError.class); } } diff --git a/src/test/java/org/assertj/core/util/introspection/PropertyOrFieldSupport_getValueOf_Test.java b/src/test/java/org/assertj/core/util/introspection/PropertyOrFieldSupport_getValueOf_Test.java index ec8e6bec88a..8e19d64b9f4 100644 --- a/src/test/java/org/assertj/core/util/introspection/PropertyOrFieldSupport_getValueOf_Test.java +++ b/src/test/java/org/assertj/core/util/introspection/PropertyOrFieldSupport_getValueOf_Test.java @@ -14,8 +14,10 @@ import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.catchThrowable; import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.util.AssertionsUtil.expectAssertionError; import static org.assertj.core.util.introspection.FieldSupport.EXTRACTION_OF_PUBLIC_FIELD_ONLY; import java.util.HashMap; @@ -184,21 +186,26 @@ void should_throw_exception_if_no_object_is_given() { void should_extract_single_value_from_maps_by_key() { String key1 = "key1"; String key2 = "key2"; + String keyWithNullValue = "key with null"; Map map1 = new HashMap<>(); map1.put(key1, yoda); Employee luke = new Employee(2L, new Name("Luke"), 22); map1.put(key2, luke); + map1.put(keyWithNullValue, null); Map map2 = new HashMap<>(); map2.put(key1, yoda); Employee han = new Employee(3L, new Name("Han"), 31); map2.put(key2, han); + map2.put(keyWithNullValue, null); List> maps = asList(map1, map2); assertThat(maps).extracting(key2).containsExactly(luke, han); assertThat(maps).extracting(key2, Employee.class).containsExactly(luke, han); assertThat(maps).extracting(key1).containsExactly(yoda, yoda); - assertThat(maps).extracting("bad key").containsExactly(null, null); + assertThat(maps).extracting(keyWithNullValue).containsExactly(null, null); + + assertThatExceptionOfType(IntrospectionError.class).isThrownBy(() -> assertThat(maps).extracting("bad key")); } @Test diff --git a/src/test/java/org/example/test/AssertJMultipleFailuresError_getMessage_Test.java b/src/test/java/org/example/test/AssertJMultipleFailuresError_getMessage_Test.java new file mode 100644 index 00000000000..5bc2a1b8c6c --- /dev/null +++ b/src/test/java/org/example/test/AssertJMultipleFailuresError_getMessage_Test.java @@ -0,0 +1,131 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.example.test; + +import static java.lang.String.format; +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.test.ErrorMessagesForTest.shouldBeEqualMessage; +import static org.assertj.core.util.AssertionsUtil.expectAssertionError; +import static org.assertj.core.util.Lists.list; + +import org.assertj.core.api.SoftAssertions; +import org.assertj.core.error.AssertJMultipleFailuresError; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +// this is not in an assertj package as we want to check the stack trace and we filter the element in assertj +@DisplayName("AssertJMultipleFailuresError getMessage") +class AssertJMultipleFailuresError_getMessage_Test { + + @Test + void should_honor_description() { + // GIVEN + String description = "desc"; + AssertJMultipleFailuresError error = new AssertJMultipleFailuresError(description, list(new AssertionError("boom"))); + // WHEN + String message = error.getMessage(); + // THEN + then(message).startsWith(format("%n%s", description)); + } + + @Test + void should_include_errors_count_and_clearly_separate_error_messages() { + // GIVEN + SoftAssertions softly = new SoftAssertions(); + softly.assertThat(list("")).isEmpty(); + softly.assertThat(list("a", "b", "c")).as("isEmpty list").isEmpty(); + softly.assertThat("abc").isEmpty(); + softly.assertThat("abc").as("isEmpty string").isEmpty(); + softly.assertThat("abc").isEqualTo("bcd"); + softly.assertThat("abc").as("isEqualTo").isEqualTo("bcd"); + softly.assertThat(list("a", "b", "c")).as("contains").contains("e").doesNotContain("a"); + softly.assertThat(list("a", "b", "c")).contains("e").doesNotContain("a"); + // WHEN + AssertionError error = expectAssertionError(() -> softly.assertAll()); + // THEN + then(error).hasMessageContainingAll(format("%nMultiple Failures (10 failures)%n"), + format("-- failure 1 --%n"), + format("Expecting empty but was: [\"\"]%n"), + format("-- failure 2 --%n"), + format("[isEmpty list] %n"), + format("Expecting empty but was: [\"a\", \"b\", \"c\"]%n"), + format("-- failure 3 --%n"), + format("Expecting empty but was: \"abc\"%n"), + format("-- failure 4 --%n"), + format("[isEmpty string] %n"), + format("Expecting empty but was: \"abc\"%n"), + format("-- failure 5 --"), + format(shouldBeEqualMessage("\"abc\"", "\"bcd\"") + "%n"), + format("-- failure 6 --%n"), + format(shouldBeEqualMessage("isEqualTo", "\"abc\"", "\"bcd\"") + "%n"), + format("-- failure 7 --%n"), + format("[contains] %n"), + format("Expecting ArrayList:%n"), + format(" [\"a\", \"b\", \"c\"]%n"), + format("to contain:%n"), + format(" [\"e\"]%n"), + format("but could not find the following element(s):%n"), + format(" [\"e\"]%n"), + format("%n"), + format("-- failure 8 --%n"), + format("[contains] %n"), + format("Expecting%n"), + format(" [\"a\", \"b\", \"c\"]%n"), + format("not to contain%n"), + format(" [\"a\"]%n"), + format("but found%n"), + format(" [\"a\"]%n"), + format("%n"), + format("-- failure 9 --%n"), + format("Expecting ArrayList:%n"), + format(" [\"a\", \"b\", \"c\"]%n"), + format("to contain:%n"), + format(" [\"e\"]%n"), + format("but could not find the following element(s):%n"), + format(" [\"e\"]%n"), + format("%n"), + format("-- failure 10 --%n"), + format("Expecting%n"), + format(" [\"a\", \"b\", \"c\"]%n"), + format("not to contain%n"), + format(" [\"a\"]%n"), + format("but found%n"), + format(" [\"a\"]%n")); + } + + @Test + void should_include_stack_trace_allowing_to_navigate_to_the_failing_assertion_in_test() { + // GIVEN + SoftAssertions softly = new SoftAssertions(); + softly.assertThat(list("")).isEmpty(); + softly.assertThat("abc").as("isEmpty string").isEmpty(); + softly.assertThat("abc").isEqualTo("bcd"); + // WHEN + AssertionError error = expectAssertionError(() -> softly.assertAll()); + // THEN + // @format:off + then(error).hasMessage(format("%nMultiple Failures (3 failures)%n" + + "-- failure 1 --%n" + + "Expecting empty but was: [\"\"]%n" + + "at AssertJMultipleFailuresError_getMessage_Test.should_include_stack_trace_allowing_to_navigate_to_the_failing_assertion_in_test(AssertJMultipleFailuresError_getMessage_Test.java:110)%n" + + "-- failure 2 --%n" + + "[isEmpty string] %n" + + "Expecting empty but was: \"abc\"%n" + + "at AssertJMultipleFailuresError_getMessage_Test.should_include_stack_trace_allowing_to_navigate_to_the_failing_assertion_in_test(AssertJMultipleFailuresError_getMessage_Test.java:111)%n" + + "-- failure 3 --" + + shouldBeEqualMessage("\"abc\"", "\"bcd\"") + "%n" + + "at AssertJMultipleFailuresError_getMessage_Test.should_include_stack_trace_allowing_to_navigate_to_the_failing_assertion_in_test(AssertJMultipleFailuresError_getMessage_Test.java:112)")); + // @format:on + } + +} diff --git a/src/test/java/org/example/test/AutoClosableSoftAssertionsLineNumberTest.java b/src/test/java/org/example/test/AutoClosableSoftAssertionsLineNumberTest.java index cc01451df92..da82e1de953 100644 --- a/src/test/java/org/example/test/AutoClosableSoftAssertionsLineNumberTest.java +++ b/src/test/java/org/example/test/AutoClosableSoftAssertionsLineNumberTest.java @@ -14,7 +14,7 @@ import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.catchThrowableOfType; +import static org.assertj.core.util.AssertionsUtil.expectAssertionError; import org.assertj.core.api.AutoCloseableSoftAssertions; import org.junit.jupiter.api.Test; @@ -33,16 +33,16 @@ void should_print_line_numbers_of_failed_assertions() { .isLessThan(0) .isLessThan(1); // WHEN - AssertionError error = catchThrowableOfType(softly::close, AssertionError.class); + AssertionError error = expectAssertionError(softly::close); // THEN assertThat(error).hasMessageContaining(format("%n" - + "Expecting:%n" + + "Expecting actual:%n" + " 1%n" + "to be less than:%n" + " 0 %n" + "at AutoClosableSoftAssertionsLineNumberTest.should_print_line_numbers_of_failed_assertions(AutoClosableSoftAssertionsLineNumberTest.java:33)%n")) .hasMessageContaining(format("%n" - + "Expecting:%n" + + "Expecting actual:%n" + " 1%n" + "to be less than:%n" + " 1 %n" diff --git a/src/test/java/org/example/test/BDDSoftAssertionsLineNumberTest.java b/src/test/java/org/example/test/BDDSoftAssertionsLineNumberTest.java index 684fc60cd3e..769f0df9963 100644 --- a/src/test/java/org/example/test/BDDSoftAssertionsLineNumberTest.java +++ b/src/test/java/org/example/test/BDDSoftAssertionsLineNumberTest.java @@ -14,7 +14,7 @@ import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.catchThrowableOfType; +import static org.assertj.core.util.AssertionsUtil.expectAssertionError; import org.assertj.core.api.BDDSoftAssertions; import org.junit.jupiter.api.Test; @@ -33,16 +33,16 @@ void should_print_line_numbers_of_failed_assertions() { .isLessThan(0) .isLessThan(1); // WHEN - AssertionError error = catchThrowableOfType(softly::assertAll, AssertionError.class); + AssertionError error = expectAssertionError(softly::assertAll); // THEN assertThat(error).hasMessageContaining(format("%n" - + "Expecting:%n" + + "Expecting actual:%n" + " 1%n" + "to be less than:%n" + " 0 %n" + "at BDDSoftAssertionsLineNumberTest.should_print_line_numbers_of_failed_assertions(BDDSoftAssertionsLineNumberTest.java:33)%n")) .hasMessageContaining(format("%n" - + "Expecting:%n" + + "Expecting actual:%n" + " 1%n" + "to be less than:%n" + " 1 %n" diff --git a/src/test/java/org/example/test/CustomSoftAssertionsLineNumberTest.java b/src/test/java/org/example/test/CustomSoftAssertionsLineNumberTest.java index f6fbf7b46ef..cb6d23d0029 100644 --- a/src/test/java/org/example/test/CustomSoftAssertionsLineNumberTest.java +++ b/src/test/java/org/example/test/CustomSoftAssertionsLineNumberTest.java @@ -13,7 +13,7 @@ package org.example.test; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.catchThrowableOfType; +import static org.assertj.core.util.AssertionsUtil.expectAssertionError; import org.junit.jupiter.api.Test; @@ -29,7 +29,7 @@ void should_print_line_numbers_of_failed_assertions_even_if_custom_assertion_in_ MyProjectSoftAssertions softly = new MyProjectSoftAssertions(); softly.assertThat(new MyProjectClass("v1")).hasValue("v2"); // WHEN - AssertionError error = catchThrowableOfType(softly::assertAll, AssertionError.class); + AssertionError error = expectAssertionError(softly::assertAll); // THEN // does not check the exact line number because it can vary (for example when Jacoco injects fields to check code coverage) assertThat(error).hasStackTraceContaining("CustomSoftAssertionsLineNumberTest.should_print_line_numbers_of_failed_assertions_even_if_custom_assertion_in_non_assertj_package(CustomSoftAssertionsLineNumberTest.java:3"); diff --git a/src/test/java/org/example/test/DefaultAssertionErrorCollector_Test.java b/src/test/java/org/example/test/DefaultAssertionErrorCollector_Test.java new file mode 100644 index 00000000000..ef3e0254143 --- /dev/null +++ b/src/test/java/org/example/test/DefaultAssertionErrorCollector_Test.java @@ -0,0 +1,47 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * Copyright 2012-2021 the original author or authors. + */ +package org.example.test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.util.AssertionsUtil.expectAssertionError; + +import java.util.List; + +import org.assertj.core.api.DefaultAssertionErrorCollector; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +// not in an assertj package to be able to check the stack trace as we filter the stack trace element in assertj packages +@DisplayName("DefaultAssertionErrorCollector assertionErrorsCollected") +class DefaultAssertionErrorCollector_Test { + + private DefaultAssertionErrorCollector defaultAssertionErrorCollector = new DefaultAssertionErrorCollector(); + + @Test + void collected_errors_should_be_decorate_with_line_numbers() { + // GIVEN + AssertionError error1 = expectAssertionError(() -> assertThat("foo").isEqualTo("bar")); + AssertionError error2 = expectAssertionError(() -> assertThat(1).isNegative()); + defaultAssertionErrorCollector.collectAssertionError(error1); + defaultAssertionErrorCollector.collectAssertionError(error2); + // WHEN + List decoratedErrors = defaultAssertionErrorCollector.assertionErrorsCollected(); + // THEN + then(decoratedErrors.get(0)).hasMessageContainingAll("at DefaultAssertionErrorCollector_Test.lambda", + "(DefaultAssertionErrorCollector_Test.java:34)"); + then(decoratedErrors.get(1)).hasMessageContaining("at DefaultAssertionErrorCollector_Test.lambda", + "(DefaultAssertionErrorCollector_Test.java:35)"); + } + +} diff --git a/src/test/java/org/example/test/SoftAssertionsLineNumberTest.java b/src/test/java/org/example/test/SoftAssertionsLineNumberTest.java index ab7257bff4e..7776b15823b 100644 --- a/src/test/java/org/example/test/SoftAssertionsLineNumberTest.java +++ b/src/test/java/org/example/test/SoftAssertionsLineNumberTest.java @@ -14,7 +14,7 @@ import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.catchThrowableOfType; +import static org.assertj.core.util.AssertionsUtil.expectAssertionError; import java.util.Optional; import java.util.function.Predicate; @@ -37,16 +37,16 @@ void should_print_line_numbers_of_failed_assertions() { .isLessThan(0) .isLessThan(1); // WHEN - AssertionError error = catchThrowableOfType(softly::assertAll, AssertionError.class); + AssertionError error = expectAssertionError(softly::assertAll); // THEN assertThat(error).hasMessageContaining(format("%n" - + "Expecting:%n" + + "Expecting actual:%n" + " 1%n" + "to be less than:%n" + " 0 %n" + "at SoftAssertionsLineNumberTest.should_print_line_numbers_of_failed_assertions(SoftAssertionsLineNumberTest.java:37)%n")) .hasMessageContaining(format("%n" - + "Expecting:%n" + + "Expecting actual:%n" + " 1%n" + "to be less than:%n" + " 1 %n" @@ -63,7 +63,7 @@ void should_print_line_numbers_of_failed_assertions_even_if_it_came_from_nested_ Predicate lowercasePredicate = s -> s.equals(s.toLowerCase()); softly.assertThat(lowercasePredicate).accepts("a", "b", "C"); // WHEN - AssertionError error = catchThrowableOfType(softly::assertAll, AssertionError.class); + AssertionError error = expectAssertionError(softly::assertAll); // THEN assertThat(error).hasMessageContaining(format("%n" + "Expecting Optional to contain:%n" diff --git a/src/test/resources/ascii.txt b/src/test/resources/ascii.txt new file mode 100644 index 00000000000..f2ba8f84ab5 --- /dev/null +++ b/src/test/resources/ascii.txt @@ -0,0 +1 @@ +abc \ No newline at end of file diff --git a/verify.bndrun b/verify.bndrun index 40a347ff8d2..25ed1e2c75a 100644 --- a/verify.bndrun +++ b/verify.bndrun @@ -30,11 +30,11 @@ # The version ranges will change as the version of # AssertJ and/or its dependencies change. -runbundles: \ - assertj-core;version='[3.19.0,3.19.1)',\ - assertj-core-tests;version='[3.19.0,3.19.1)',\ - junit-jupiter-api;version='[5.6.3,5.6.4)',\ - junit-jupiter-engine;version='[5.6.3,5.6.4)',\ - junit-platform-commons;version='[1.6.3,1.6.4)',\ - junit-platform-engine;version='[1.6.3,1.6.4)',\ - junit-platform-launcher;version='[1.6.3,1.6.4)',\ + assertj-core;version='[3.19.1,3.19.2)',\ + assertj-core-tests;version='[3.19.1,3.19.2)',\ + junit-jupiter-api;version='[5.7.2,5.7.3)',\ + junit-jupiter-engine;version='[5.7.2,5.7.3)',\ + junit-platform-commons;version='[1.7.2,1.7.3)',\ + junit-platform-engine;version='[1.7.2,1.7.3)',\ + junit-platform-launcher;version='[1.7.2,1.7.3)',\ org.opentest4j;version='[1.2.0,1.2.1)'