Class Assertions

  • All Implemented Interfaces:
    InstanceOfAssertFactories
    Direct Known Subclasses:
    BDDAssertions

    public class Assertions
    extends Object
    implements InstanceOfAssertFactories
    Entry point for assertion methods for different types. Each method in this class is a static factory for a type-specific assertion object.

    For example:

     int removed = employees.removeFired();
     assertThat(removed).isZero();
    
     List<Employee> newEmployees = employees.hired(TODAY);
     assertThat(newEmployees).hasSize(6);

    This class only contains all assertThat methods, if you have ambiguous method compilation error, use either AssertionsForClassTypes or AssertionsForInterfaceTypes and if you need both, fully qualify you assertThat method.

    Java 8 is picky when choosing the right assertThat method if the object under test is generic and bounded, for example if foo is instance of T that extends Exception, java 8 will complain that it can't resolve the proper assertThat method (normally assertThat(Throwable) as foo might implement an interface like List, if that occurred assertThat(List) would also be a possible choice - thus confusing java 8.

    This why Assertions have been split in AssertionsForClassTypes and AssertionsForInterfaceTypes (see http://stackoverflow.com/questions/29499847/ambiguous-method-in-java-8-why).

    Author:
    Alex Ruiz, Yvonne Wang, David DIDIER, Ted Young, Joel Costigliola, Matthieu Baechler, Mikhail Mazursky, Nicolas François, Julien Meddah, William Bakker, William Delanoue
    • Constructor Detail

      • Assertions

        protected Assertions()
        Creates a new Assertions.
    • Method Detail

      • assertThat

        public static <T> PredicateAssert<T> assertThat​(Predicate<T> actual)
        Create assertion for Predicate.
        Type Parameters:
        T - the type of the value contained in the Predicate.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
        Since:
        3.5.0
      • assertThat

        public static <VALUE> OptionalAssert<VALUE> assertThat​(Optional<VALUE> actual)
        Create assertion for Optional.
        Type Parameters:
        VALUE - the type of the value contained in the Optional.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
      • assertThat

        public static AbstractUriAssert<?> assertThat​(URI actual)
        Creates a new instance of UriAssert.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
      • assertThat

        public static AbstractUrlAssert<?> assertThat​(URL actual)
        Creates a new instance of UrlAssert.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
      • assertThat

        public static AbstractBooleanAssert<?> assertThat​(boolean actual)
        Creates a new instance of BooleanAssert.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
      • assertThat

        public static AbstractByteAssert<?> assertThat​(byte actual)
        Creates a new instance of ByteAssert.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
      • assertThat

        public static AbstractByteAssert<?> assertThat​(Byte actual)
        Creates a new instance of ByteAssert.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
      • assertThat

        public static AbstractByteArrayAssert<?> assertThat​(byte[] actual)
        Creates a new instance of ByteArrayAssert.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
      • assertThat

        public static AbstractCharacterAssert<?> assertThat​(char actual)
        Creates a new instance of CharacterAssert.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
      • assertThat

        public static AbstractCharArrayAssert<?> assertThat​(char[] actual)
        Creates a new instance of CharArrayAssert.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
      • assertThat

        public static ClassAssert assertThat​(Class<?> actual)
        Creates a new instance of ClassAssert
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
      • assertThat

        public static AbstractDoubleAssert<?> assertThat​(double actual)
        Creates a new instance of DoubleAssert.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
      • assertThat

        public static AbstractDoubleAssert<?> assertThat​(Double actual)
        Creates a new instance of DoubleAssert.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
      • assertThat

        public static AbstractDoubleArrayAssert<?> assertThat​(double[] actual)
        Creates a new instance of DoubleArrayAssert.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
      • assertThat

        public static AbstractFileAssert<?> assertThat​(File actual)
        Creates a new instance of FileAssert.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
      • assertThat

        public static <RESULT> FutureAssert<RESULT> assertThat​(Future<RESULT> actual)
        Create assertion for Future.
        Type Parameters:
        RESULT - the type of the value contained in the Future.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
        Since:
        2.7.0 / 3.7.0
      • assertThat

        public static AbstractFloatAssert<?> assertThat​(float actual)
        Creates a new instance of FloatAssert.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
      • assertThat

        public static AbstractFloatAssert<?> assertThat​(Float actual)
        Creates a new instance of FloatAssert.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
      • assertThat

        public static AbstractFloatArrayAssert<?> assertThat​(float[] actual)
        Creates a new instance of FloatArrayAssert.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
      • assertThat

        public static AbstractIntegerAssert<?> assertThat​(int actual)
        Creates a new instance of IntegerAssert.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
      • assertThat

        public static AbstractIntArrayAssert<?> assertThat​(int[] actual)
        Creates a new instance of IntArrayAssert.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
      • assertThat

        public static <ACTUAL extends Iterable<? extends ELEMENT>,​ELEMENT,​ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT,​ELEMENT>> FactoryBasedNavigableIterableAssert<?,​ACTUAL,​ELEMENT,​ELEMENT_ASSERT> assertThat​(Iterable<? extends ELEMENT> actual,
                                                                                                                                                                                                                                                             AssertFactory<ELEMENT,​ELEMENT_ASSERT> assertFactory)
        Creates a new instance of FactoryBasedNavigableIterableAssert allowing to navigate to any Iterable element in order to perform assertions on it.

        Navigational methods provided:

        The available assertions after navigating to an element depend on the ELEMENT_ASSERT parameter of the given AssertFactory<ELEMENT, ELEMENT_ASSERT> (AssertJ can't figure it out because of Java type erasure).

        Example with String element assertions:

         Iterable<String> hobbits = newHashSet("frodo", "sam", "pippin");
        
         // build an AssertFactory for StringAssert (much nicer with Java 8 lambdas)
         AssertFactory<String, StringAssert> stringAssertFactory = new AssertFactory<String, StringAssert>() {
           @Override
           public StringAssert createAssert(String string) {
             return new StringAssert(string);
           }
         };
        
         // assertion succeeds with String assertions chained after first()
         assertThat(hobbits, stringAssertFactory).first()
                                                 .startsWith("fro")
                                                 .endsWith("do");
        Type Parameters:
        ACTUAL - The actual type
        ELEMENT - The actual elements type
        ELEMENT_ASSERT - The actual elements AbstractAssert type
        Parameters:
        actual - the actual value.
        assertFactory - the factory used to create the elements assert instance.
        Returns:
        the created assertion object.
        Since:
        2.5.0 / 3.5.0
      • assertThat

        public static <ACTUAL extends Iterable<? extends ELEMENT>,​ELEMENT,​ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT,​ELEMENT>> ClassBasedNavigableIterableAssert<?,​ACTUAL,​ELEMENT,​ELEMENT_ASSERT> assertThat​(ACTUAL actual,
                                                                                                                                                                                                                                                           Class<ELEMENT_ASSERT> assertClass)
        Creates a new instance of ClassBasedNavigableIterableAssert allowing to navigate to any Iterable element in order to perform assertions on it.

        Navigational methods provided:

        The available assertions after navigating to an element depend on the given assertClass (AssertJ can't find the element assert type by itself because of Java type erasure).

        Example with String element assertions:

         Iterable<String> hobbits = newHashSet("frodo", "sam", "pippin");
        
         // assertion succeeds with String assertions chained after first()
         assertThat(hobbits, StringAssert.class).first()
                                                .startsWith("fro")
                                                .endsWith("do");
        Type Parameters:
        ACTUAL - The actual type
        ELEMENT - The actual elements type
        ELEMENT_ASSERT - The actual elements AbstractAssert type
        Parameters:
        actual - the actual value.
        assertClass - the class used to create the elements assert instance.
        Returns:
        the created assertion object.
        Since:
        2.5.0 / 3.5.0
      • assertThat

        public static <ACTUAL extends List<? extends ELEMENT>,​ELEMENT,​ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT,​ELEMENT>> FactoryBasedNavigableListAssert<?,​ACTUAL,​ELEMENT,​ELEMENT_ASSERT> assertThat​(List<? extends ELEMENT> actual,
                                                                                                                                                                                                                                                     AssertFactory<ELEMENT,​ELEMENT_ASSERT> assertFactory)
        Creates a new instance of FactoryBasedNavigableListAssert allowing to navigate to any List element in order to perform assertions on it.

        Navigational methods provided:

        The available assertions after navigating to an element depend on the ELEMENT_ASSERT parameter of the given AssertFactory<ELEMENT, ELEMENT_ASSERT> (AssertJ can't figure it out because of Java type erasure).

        Example with String element assertions:

         List<String> hobbits = newArrayList("frodo", "sam", "pippin");
        
         // build an AssertFactory for StringAssert (much nicer with Java 8 lambdas)
         AssertFactory<String, StringAssert> stringAssertFactory = new AssertFactory<String, StringAssert>() {
           @Override
           public StringAssert createAssert(String string) {
             return new StringAssert(string);
           }
         };
        
         // assertion succeeds with String assertions chained after first()
         assertThat(hobbits, stringAssertFactory).first()
                                                 .startsWith("fro")
                                                 .endsWith("do");
        Type Parameters:
        ACTUAL - The actual type
        ELEMENT - The actual elements type
        ELEMENT_ASSERT - The actual elements AbstractAssert type
        Parameters:
        actual - the actual value.
        assertFactory - the factory used to create the elements assert instance.
        Returns:
        the created assertion object.
        Since:
        2.5.0 / 3.5.0
      • assertThat

        public static <ELEMENT,​ACTUAL extends List<? extends ELEMENT>,​ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT,​ELEMENT>> ClassBasedNavigableListAssert<?,​ACTUAL,​ELEMENT,​ELEMENT_ASSERT> assertThat​(List<? extends ELEMENT> actual,
                                                                                                                                                                                                                                                   Class<ELEMENT_ASSERT> assertClass)
        Creates a new instance of ClassBasedNavigableListAssert allowing to navigate to any List element in order to perform assertions on it.

        Navigational methods provided:

        The available assertions after navigating to an element depend on the given assertClass (AssertJ can't find the element assert type by itself because of Java type erasure).

        Example with String element assertions:

         List<String> hobbits = newArrayList("frodo", "sam", "pippin");
        
         // assertion succeeds with String assertions chained after first()
         assertThat(hobbits, StringAssert.class).first()
                                                .startsWith("fro")
                                                .endsWith("do");
        Type Parameters:
        ACTUAL - The actual type
        ELEMENT - The actual elements type
        ELEMENT_ASSERT - The actual elements AbstractAssert type
        Parameters:
        actual - the actual value.
        assertClass - the class used to create the elements assert instance.
        Returns:
        the created assertion object.
        Since:
        2.5.0 / 3.5.0
      • assertThat

        public static AbstractLongAssert<?> assertThat​(long actual)
        Creates a new instance of LongAssert.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
      • assertThat

        public static AbstractLongAssert<?> assertThat​(Long actual)
        Creates a new instance of LongAssert.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
      • assertThat

        public static AbstractLongArrayAssert<?> assertThat​(long[] actual)
        Creates a new instance of LongArrayAssert.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
      • assertThat

        public static <T> ObjectAssert<T> assertThat​(T actual)
        Creates a new instance of ObjectAssert.
        Type Parameters:
        T - the type of the actual value.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
      • assertThat

        public static <T> ObjectArrayAssert<T> assertThat​(T[] actual)
        Creates a new instance of ObjectArrayAssert.
        Type Parameters:
        T - the actual's elements type.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
      • assertThat

        public static AbstractShortAssert<?> assertThat​(short actual)
        Creates a new instance of ShortAssert.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
      • assertThat

        public static AbstractShortAssert<?> assertThat​(Short actual)
        Creates a new instance of ShortAssert.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
      • assertThat

        public static AbstractShortArrayAssert<?> assertThat​(short[] actual)
        Creates a new instance of ShortArrayAssert.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
      • assertThat

        public static AbstractDateAssert<?> assertThat​(Date actual)
        Creates a new instance of DateAssert.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
      • assertThat

        public static AbstractInstantAssert<?> assertThat​(Instant actual)
        Creates a new instance of InstantAssert.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
        Since:
        3.7.0
      • assertThat

        public static AtomicLongAssert assertThat​(AtomicLong actual)
        Create assertion for AtomicLong.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
        Since:
        2.7.0 / 3.7.0
      • assertThat

        public static <VALUE> AtomicReferenceAssert<VALUE> assertThat​(AtomicReference<VALUE> actual)
        Create assertion for AtomicReference.
        Type Parameters:
        VALUE - the type of the value contained in the AtomicReference.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
        Since:
        2.7.0 / 3.7.0
      • assertThatThrownBy

        public static AbstractThrowableAssert<?,​? extends Throwable> assertThatThrownBy​(ThrowableAssert.ThrowingCallable shouldRaiseThrowable)
        Allows to capture and then assert on a Throwable (easier done with lambdas).

        Java 8 example :

         @Test
          public void testException() {
            assertThatThrownBy(() -> { throw new Exception("boom!"); }).isInstanceOf(Exception.class)
                                                                       .hasMessageContaining("boom");
         }
        If the provided ThrowableAssert.ThrowingCallable does not raise an exception, an error is immediately thrown, in that case the test description provided with as(String, Object...) is not honored.
        To use a test description, use catchThrowable(ThrowableAssert.ThrowingCallable) as shown below:
         // assertion will fail but "display me" won't appear in the error
         assertThatThrownBy(() -> {}).as("display me")
                                     .isInstanceOf(Exception.class);
        
         // assertion will fail AND "display me" will appear in the error
         Throwable thrown = catchThrowable(() -> {});
         assertThat(thrown).as("display me")
                           .isInstanceOf(Exception.class);
        Alternatively you can also use assertThatCode(ThrowingCallable) for the test description provided with as(String, Object...) to always be honored.
        Parameters:
        shouldRaiseThrowable - The ThrowableAssert.ThrowingCallable or lambda with the code that should raise the throwable.
        Returns:
        the created ThrowableAssert.
      • assertThatThrownBy

        public static AbstractThrowableAssert<?,​? extends Throwable> assertThatThrownBy​(ThrowableAssert.ThrowingCallable shouldRaiseThrowable,
                                                                                              String description,
                                                                                              Object... args)
        Allows to capture and then assert on a Throwable like assertThatThrownBy(ThrowingCallable) but this method let you set the assertion description the same way you do with as(String, Object...).

        Example:

         @Test
          public void testException() {
            // if this assertion failed (but it doesn't), the error message would start with [Test explosive code]
            assertThatThrownBy(() -> { throw new IOException("boom!"); }, "Test explosive code")
                     .isInstanceOf(IOException.class)
                     .hasMessageContaining("boom");
         }
        If the provided ThrowingCallable does not raise an exception, an error is immediately thrown.

        The test description provided is honored but not the one with as(String, Object...), example:

         // assertion will fail but "display me" won't appear in the error message
         assertThatThrownBy(() -> {}).as("display me")
                                     .isInstanceOf(Exception.class);
        
         // assertion will fail AND "display me" will appear in the error message
         assertThatThrownBy(() -> {}, "display me")
                                     .isInstanceOf(Exception.class);
        Parameters:
        shouldRaiseThrowable - The ThrowableAssert.ThrowingCallable or lambda with the code that should raise the throwable.
        description - the new description to set.
        args - optional parameter if description is a format String.
        Returns:
        the created ThrowableAssert.
        Since:
        3.9.0
      • assertThatCode

        public static AbstractThrowableAssert<?,​? extends Throwable> assertThatCode​(ThrowableAssert.ThrowingCallable shouldRaiseOrNotThrowable)
        Allows to capture and then assert on a Throwable (easier done with lambdas).

        The main difference with assertThatThrownBy(ThrowingCallable) is that this method does not fail if no exception was thrown.

        Example :

         ThrowingCallable boomCode = () -> {
           throw new Exception("boom!");
         };
         ThrowingCallable doNothing = () -> {};
        
         // assertions succeed
         assertThatCode(doNothing).doesNotThrowAnyException();
         assertThatCode(boomCode).isInstanceOf(Exception.class)
                                 .hasMessageContaining("boom");
        
         // assertion fails
         assertThatCode(boomCode).doesNotThrowAnyException();
        Contrary to assertThatThrownBy(ThrowingCallable) the test description provided with as(String, Object...) is always honored as shown below.
         ThrowingCallable doNothing = () -> {};
        
         // assertion fails and "display me" appears in the assertion error
         assertThatCode(doNothing).as("display me")
                                  .isInstanceOf(Exception.class);

        This method was not named assertThat because the java compiler reported it ambiguous when used directly with a lambda :(

        Parameters:
        shouldRaiseOrNotThrowable - The ThrowableAssert.ThrowingCallable or lambda with the code that should raise the throwable.
        Returns:
        the created ThrowableAssert.
        Since:
        3.7.0
      • assertThatObject

        public static <T> ObjectAssert<T> assertThatObject​(T actual)
        Creates a new instance of ObjectAssert for any object.

        This overload is useful, when an overloaded method of assertThat(...) takes precedence over the generic assertThat(Object).

        Example:

        Cast necessary because assertThat(List) "forgets" actual type:
        assertThat(new LinkedList<>(asList("abc"))).matches(list -> ((Deque<String>) list).getFirst().equals("abc")); 
        No cast needed, but also no additional list assertions:
        assertThatObject(new LinkedList<>(asList("abc"))).matches(list -> list.getFirst().equals("abc")); 
        Type Parameters:
        T - the type of the actual value.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
        Since:
        3.12.0
      • catchThrowableOfType

        public static <THROWABLE extends Throwable> THROWABLE catchThrowableOfType​(ThrowableAssert.ThrowingCallable shouldRaiseThrowable,
                                                                                   Class<THROWABLE> type)
        Allows catching a Throwable of a specific type.

        A call is made to catchThrowable(ThrowingCallable), if no exception is thrown it returns null otherwise it checks that the caught 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);
        Type Parameters:
        THROWABLE - the Throwable type.
        Parameters:
        shouldRaiseThrowable - The lambda with the code that should raise the exception.
        type - The type of exception that the code is expected to raise.
        Returns:
        The captured exception or null if none was raised by the callable.
        Since:
        3.9.0
        See Also:
        catchThrowable(ThrowableAssert.ThrowingCallable)
      • assertThatExceptionOfType

        public static <T extends ThrowableThrowableTypeAssert<T> assertThatExceptionOfType​(Class<? extends T> exceptionType)
        Entry point to check that an exception of type T is thrown by a given throwingCallable which allows to chain assertions on the thrown exception.

        Example:

         assertThatExceptionOfType(IOException.class)
                   .isThrownBy(() -> { throw new IOException("boom!"); })
                   .withMessage("boom!"); 
        This method is more or less the same of assertThatThrownBy(ThrowableAssert.ThrowingCallable) but in a more natural way.
        Type Parameters:
        T - the exception type.
        Parameters:
        exceptionType - the exception type class.
        Returns:
        the created ThrowableTypeAssert.
      • setRemoveAssertJRelatedElementsFromStackTrace

        public static void setRemoveAssertJRelatedElementsFromStackTrace​(boolean removeAssertJRelatedElementsFromStackTrace)
        Sets whether we remove elements related to AssertJ from assertion error stack trace.

        Default is true.

        Parameters:
        removeAssertJRelatedElementsFromStackTrace - flag.
      • fail

        public static <T> T fail​(String failureMessage)
        Throws an AssertionError with the given message.
        Type Parameters:
        T - dummy return value type
        Parameters:
        failureMessage - error message.
        Returns:
        nothing, it's just to be used in doSomething(optional.orElse(() -> fail("boom")));.
        Throws:
        AssertionError - with the given message.
      • fail

        public static <T> T fail​(String failureMessage,
                                 Object... args)
        Throws an AssertionError with the given message built as String.format(String, Object...).
        Type Parameters:
        T - dummy return value type
        Parameters:
        failureMessage - error message.
        args - Arguments referenced by the format specifiers in the format string.
        Returns:
        nothing, it's just to be used in doSomething(optional.orElse(() -> fail("b%s", ""oom)));.
        Throws:
        AssertionError - with the given built message.
      • fail

        public static <T> T fail​(String failureMessage,
                                 Throwable realCause)
        Throws an AssertionError with the given message and with the Throwable that caused the failure.
        Type Parameters:
        T - dummy return value type
        Parameters:
        failureMessage - the description of the failed assertion. It can be null.
        realCause - cause of the error.
        Returns:
        nothing, it's just to be used in doSomething(optional.orElse(() -> fail("boom", cause)));.
        Throws:
        AssertionError - with the given message and with the Throwable that caused the failure.
      • failBecauseExceptionWasNotThrown

        public static <T> T failBecauseExceptionWasNotThrown​(Class<? extends Throwable> throwableClass)
        Throws an AssertionError with a message explaining that a Throwable of given class was expected to be thrown but had not been.

        shouldHaveThrown(Class) can be used as a replacement.

        Type Parameters:
        T - dummy return value type
        Parameters:
        throwableClass - the Throwable class that was expected to be thrown.
        Returns:
        nothing, it's just to be used in doSomething(optional.orElse(() -> failBecauseExceptionWasNotThrown(IOException.class)));.
        Throws:
        AssertionError - with a message explaining that a Throwable of given class was expected to be thrown but had not been.
      • shouldHaveThrown

        public static <T> T shouldHaveThrown​(Class<? extends Throwable> throwableClass)
        Throws an AssertionError with a message explaining that a Throwable of given class was expected to be thrown but had not been.
        Type Parameters:
        T - dummy return value type
        Parameters:
        throwableClass - the Throwable class that was expected to be thrown.
        Returns:
        nothing, it's just to be used in doSomething(optional.orElse(() -> shouldHaveThrown(IOException.class)));.
        Throws:
        AssertionError - with a message explaining that a Throwable of given class was expected to be thrown but had not been.
      • setMaxLengthForSingleLineDescription

        public static void setMaxLengthForSingleLineDescription​(int maxLengthForSingleLineDescription)
        In error messages, sets the threshold when iterable/array formatting will be on one line (if their String description is less than this parameter) or it will be formatted with one element per line.

        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)"]
        Parameters:
        maxLengthForSingleLineDescription - the maximum length for an iterable/array to be displayed on one line
      • setMaxElementsForPrinting

        public static void setMaxElementsForPrinting​(int maxElementsForPrinting)
        In error messages, sets the threshold for how many elements from one iterable/array/map will be included in the in the description. E.q. When this method is called with a value of 3.

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

         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 only with it's first 3 elements, followed by ...:
         String[] greatBooks = array("A Game of Thrones", "The Lord of the Rings", "Assassin's Apprentice", "Guards! Guards!");
        
         // formatted as:
        
         ["A Game of Thrones", "The Lord of the Rings", "Assassin's Apprentice", ...]
        Parameters:
        maxElementsForPrinting - the maximum elements that would be printed from one iterable/array/map
        Since:
        2.6.0 / 3.6.0
      • extractProperty

        public static <T> Properties<T> extractProperty​(String propertyName,
                                                        Class<T> propertyType)
        Only delegate to Properties.extractProperty(String) so that Assertions offers a full feature entry point to all AssertJ features (but you can use 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");
        Type Parameters:
        T - the type of value to extract.
        Parameters:
        propertyName - the name of the property to be read from the elements of a Iterable. It may be a nested property (e.g. "address.street.number").
        propertyType - the type of property to extract
        Returns:
        the created Properties.
        Throws:
        NullPointerException - if the given property name is null.
        IllegalArgumentException - if the given property name is empty.
      • extractProperty

        public static Properties<Object> extractProperty​(String propertyName)
        Only delegate to Properties.extractProperty(String) so that Assertions offers a full feature entry point to all AssertJ features (but you can use 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"); 
        Parameters:
        propertyName - the name of the property to be read from the elements of a Iterable. It may be a nested property (e.g. "address.street.number").
        Returns:
        the created Properties.
        Throws:
        NullPointerException - if the given property name is null.
        IllegalArgumentException - if the given property name is empty.
      • setAllowExtractingPrivateFields

        public static void setAllowExtractingPrivateFields​(boolean allowExtractingPrivateFields)
        Globally sets whether IterableAssert#extracting(String) and ObjectArrayAssert#extracting(String) should be allowed to extract private fields, if not and they try it fails with exception.
        Parameters:
        allowExtractingPrivateFields - allow private fields extraction. Default is true.
      • setExtractBareNamePropertyMethods

        public static void setExtractBareNamePropertyMethods​(boolean barenamePropertyMethods)
        Globally sets whether the extractor considers bare-named property methods like String name(). Defaults to enabled.
        Parameters:
        barenamePropertyMethods - whether bare-named property methods are found
      • entry

        public static <K,​V> MapEntry<K,​V> entry​(K key,
                                                            V value)
        Only delegate to MapEntry.entry(Object, Object) so that Assertions offers a full feature entry point to all AssertJ features (but you can use 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));
        Type Parameters:
        K - the type of keys in the map.
        V - the type of values in the map.
        Parameters:
        key - the key of the entry to create.
        value - the value of the entry to create.
        Returns:
        the created MapEntry.
      • atIndex

        public static Index atIndex​(int index)
        Only delegate to Index.atIndex(int) so that Assertions offers a full feature entry point to all AssertJ features (but you can use 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));
        Parameters:
        index - the value of the index.
        Returns:
        the created Index.
        Throws:
        IllegalArgumentException - if the given value is negative.
      • offset

        public static Offset<Double> offset​(Double value)
        Assertions entry point for double Offset.

        Typical usage :

         assertThat(0.1).isEqualTo(0.0, offset(0.1));
        Parameters:
        value - the allowed offset
        Returns:
        the created Offset.
        Throws:
        NullPointerException - if the given value is null.
        IllegalArgumentException - if the given value is negative.
      • offset

        public static Offset<Float> offset​(Float value)
        Assertions entry point for float Offset.

        Typical usage :

         assertThat(0.2f).isCloseTo(0.0f, offset(0.2f));
        Parameters:
        value - the allowed offset
        Returns:
        the created Offset.
        Throws:
        NullPointerException - if the given value is null.
        IllegalArgumentException - if the given value is negative.
      • withPrecision

        public static Offset<Double> withPrecision​(Double value)
        Alias for offset(Double) to use with real number assertions.

        Typical usage :

         assertThat(0.1).isEqualTo(0.0, withPrecision(0.1));
        Parameters:
        value - the required precision
        Returns:
        the created Offset.
        Throws:
        NullPointerException - if the given value is null.
        IllegalArgumentException - if the given value is negative.
      • within

        public static Offset<Float> within​(Float value)
        Alias for offset(Float) to use with isCloseTo assertions.

        Typical usage :

         assertThat(8.2f).isCloseTo(8.0f, within(0.2f));
        Parameters:
        value - the allowed offset
        Returns:
        the created Offset.
        Throws:
        NullPointerException - if the given value is null.
        IllegalArgumentException - if the given value is negative.
      • withPrecision

        public static Offset<Float> withPrecision​(Float value)
        Alias for offset(Float) to use with real number assertions.

        Typical usage :

         assertThat(0.2f).isEqualTo(0.0f, withPrecision(0.2f));
        Parameters:
        value - the required precision
        Returns:
        the created Offset.
        Throws:
        NullPointerException - if the given value is null.
        IllegalArgumentException - if the given value is negative.
      • within

        public static Offset<BigDecimal> within​(BigDecimal value)
        Assertions entry point for BigDecimal Offset to use with isCloseTo assertions.

        Typical usage :

         assertThat(BigDecimal.TEN).isCloseTo(new BigDecimal("10.5"), within(BigDecimal.ONE));
        Parameters:
        value - the allowed offset
        Returns:
        the created Offset.
        Throws:
        NullPointerException - if the given value is null.
        IllegalArgumentException - if the given value is negative.
      • within

        public static Offset<BigInteger> within​(BigInteger value)
        Assertions entry point for BigInteger Offset to use with isCloseTo assertions.

        Typical usage :

         assertThat(BigInteger.TEN).isCloseTo(new BigInteger("11"), within(new BigInteger("2")));
        Parameters:
        value - the allowed offset
        Returns:
        the created Offset.
        Throws:
        NullPointerException - if the given value is null.
        IllegalArgumentException - if the given value is negative.
        Since:
        2.7.0 / 3.7.0, 2.7.0 / 3.7.0
      • within

        public static Offset<Byte> within​(Byte value)
        Assertions entry point for Byte Offset to use with isCloseTo assertions.

        Typical usage :

         assertThat((byte) 10).isCloseTo((byte) 11, within((byte) 1));
        Parameters:
        value - the value of the offset.
        Returns:
        the created Offset.
        Throws:
        NullPointerException - if the given value is null.
        IllegalArgumentException - if the given value is negative.
      • within

        public static Offset<Integer> within​(Integer value)
        Assertions entry point for Integer Offset to use with isCloseTo assertions.

        Typical usage :

         assertThat(10).isCloseTo(11, within(1));
        Parameters:
        value - the value of the offset.
        Returns:
        the created Offset.
        Throws:
        NullPointerException - if the given value is null.
        IllegalArgumentException - if the given value is negative.
      • within

        public static Offset<Short> within​(Short value)
        Assertions entry point for Short Offset to use with isCloseTo assertions.

        Typical usage :

         assertThat(10).isCloseTo(11, within(1));
        Parameters:
        value - the allowed offset
        Returns:
        the created Offset.
        Throws:
        NullPointerException - if the given value is null.
        IllegalArgumentException - if the given value is negative.
      • within

        public static Offset<Long> within​(Long value)
        Assertions entry point for Long Offset to use with isCloseTo assertions.

        Typical usage :

         assertThat(5l).isCloseTo(7l, within(2l));
        Parameters:
        value - the allowed offset
        Returns:
        the created Offset.
        Throws:
        NullPointerException - if the given value is null.
        IllegalArgumentException - if the given value is negative.
      • within

        public static TemporalUnitOffset within​(long value,
                                                TemporalUnit unit)
        Assertions entry point for 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));
        Parameters:
        value - the allowed offset
        unit - the TemporalUnit of the offset
        Returns:
        the created Offset.
        Since:
        3.7.0
      • withinPercentage

        public static Percentage withinPercentage​(Double value)
        Assertions entry point for Double Percentage to use with isCloseTo assertions for percentages.

        Typical usage :

         assertThat(11.0).isCloseTo(10.0, withinPercentage(10.0));
        Parameters:
        value - the required precision percentage
        Returns:
        the created Percentage.
        Throws:
        NullPointerException - if the given value is null.
        IllegalArgumentException - if the given value is negative.
      • withinPercentage

        public static Percentage withinPercentage​(Integer value)
        Assertions entry point for Integer Percentage to use with isCloseTo assertions for percentages.

        Typical usage :

         assertThat(11).isCloseTo(10, withinPercentage(10));
        Parameters:
        value - the required precision percentage
        Returns:
        the created Percentage.
        Throws:
        NullPointerException - if the given value is null.
        IllegalArgumentException - if the given value is negative.
      • withinPercentage

        public static Percentage withinPercentage​(Long value)
        Assertions entry point for Long Percentage to use with isCloseTo assertions for percentages.

        Typical usage :

         assertThat(11L).isCloseTo(10L, withinPercentage(10L));
        Parameters:
        value - the required precision percentage
        Returns:
        the created Percentage.
        Throws:
        NullPointerException - if the given value is null.
        IllegalArgumentException - if the given value is negative.
      • byLessThan

        public static Offset<Float> byLessThan​(Float value)
        Alias for offset(Float) to use with isCloseTo assertions.

        Typical usage :

         assertThat(8.2f).isCloseTo(8.0f, byLessThan(0.5f));
        Parameters:
        value - the value of the offset.
        Returns:
        the created Offset.
        Throws:
        NullPointerException - if the given value is null.
        IllegalArgumentException - if the given value is negative.
      • byLessThan

        public static Offset<BigDecimal> byLessThan​(BigDecimal value)
        Assertions entry point for BigDecimal Offset to use with isCloseTo assertions.

        Typical usage :

         assertThat(BigDecimal.TEN).isCloseTo(new BigDecimal("10.5"), byLessThan(BigDecimal.ONE));
        Parameters:
        value - the value of the offset.
        Returns:
        the created Offset.
        Throws:
        NullPointerException - if the given value is null.
        IllegalArgumentException - if the given value is negative.
      • byLessThan

        public static Offset<BigInteger> byLessThan​(BigInteger value)
        Assertions entry point for BigInteger Offset to use with isCloseTo assertions.

        Typical usage :

         assertThat(BigInteger.TEN).isCloseTo(new BigInteger("11"), byLessThan(new BigInteger("2")));
        Parameters:
        value - the value of the offset.
        Returns:
        the created Offset.
        Throws:
        NullPointerException - if the given value is null.
        IllegalArgumentException - if the given value is negative.
        Since:
        2.7.0 / 3.7.0
      • byLessThan

        public static Offset<Byte> byLessThan​(Byte value)
        Assertions entry point for Byte Offset to use with isCloseTo assertions.

        Typical usage :

         assertThat((byte) 10).isCloseTo((byte) 11, byLessThan((byte) 2));
        Parameters:
        value - the value of the offset.
        Returns:
        the created Offset.
        Throws:
        NullPointerException - if the given value is null.
        IllegalArgumentException - if the given value is negative.
      • byLessThan

        public static Offset<Integer> byLessThan​(Integer value)
        Assertions entry point for Long Offset to use with strict isCloseTo assertions.

        Typical usage :

         assertThat(10).isCloseTo(12, byLessThan(1));
        Parameters:
        value - the value of the offset.
        Returns:
        the created Offset.
        Throws:
        NullPointerException - if the given value is null.
        IllegalArgumentException - if the given value is negative.
      • byLessThan

        public static Offset<Short> byLessThan​(Short value)
        Assertions entry point for Short Offset to use with isCloseTo assertions.

        Typical usage :

         assertThat((short) 10).isCloseTo((short) 11, byLessThan((short) 2));
        Parameters:
        value - the value of the offset.
        Returns:
        the created Offset.
        Throws:
        NullPointerException - if the given value is null.
        IllegalArgumentException - if the given value is negative.
      • byLessThan

        public static Offset<Long> byLessThan​(Long value)
        Assertions entry point for Long Offset to use with strict isCloseTo assertions.

        Typical usage :

         assertThat(5l).isCloseTo(7l, byLessThan(3l));
        Parameters:
        value - the value of the offset.
        Returns:
        the created Offset.
        Throws:
        NullPointerException - if the given value is null.
        IllegalArgumentException - if the given value is negative.
      • byLessThan

        public static TemporalUnitOffset byLessThan​(long value,
                                                    TemporalUnit unit)
        Assertions entry point for TemporalUnitOffset with strict less than 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, byLessThan(5, ChronoUnit.MINUTES));
        Parameters:
        value - the value of the offset.
        unit - the TemporalUnit of the offset.
        Returns:
        the created Offset.
        Since:
        3.7.0
      • from

        public static <F,​T> Function<F,​T> from​(Function<F,​T> extractor)
        A syntax sugar to write fluent assertion using AbstractObjectAssert.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)); 
        Type Parameters:
        F - Type of test subject
        T - Type of the property under the assertion
        Parameters:
        extractor - A function to extract test subject's property
        Returns:
        same instance of extractor
      • allOf

        @SafeVarargs
        public static <T> Condition<T> allOf​(Condition<? super T>... conditions)
        Creates a new AllOf
        Type Parameters:
        T - the type of object the given condition accept.
        Parameters:
        conditions - the conditions to evaluate.
        Returns:
        the created AllOf.
        Throws:
        NullPointerException - if the given array is null.
        NullPointerException - if any of the elements in the given array is null.
      • allOf

        public static <T> Condition<T> allOf​(Iterable<? extends Condition<? super T>> conditions)
        Creates a new AllOf
        Type Parameters:
        T - the type of object the given condition accept.
        Parameters:
        conditions - the conditions to evaluate.
        Returns:
        the created AllOf.
        Throws:
        NullPointerException - if the given iterable is null.
        NullPointerException - if any of the elements in the given iterable is null.
      • anyOf

        @SafeVarargs
        public static <T> Condition<T> anyOf​(Condition<? super T>... conditions)
        Only delegate to AnyOf.anyOf(Condition...) so that Assertions offers a full feature entry point to all AssertJ features (but you can use AnyOf if you prefer).

        Typical usage (jedi and sith are Condition) :

         assertThat("Vader").is(anyOf(jedi, sith));
        Type Parameters:
        T - the type of object the given condition accept.
        Parameters:
        conditions - the conditions to evaluate.
        Returns:
        the created AnyOf.
      • anyOf

        public static <T> Condition<T> anyOf​(Iterable<? extends Condition<? super T>> conditions)
        Creates a new AnyOf
        Type Parameters:
        T - the type of object the given condition accept.
        Parameters:
        conditions - the conditions to evaluate.
        Returns:
        the created AnyOf.
        Throws:
        NullPointerException - if the given iterable is null.
        NullPointerException - if any of the elements in the given iterable is null.
      • doesNotHave

        public static <T> DoesNotHave<T> doesNotHave​(Condition<? super T> condition)
        Creates a new DoesNotHave.
        Type Parameters:
        T - the type of object the given condition accept.
        Parameters:
        condition - the condition to inverse.
        Returns:
        The DoesNotHave condition created.
      • not

        public static <T> Not<T> not​(Condition<? super T> condition)
        Creates a new Not.
        Type Parameters:
        T - the type of object the given condition accept.
        Parameters:
        condition - the condition to inverse.
        Returns:
        The Not condition created.
      • filter

        public static <E> Filters<E> filter​(E[] array)
        Only delegate to Filters.filter(Object[]) so that Assertions offers a full feature entry point to all AssertJ features (but you can use Filters if you prefer).

        Note that the given array is not modified, the filters are performed on an Iterable copy of the array.

        Typical usage with Condition :

         assertThat(filter(players).being(potentialMVP).get()).containsOnly(james, rose);

        and with filter language based on java bean property :

         assertThat(filter(players).with("pointsPerGame").greaterThan(20).and("assistsPerGame").greaterThan(7).get())
                   .containsOnly(james, rose);
        Type Parameters:
        E - the array elements type.
        Parameters:
        array - the array to filter.
        Returns:
        the created Filters.
      • filter

        public static <E> Filters<E> filter​(Iterable<E> iterableToFilter)
        Only delegate to Filters.filter(Object[]) so that Assertions offers a full feature entry point to all AssertJ features (but you can use Filters if you prefer).

        Note that the given Iterable is not modified, the filters are performed on a copy.

        Typical usage with Condition :

         assertThat(filter(players).being(potentialMVP).get()).containsOnly(james, rose);

        and with filter language based on java bean property :

         assertThat(filter(players).with("pointsPerGame").greaterThan(20)
                                   .and("assistsPerGame").greaterThan(7).get())
                   .containsOnly(james, rose);
        Type Parameters:
        E - the Iterable elements type.
        Parameters:
        iterableToFilter - the Iterable to filter.
        Returns:
        the created Filters.
      • in

        public static InFilter in​(Object... values)
        Create a FilterOperator to use in 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);
        Parameters:
        values - values to match (one match is sufficient)
        Returns:
        the created "in" filter
      • notIn

        public static NotInFilter notIn​(Object... valuesNotToMatch)
        Create a FilterOperator to use in 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);
        Parameters:
        valuesNotToMatch - values not to match (none of the values must match)
        Returns:
        the created "not in" filter
      • not

        public static NotFilter not​(Object valueNotToMatch)
        Create a FilterOperator to use in 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);
        Parameters:
        valueNotToMatch - the value not to match
        Returns:
        the created "not" filter
      • contentOf

        public static String contentOf​(File file,
                                       Charset charset)
        Loads the text content of a file, so that it can be passed to assertThat(String).

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

        Parameters:
        file - the file.
        charset - the character set to use.
        Returns:
        the content of the file.
        Throws:
        NullPointerException - if the given charset is null.
        UncheckedIOException - if an I/O exception occurs.
      • contentOf

        public static String contentOf​(File file,
                                       String charsetName)
        Loads the text content of a file, so that it can be passed to assertThat(String).

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

        Parameters:
        file - the file.
        charsetName - the name of the character set to use.
        Returns:
        the content of the file.
        Throws:
        IllegalArgumentException - if the given character set is not supported on this platform.
        UncheckedIOException - if an I/O exception occurs.
      • contentOf

        public static String contentOf​(File file)
        Loads the text content of a file with the default character set, so that it can be passed to assertThat(String).

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

        Parameters:
        file - the file.
        Returns:
        the content of the file.
        Throws:
        UncheckedIOException - if an I/O exception occurs.
      • linesOf

        public static List<String> linesOf​(File file)
        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.
        Parameters:
        file - the file.
        Returns:
        the content of the file.
        Throws:
        NullPointerException - if the given charset is null.
        UncheckedIOException - if an I/O exception occurs.
      • linesOf

        public static List<String> linesOf​(File file,
                                           Charset 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.
        Parameters:
        file - the file.
        charset - the character set to use.
        Returns:
        the content of the file.
        Throws:
        NullPointerException - if the given charset is null.
        UncheckedIOException - if an I/O exception occurs.
      • linesOf

        public static List<String> linesOf​(File file,
                                           String charsetName)
        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.
        Parameters:
        file - the file.
        charsetName - the name of the character set to use.
        Returns:
        the content of the file.
        Throws:
        NullPointerException - if the given charset is null.
        UncheckedIOException - if an I/O exception occurs.
      • contentOf

        public static String contentOf​(URL url,
                                       Charset charset)
        Loads the text content of a URL, so that it can be passed to assertThat(String).

        Note that this will load the entire contents in memory.

        Parameters:
        url - the URL.
        charset - the character set to use.
        Returns:
        the content of the URL.
        Throws:
        NullPointerException - if the given charset is null.
        UncheckedIOException - if an I/O exception occurs.
      • contentOf

        public static String contentOf​(URL url,
                                       String charsetName)
        Loads the text content of a URL, so that it can be passed to assertThat(String).

        Note that this will load the entire contents in memory.

        Parameters:
        url - the URL.
        charsetName - the name of the character set to use.
        Returns:
        the content of the URL.
        Throws:
        IllegalArgumentException - if the given character set is not supported on this platform.
        UncheckedIOException - if an I/O exception occurs.
      • contentOf

        public static String contentOf​(URL url)
        Loads the text content of a URL with the default character set, so that it can be passed to assertThat(String).

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

        Parameters:
        url - the URL.
        Returns:
        the content of the file.
        Throws:
        UncheckedIOException - if an I/O exception occurs.
      • linesOf

        public static List<String> linesOf​(URL url)
        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.
        Parameters:
        url - the URL.
        Returns:
        the content of the file.
        Throws:
        NullPointerException - if the given charset is null.
        UncheckedIOException - if an I/O exception occurs.
      • linesOf

        public static List<String> linesOf​(URL url,
                                           Charset 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.
        Parameters:
        url - the URL.
        charset - the character set to use.
        Returns:
        the content of the file.
        Throws:
        NullPointerException - if the given charset is null.
        UncheckedIOException - if an I/O exception occurs.
      • linesOf

        public static List<String> linesOf​(URL url,
                                           String charsetName)
        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.
        Parameters:
        url - the URL.
        charsetName - the name of the character set to use.
        Returns:
        the content of the file.
        Throws:
        NullPointerException - if the given charset is null.
        UncheckedIOException - if an I/O exception occurs.
      • setLenientDateParsing

        public static void setLenientDateParsing​(boolean value)
        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 setLenientDateParsing(false).
        Parameters:
        value - whether lenient parsing mode should be enabled or not
      • registerCustomDateFormat

        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 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 :

        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 useDefaultDateFormatsOnly() or 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");
        Parameters:
        userCustomDateFormat - the new Date format used for String based Date assertions.
      • registerCustomDateFormat

        public static void registerCustomDateFormat​(String userCustomDateFormatPattern)
        Add the given date format to the ones used to parse date String in String based Date assertions like 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 :

        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 useDefaultDateFormatsOnly() or 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");
        Parameters:
        userCustomDateFormatPattern - the new Date format pattern used for String based Date assertions.
      • useDefaultDateFormatsOnly

        public static void useDefaultDateFormatsOnly()
        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 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
      • assertThat

        public static <T> T assertThat​(AssertProvider<T> component)
        Delegates the creation of the Assert to the AssertProvider.assertThat() of the given component.

        Read the comments on AssertProvider for an example of its usage.

        Type Parameters:
        T - the AssertProvider wrapped type.
        Parameters:
        component - the component that creates its own assert
        Returns:
        the associated Assert of the given component
      • assertThat

        public static <ELEMENT> IterableAssert<ELEMENT> assertThat​(Iterable<? extends ELEMENT> actual)
        Creates a new instance of IterableAssert.
        Type Parameters:
        ELEMENT - the type of elements.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
      • assertThat

        public static <ELEMENT> IteratorAssert<ELEMENT> assertThat​(Iterator<? extends ELEMENT> actual)
        Creates a new instance of IteratorAssert.

        Breaking change in version 3.12.0: this method does not return anymore an IterableAssert but an IteratorAssert.
        In order to access assertions from IterableAssert, use AbstractIteratorAssert.toIterable().

        IteratorAssert instances have limited assertions because it does not consume iterator's elements.

        Examples:

         Iterator<String> bestBasketBallPlayers = getBestBasketBallPlayers();
        
         assertThat(bestBasketBallPlayers).hasNext() // Iterator assertion
                                          .toIterable() // switch to Iterable assertions
                                          .contains("Jordan", "Magic", "Lebron"); // Iterable assertion 
        Type Parameters:
        ELEMENT - the type of elements.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
      • assertThat

        public static <ELEMENT> ListAssert<ELEMENT> assertThat​(List<? extends ELEMENT> actual)
        Creates a new instance of ListAssert.
        Type Parameters:
        ELEMENT - the type of elements.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
      • assertThat

        public static <ELEMENT> ListAssert<ELEMENT> assertThat​(Stream<? extends ELEMENT> actual)
        Creates a new instance of ListAssert from the given Stream.

        Be aware that the Stream under test will be converted to a List when an assertion requires to inspect its content. Once this is done the Stream can't be reused as it has already been consumed.

        Calling multiple methods on the returned ListAssert is safe as it only interacts with the List built from the Stream.

        Examples:

         // you can chain multiple assertions on the Stream as it is converted to a List
         assertThat(Stream.of(1, 2, 3)).contains(1)
                                       .doesNotContain(42);

        The following assertion fails as the Stream under test is converted to a List before being compared to the expected Stream:

         // FAIL: the Stream under test is converted to a List and compared to a Stream but a List is not a Stream.
         assertThat(Stream.of(1, 2, 3)).isEqualTo(Stream.of(1, 2, 3));

        These assertions succeed as isEqualTo and isSameAs checks references which does not require to convert the Stream to a List.

         // The following assertions succeed as it only performs reference checking which does not require to convert the Stream to a List
         Stream<Integer> stream = Stream.of(1, 2, 3);
         assertThat(stream).isEqualTo(stream)
                           .isSameAs(stream);
        Type Parameters:
        ELEMENT - the type of elements.
        Parameters:
        actual - the actual Stream value.
        Returns:
        the created assertion object.
      • assertThat

        public static ListAssert<Double> assertThat​(DoubleStream actual)
        Creates a new instance of ListAssert from the given DoubleStream.

        Be aware that the DoubleStream under test will be converted to a List when an assertion requires to inspect its content. Once this is done the DoubleStream can't reused as it has already been consumed.

        Calling multiple methods on the returned ListAssert is safe as it only interacts with the List built from the DoubleStream.

        Examples:

         // you can chain multiple assertions on the DoubleStream as it is converted to a List
         assertThat(DoubleStream.of(1.0, 2.0, 3.0)).contains(1.0)
                                                   .doesNotContain(42.0);

        The following assertion fails as the DoubleStream under test is converted to a List before being compared to the expected DoubleStream:

         // FAIL: the DoubleStream under test is converted to a List and compared to a DoubleStream but a List is not a DoubleStream.
         assertThat(DoubleStream.of(1.0, 2.0, 3.0)).isEqualTo(DoubleStream.of(1.0, 2.0, 3.0));

        These assertions succeed as isEqualTo and isSameAs checks references which does not require to convert the DoubleStream to a List.

         // The following assertions succeed as it only performs reference checking which does not require to convert the DoubleStream to a List
         DoubleStream stream = DoubleStream.of(1.0, 2.0, 3.0);
         assertThat(stream).isEqualTo(stream)
                           .isSameAs(stream);
        Parameters:
        actual - the actual DoubleStream value.
        Returns:
        the created assertion object.
      • assertThat

        public static ListAssert<Long> assertThat​(LongStream actual)
        Creates a new instance of ListAssert from the given LongStream.

        Be aware that the LongStream under test will be converted to a List when an assertion requires to inspect its content. Once this is done the LongStream can't reused as it has already been consumed.

        Calling multiple methods on the returned ListAssert is safe as it only interacts with the List built from the LongStream.

        Examples:

         // you can chain multiple assertions on the LongStream as it is converted to a List
         assertThat(LongStream.of(1, 2, 3)).contains(1)
                                           .doesNotContain(42);

        The following assertion fails as the LongStream under test is converted to a List before being compared to the expected LongStream:

         // FAIL: the LongStream under test is converted to a List and compared to a LongStream but a List is not a LongStream.
         assertThat(LongStream.of(1, 2, 3)).isEqualTo(LongStream.of(1, 2, 3));

        These assertions succeed as isEqualTo and isSameAs checks references which does not require to convert the LongStream to a List.

         // The following assertions succeed as it only performs reference checking which does not require to convert the LongStream to a List
         LongStream stream = LongStream.of(1, 2, 3);
         assertThat(stream).isEqualTo(stream)
                           .isSameAs(stream);
        Parameters:
        actual - the actual LongStream value.
        Returns:
        the created assertion object.
      • assertThat

        public static ListAssert<Integer> assertThat​(IntStream actual)
        Creates a new instance of ListAssert from the given IntStream.

        Be aware that the IntStream under test will be converted to a List when an assertion requires to inspect its content. Once this is done the IntStream can't reused as it has already been consumed.

        Calling multiple methods on the returned ListAssert is safe as it only interacts with the List built from the IntStream.

        Examples:

         // you can chain multiple assertions on the IntStream as it is converted to a List
         assertThat(IntStream.of(1, 2, 3)).contains(1)
                                          .doesNotContain(42);

        The following assertion fails as the IntStream under test is converted to a List before being compared to the expected IntStream:

         // FAIL: the IntStream under test is converted to a List and compared to a IntStream but a List is not a IntStream.
         assertThat(IntStream.of(1, 2, 3)).isEqualTo(IntStream.of(1, 2, 3));

        These assertions succeed as isEqualTo and isSameAs checks references which does not require to convert the IntStream to a List.

         // The following assertions succeed as it only performs reference checking which does not require to convert the IntStream to a List
         IntStream stream = IntStream.of(1, 2, 3);
         assertThat(stream).isEqualTo(stream)
                           .isSameAs(stream);
        Parameters:
        actual - the actual IntStream value.
        Returns:
        the created assertion object.
      • assertThat

        public static <ELEMENT> SpliteratorAssert<ELEMENT> assertThat​(Spliterator<ELEMENT> actual)
        Creates a new instance of SpliteratorAssert from the given Spliterator. Example:
         Spliterator<Integer> spliterator = Stream.of(1, 2, 3).spliterator();
         assertThat(spliterator).hasCharacteristics(Spliterator.SIZED); 
        Type Parameters:
        ELEMENT - the type of elements.
        Parameters:
        actual - the spliterator to test.
        Returns:
        the created assertion object.
      • assertThat

        public static AbstractPathAssert<?> assertThat​(Path actual)
        Creates a new instance of PathAssert
        Parameters:
        actual - the path to test
        Returns:
        the created assertion object
      • assertThat

        public static <K,​V> MapAssert<K,​V> assertThat​(Map<K,​V> actual)
        Creates a new instance of MapAssert.

        Returned type is MapAssert as it overrides method to annotate them with SafeVarargs avoiding annoying warnings.

        Type Parameters:
        K - the type of keys in the map.
        V - the type of values in the map.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
      • assertThat

        public static <T extends Comparable<? super T>> AbstractComparableAssert<?,​T> assertThat​(T actual)
        Creates a new instance of GenericComparableAssert with standard comparison semantics.
        Type Parameters:
        T - the type of actual.
        Parameters:
        actual - the actual value.
        Returns:
        the created assertion object.
      • assertThat

        public static <T extends AssertDelegateTarget> T assertThat​(T assertion)
        Returns the given assertion. This method improves code readability by surrounding the given assertion with assertThat.

        Consider for example the following MyButton and MyButtonAssert classes:

         public class MyButton extends JButton {
        
           private boolean blinking;
        
           public boolean isBlinking() { return this.blinking; }
        
           public void setBlinking(boolean blink) { this.blinking = blink; }
        
         }
        
         private static class MyButtonAssert implements AssertDelegateTarget {
        
           private MyButton button;
           MyButtonAssert(MyButton button) { this.button = button; }
        
           void isBlinking() {
             // standard assertion from core Assertions.assertThat
             assertThat(button.isBlinking()).isTrue();
           }
        
           void isNotBlinking() {
             // standard assertion from core Assertions.assertThat
             assertThat(button.isBlinking()).isFalse();
           }
         }
        As MyButtonAssert implements AssertDelegateTarget, you can use assertThat(buttonAssert).isBlinking(); instead of buttonAssert.isBlinking(); to have easier to read assertions:
         @Test
         public void AssertDelegateTarget_example() {
        
           MyButton button = new MyButton();
           MyButtonAssert buttonAssert = new MyButtonAssert(button);
        
           // you can encapsulate MyButtonAssert assertions methods within assertThat
           assertThat(buttonAssert).isNotBlinking(); // same as : buttonAssert.isNotBlinking();
        
           button.setBlinking(true);
        
           assertThat(buttonAssert).isBlinking(); // same as : buttonAssert.isBlinking();
         }
        Type Parameters:
        T - the generic type of the user-defined assert.
        Parameters:
        assertion - the assertion to return.
        Returns:
        the given assertion.
      • useRepresentation

        public static void useRepresentation​(Representation customRepresentation)
        Register a Representation that will be used in all following assertions.

        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 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
           @Override
           public String toStringOf(Object o) {
             if (o instanceof Example) return "Example";
             // fallback to default formatting.
             return super.toStringOf(o);
           }
        
           // change String representation
           @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$>
        Parameters:
        customRepresentation - the Representation to use
        Since:
        2.5.0 / 3.5.0
      • registerFormatterForType

        public static <T> void registerFormatterForType​(Class<T> type,
                                                        Function<T,​String> formatter)
        Assertions error messages uses a 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 Representation:

        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);
        Type Parameters:
        T - the type of format.
        Parameters:
        type - the class of the type to format
        formatter - the formatter Function
        Since:
        3.5.0