com.fitbur.assertj.api.Assertions Maven / Gradle / Ivy
/** * 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-2016 the original author or authors. */ package com.fitbur.assertj.api; import static com.fitbur.assertj.data.Percentage.withPercentage; import java.io.File; import java.io.InputStream; import java.math.BigDecimal; import java.net.URI; import java.net.URL; import java.nio.charset.Charset; import java.nio.file.Path; import java.sql.Timestamp; import java.text.DateFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.OffsetDateTime; import java.time.OffsetTime; import java.time.ZonedDateTime; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.OptionalDouble; import java.util.OptionalInt; import java.util.OptionalLong; import java.util.concurrent.CompletableFuture; import java.util.stream.Stream; import com.fitbur.assertj.api.ThrowableAssert.ThrowingCallable; import com.fitbur.assertj.api.exception.RuntimeIOException; import com.fitbur.assertj.api.filter.FilterOperator; import com.fitbur.assertj.api.filter.Filters; import com.fitbur.assertj.api.filter.InFilter; import com.fitbur.assertj.api.filter.NotFilter; import com.fitbur.assertj.api.filter.NotInFilter; import com.fitbur.assertj.condition.AllOf; import com.fitbur.assertj.condition.AnyOf; import com.fitbur.assertj.condition.DoesNotHave; import com.fitbur.assertj.condition.Not; import com.fitbur.assertj.data.Index; import com.fitbur.assertj.data.MapEntry; import com.fitbur.assertj.data.Offset; import com.fitbur.assertj.data.Percentage; import com.fitbur.assertj.groups.Properties; import com.fitbur.assertj.groups.Tuple; import com.fitbur.assertj.util.Files; import com.fitbur.assertj.util.GroupFormatUtil; import com.fitbur.assertj.util.URLs; import com.fitbur.assertj.util.introspection.FieldSupport; /** * Entry point for assertion methods for different data types. Each method in this class is a static factory for the * type-specific assertion objects. The purpose of this class is to make test code more readable. *
{@link DoesNotHave}. * * @param condition the condition to inverse. * @return The Not condition created. */ public static* For example: * *
* * This class only contains all assertThat methods, if you have ambiguous method compilation error, use either {@link AssertionsForClassTypes} or {@link AssertionsForInterfaceTypes} * and if you need both, fully qualify you assertThat method. * * Java 8 is picky when choosing the rightint removed = employees.removeFired(); * {@link Assertions#assertThat(int) assertThat}(removed).{@link IntegerAssert#isZero isZero}(); * * List<Employee> newEmployees = employees.hired(TODAY); * {@link Assertions#assertThat(Iterable) assertThat}(newEmployees).{@link IterableAssert#hasSize(int) hasSize}(6);
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 properassertThat
method (normallyassertThat(Throwable)
as foo might implement an interface like List, * if that occurredassertThat(List)
would also be a possible choice - thus confusing java 8. ** This why {@link Assertions} have been split in {@link AssertionsForClassTypes} and {@link AssertionsForInterfaceTypes} * (see http://stackoverflow.com/questions/29499847/ambiguous-method-in-java-8-why). * * @author Alex Ruiz * @author Yvonne Wang * @author David DIDIER * @author Ted Young * @author Joel Costigliola * @author Matthieu Baechler * @author Mikhail Mazursky * @author Nicolas François * @author Julien Meddah * @author William Delanoue */ public class Assertions { /** * Create assertion for {@link java.util.concurrent.CompletableFuture}. * * @param future the actual value. * @param
the type of the value contained in the {@link java.util.concurrent.CompletableFuture}. * * @return the created assertion object. */ public static CompletableFutureAssert assertThat(CompletableFuture actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Create assertion for {@link java.util.Optional}. * * @param optional the actual value. * @param the type of the value contained in the {@link java.util.Optional}. * * @return the created assertion object. */ public static OptionalAssert assertThat(Optional actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Create assertion for {@link java.util.OptionalDouble}. * * @param optionalDouble the actual value. * * @return the created assertion object. */ public static OptionalDoubleAssert assertThat(OptionalDouble actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Create assertion for {@link java.util.OptionalInt}. * * @param optionalInt the actual value. * * @return the created assertion object. */ public static OptionalIntAssert assertThat(OptionalInt actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Create assertion for {@link java.util.OptionalInt}. * * @param optionalLong the actual value. * * @return the created assertion object. */ public static OptionalLongAssert assertThat(OptionalLong actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of {@link BigDecimalAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractBigDecimalAssert> assertThat(BigDecimal actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link UriAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractUriAssert> assertThat(URI actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link UrlAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractUrlAssert> assertThat(URL actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link BooleanAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractBooleanAssert> assertThat(boolean actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link BooleanAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractBooleanAssert> assertThat(Boolean actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link BooleanArrayAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractBooleanArrayAssert> assertThat(boolean[] actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link ByteAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractByteAssert> assertThat(byte actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link ByteAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractByteAssert> assertThat(Byte actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link ByteArrayAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractByteArrayAssert> assertThat(byte[] actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link CharacterAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractCharacterAssert> assertThat(char actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link CharArrayAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractCharArrayAssert> assertThat(char[] actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link CharacterAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractCharacterAssert> assertThat(Character actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link ClassAssert}
* * @param actual the actual value. * @return the created assertion object. */ public static AbstractClassAssert> assertThat(Class> actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link DoubleAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractDoubleAssert> assertThat(double actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link DoubleAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractDoubleAssert> assertThat(Double actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link DoubleArrayAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractDoubleArrayAssert> assertThat(double[] actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link FileAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractFileAssert> assertThat(File actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link InputStreamAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractInputStreamAssert, ? extends InputStream> assertThat(InputStream actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link FloatAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractFloatAssert> assertThat(float actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link FloatAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractFloatAssert> assertThat(Float actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link FloatArrayAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractFloatArrayAssert> assertThat(float[] actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link IntegerAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractIntegerAssert> assertThat(int actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link IntArrayAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractIntArrayAssert> assertThat(int[] actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link IntegerAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractIntegerAssert> assertThat(Integer actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link LongAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractLongAssert> assertThat(long actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link LongAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractLongAssert> assertThat(Long actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link LongArrayAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractLongArrayAssert> assertThat(long[] actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link ObjectAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public staticAbstractObjectAssert, T> assertThat(T actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of {@link ObjectArrayAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public staticAbstractObjectArrayAssert, T> assertThat(T[] actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of {@link ShortAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractShortAssert> assertThat(short actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link ShortAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractShortAssert> assertThat(Short actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link ShortArrayAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractShortArrayAssert> assertThat(short[] actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link StringAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractCharSequenceAssert, String> assertThat(String actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link DateAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractDateAssert> assertThat(Date actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link ZonedDateTimeAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractZonedDateTimeAssert> assertThat(ZonedDateTime actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link LocalDateTimeAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractLocalDateTimeAssert> assertThat(LocalDateTime actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link java.time.OffsetDateTime}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractOffsetDateTimeAssert> assertThat(OffsetDateTime actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Create assertion for {@link java.time.OffsetTime}. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractOffsetTimeAssert> assertThat(OffsetTime actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link LocalTimeAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractLocalTimeAssert> assertThat(LocalTime actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link LocalDateAssert}
. * * @param localDate the actual value. * @return the created assertion object. */ public static AbstractLocalDateAssert> assertThat(LocalDate actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Creates a new instance of{@link ThrowableAssert}
. * * @param actual the actual value. * @return the created {@link ThrowableAssert}. */ public static AbstractThrowableAssert, ? extends Throwable> assertThat(Throwable actual) { return AssertionsForClassTypes.assertThat(actual); } /** * Allows to capture and then assert on a {@link Throwable} more easily when used with Java 8 lambdas. * ** Example : *
* ** * If the provided {@link ThrowingCallable} does not raise an exception, an error is immediately raised, * in that case the test description provided with {@link AbstractAssert#as(String, Object...) as(String, Object...)} is not honored. * To use a test description, use {@link #catchThrowable(ThrowingCallable) catchThrowable} as shown below. *{@literal @}Test * public void testException() { * assertThatThrownBy(() -> { throw new Exception("boom!"); }).isInstanceOf(Exception.class) * .hasMessageContaining("boom"); * }
* * @param shouldRaiseThrowable The {@link ThrowingCallable} or lambda with the code that should raise the throwable. * @return The captured exception or// assertion will fail but "display me" won't appear in the error * assertThatThrownBy(() -> { // do nothing }).as("display me").isInstanceOf(Exception.class); * * // assertion will fail AND "display me" will appear in the error * Throwable thrown = catchThrowable(() -> { // do nothing }); * assertThat(thrown).as("display me").isInstanceOf(Exception.class);
null
if none was raised by the callable. */ public static AbstractThrowableAssert, ? extends Throwable> assertThatThrownBy(ThrowingCallable shouldRaiseThrowable) { return assertThat(catchThrowable(shouldRaiseThrowable)).hasBeenThrown(); } /** * Allows to catch an {@link Throwable} more easily when used with Java 8 lambdas. * ** This caught {@link Throwable} can then be asserted. *
* ** Example: *
* ** * @param shouldRaiseThrowable The lambda with the code that should raise the exception. * @return The captured exception or{@literal @}Test * public void testException() { * // when * Throwable thrown = catchThrowable(() -> { throw new Exception("boom!"); }); * * // then * assertThat(thrown).isInstanceOf(Exception.class) * .hasMessageContaining("boom"); * }
null
if none was raised by the callable. */ public static Throwable catchThrowable(ThrowingCallable shouldRaiseThrowable) { return AssertionsForClassTypes.catchThrowable(shouldRaiseThrowable); } /** * 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. ** Example: *
* * This method is more or less the same of {@link #assertThatThrownBy(ThrowingCallable)} but in a more natural way. * @param actual the actual value. * @return the created {@link ThrowableTypeAssert}. */ public staticassertThatExceptionOfType(IOException.class) * .isThrownBy(() -> { throw new IOException("boom!"); }) * .withMessage("boom!");
ThrowableTypeAssert assertThatExceptionOfType(final Class extends T> exceptionType) { return AssertionsForClassTypes.assertThatExceptionOfType(exceptionType); } // ------------------------------------------------------------------------------------------------- // fail methods : not assertions but here to have a single entry point to all AssertJ features. // ------------------------------------------------------------------------------------------------- /** * Only delegate to {@link Fail#setRemoveAssertJRelatedElementsFromStackTrace(boolean)} so that Assertions offers a * full feature entry point to all AssertJ Assert features (but you can use {@link Fail} if you prefer). */ public static void setRemoveAssertJRelatedElementsFromStackTrace(boolean removeAssertJRelatedElementsFromStackTrace) { Fail.setRemoveAssertJRelatedElementsFromStackTrace(removeAssertJRelatedElementsFromStackTrace); } /** * Only delegate to {@link Fail#fail(String)} so that Assertions offers a full feature entry point to all Assertj * Assert features (but you can use Fail if you prefer). */ public static void fail(String failureMessage) { Fail.fail(failureMessage); } /** * Only delegate to {@link Fail#fail(String, Throwable)} so that Assertions offers a full feature entry point to all * AssertJ features (but you can use Fail if you prefer). */ public static void fail(String failureMessage, Throwable realCause) { Fail.fail(failureMessage, realCause); } /** * Only delegate to {@link Fail#failBecauseExceptionWasNotThrown(Class)} so that Assertions offers a full feature * entry point to all AssertJ features (but you can use Fail if you prefer). * * {@link Assertions#shouldHaveThrown(Class)} can be used as a replacement. */ public static void failBecauseExceptionWasNotThrown(Class extends Throwable> exceptionClass) { Fail.shouldHaveThrown(exceptionClass); } /** * Only delegate to {@link Fail#shouldHaveThrown(Class)} so that Assertions offers a full feature * entry point to all AssertJ features (but you can use Fail if you prefer). */ public static void shouldHaveThrown(Class extends Throwable> exceptionClass) { Fail.shouldHaveThrown(exceptionClass); } /** * In error messages, sets the threshold when iterable/array formatting will 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 * *
* 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"); * * // formatted as: * * ["A Game of Thrones", "The Lord of the Rings", "Assassin's Apprentice"]
* * @param maxLengthForSingleLineDescription the maximum length for an iterable/array to be displayed on one line */ public static void setMaxLengthForSingleLineDescription(int maxLengthForSingleLineDescription) { GroupFormatUtil.setMaxLengthForSingleLineDescription(maxLengthForSingleLineDescription); } // ------------------------------------------------------------------------------------------------------ // 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 chainString[] 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)"]
extractProperty
withfrom
method, see examples below : * * **/ public static// 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");
Properties extractProperty(String propertyName, Class propertyType) { return Properties.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
withfrom
method, see examples below : * * **/ public static Properties// 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");
DoesNotHave doesNotHave(Condition super T> condition) { return DoesNotHave.doesNotHave(condition); } /** * Creates a new {@link Not}. * * @param condition the condition to inverse. * @return The Not condition created. */ public static Not not(Condition super T> condition) { return Not.not(condition); } // -------------------------------------------------------------------------------------------------- // Filter methods : not assertions but here to have a single entry point to all AssertJ features. // -------------------------------------------------------------------------------------------------- /** * Only delegate to {@link Filters#filter(Object[])} so that Assertions offers a full feature entry point to all * AssertJ features (but you can use {@link Filters} if you prefer). * * Note that the given array is not modified, the filters are performed on an {@link Iterable} copy of the array. * * Typical usage with {@link Condition} : * * * * * and with filter language based on java bean property : * * *assertThat(filter(players).being(potentialMVP).get()).containsOnly(james, rose);
*/ public staticassertThat(filter(players).with("pointsPerGame").greaterThan(20).and("assistsPerGame").greaterThan(7).get()) * .containsOnly(james, rose);
Filters filter(E[] array) { return Filters.filter(array); } /** * Only delegate to {@link Filters#filter(Object[])} so that Assertions offers a full feature entry point to all * AssertJ features (but you can use {@link Filters} if you prefer). * * Note that the given {@link Iterable} is not modified, the filters are performed on a copy. * * Typical usage with {@link Condition} : * * * * * and with filter language based on java bean property : * * *assertThat(filter(players).being(potentialMVP).get()).containsOnly(james, rose);
*/ public staticassertThat(filter(players).with("pointsPerGame").greaterThan(20).and("assistsPerGame").greaterThan(7).get()) * .containsOnly(james, rose);
Filters filter(Iterable iterableToFilter) { return Filters.filter(iterableToFilter); } /** * 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: * * * * @param values values to match (one match is sufficient) * @return the created "in" filter */ public static InFilter in(Object... values) { return InFilter.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", in(800, 26)) * .containsOnly(yoda, obiwan, luke);
* * @param valuesNotToMatch values not to match (none of the values must match) * @return the created "not in" filter */ public static NotInFilter notIn(Object... valuesNotToMatch) { return NotInFilter.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. *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);
* As often, an example helps: * *
* * @param valueNotToMatch the value not to match * @return the created "not" filter */ public static NotFilter not(Object valueNotToMatch) { return NotFilter.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)}. *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);
* 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 RuntimeIOException if an I/O exception occurs. */ public static String contentOf(File file, Charset charset) { return Files.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 RuntimeIOException if an I/O exception occurs. */ public static String contentOf(File file, String charsetName) { return Files.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 RuntimeIOException if an I/O exception occurs. */ public static String contentOf(File file) { return Files.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 RuntimeIOException if an I/O exception occurs. */ public static ListlinesOf(File file) { return Files.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 RuntimeIOException if an I/O exception occurs. */ public static List linesOf(File file, Charset charset) { return Files.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 RuntimeIOException if an I/O exception occurs. */ public static List linesOf(File file, String charsetName) { return Files.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 RuntimeIOException if an I/O exception occurs. */ public static String contentOf(URL url, Charset charset) { return URLs.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 RuntimeIOException if an I/O exception occurs. */ public static String contentOf(URL url, String charsetName) { return URLs.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 RuntimeIOException if an I/O exception occurs. */ public static String contentOf(URL url) { return URLs.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 RuntimeIOException if an I/O exception occurs. */ public static ListlinesOf(URL url) { return URLs.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 RuntimeIOException if an I/O exception occurs. */ public static List linesOf(URL url, Charset charset) { return URLs.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 RuntimeIOException if an I/O exception occurs. */ public static List linesOf(URL url, String charsetName) { return URLs.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: *
* ** * To revert to default strict date parsing, call {@code setLenientDateParsing(false)}. * * @param value whether lenient parsing mode should be enabled or not */ public static void setLenientDateParsing(boolean value) { AbstractDateAssert.setLenientDateParsing(value); } /** * Add the given date format to the ones used to parse date String in String based Date assertions like * {@link com.fitbur.assertj.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 : *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
*
* * 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 com.fitbur.assertj.api.AbstractDateAssert#withDefaultDateFormatsOnly()}. * * Code examples: * *- {@link com.fitbur.assertj.api.AbstractDateAssert#withDateFormat(String)}
*- {@link com.fitbur.assertj.api.AbstractDateAssert#withDateFormat(java.text.DateFormat)}
*- {@link #registerCustomDateFormat(java.text.DateFormat)}
*- {@link #registerCustomDateFormat(String)}
** * @param userCustomDateFormat the new Date format used for String based Date assertions. */ public static void registerCustomDateFormat(DateFormat userCustomDateFormat) { AbstractDateAssert.registerCustomDateFormat(userCustomDateFormat); } /** * Add the given date format to the ones used to parse date String in String based Date assertions like * {@link com.fitbur.assertj.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 : *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.SSS, 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");
*
* * 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 com.fitbur.assertj.api.AbstractDateAssert#withDefaultDateFormatsOnly()}. * * Code examples: * *- {@link com.fitbur.assertj.api.AbstractDateAssert#withDateFormat(String)}
*- {@link com.fitbur.assertj.api.AbstractDateAssert#withDateFormat(java.text.DateFormat)}
*- {@link #registerCustomDateFormat(java.text.DateFormat)}
*- {@link #registerCustomDateFormat(String)}
** * @param userCustomDateFormatPattern the new Date format pattern used for String based Date assertions. */ public static void registerCustomDateFormat(String userCustomDateFormatPattern) { AbstractDateAssert.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: *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.SSS, 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");
*
* * Example of valid string date representations: *- *
yyyy-MM-dd'T'HH:mm:ss.SSS
- *
yyyy-MM-dd HH:mm:ss.SSS
(for {@link Timestamp} String representation support)- *
yyyy-MM-dd'T'HH:mm:ss
- *
yyyy-MM-dd
*
*/ public static void useDefaultDateFormatsOnly() { AbstractDateAssert.useDefaultDateFormatsOnly(); } /** * Delegates the creation of the {@link Assert} to the {@link AssertProvider#assertThat()} of the given component. * *- *
2003-04-26T03:01:02.999
- *
2003-04-26 03:01:02.999
- *
2003-04-26T13:01:02
- *
2003-04-26
* Read the comments on {@link AssertProvider} for an example of its usage. *
* * @param component * the component that creates its own assert * @return the associated {@link Assert} of the given component */ public staticT assertThat(final AssertProvider component) { return AssertionsForInterfaceTypes.assertThat(component); } /** * Creates a new instance of {@link CharSequenceAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public static AbstractCharSequenceAssert, ? extends CharSequence> assertThat(CharSequence actual) { return AssertionsForInterfaceTypes.assertThat(actual); } /** * Creates a new instance of{@link IterableAssert}
. * * @param actual the actual value. * @return the created assertion object. */ public staticAbstractIterableAssert, ? extends Iterable extends T>, T> assertThat(Iterable extends T> actual) { return AssertionsForInterfaceTypes.assertThat(actual); } /** * Creates a new instance of {@link IterableAssert}
. * * Be aware that calls to most methods on returned IterableAssert will consume Iterator so it won't be possible to * iterate over it again. Calling multiple methods on returned IterableAssert is safe as Iterator's elements are * cached by IterableAssert first time Iterator is consumed. * * @param actual the actual value. * @return the created assertion object. */ public staticAbstractIterableAssert, ? extends Iterable extends T>, T> assertThat(Iterator extends T> actual) { return AssertionsForInterfaceTypes.assertThat(actual); } /** * Creates a new instance of {@link ListAssert}
from a {@link Stream}. * * @param actual the actual {@link Stream} value. * @return the created assertion object. */ public staticAbstractListAssert, ? extends List extends T>, T> assertThat(List extends T> actual) { return AssertionsForInterfaceTypes.assertThat(actual); } /** * Creates a new instance of {@link ListAssert}
from the given {@link Stream}. * * Be aware that to create the returned {@link ListAssert} the given the {@link Stream} is consumed so it won't be * possible to use it again. Calling multiple methods on the returned {@link ListAssert} is safe as it only * interacts with the {@link List} built from the {@link Stream}. * * @param actual the actual value. * @return the created assertion object. */ public staticAbstractListAssert, ? extends List extends T>, T> assertThat(Stream extends T> actual) { return AssertionsForInterfaceTypes.assertThat(actual); } /** * Creates a new instance of {@link PathAssert} * * @param actual the path to test * @return the created assertion object */ public static AbstractPathAssert> assertThat(Path actual) { return AssertionsForInterfaceTypes.assertThat(actual); } /** * Creates a new instance of {@link MapAssert}
. ** Returned type is {@link MapAssert} as it overrides method to annotate them with {@link SafeVarargs} avoiding * annoying warnings. * * @param actual the actual value. * @return the created assertion object. */ public static
MapAssert assertThat(Map actual) { return AssertionsForInterfaceTypes.assertThat(actual); } /** * Creates a new instance of {@link GenericComparableAssert}
with * standard comparison semantics. * * @param actual the actual value. * @return the created assertion object. */ public static> AbstractComparableAssert, T> assertThat(T actual) { return AssertionsForInterfaceTypes.assertThat(actual); } /** * 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: *
* * As MyButtonAssert implements AssertDelegateTarget, you can usepublic 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(); * } * }
assertThat(buttonAssert).isBlinking();
* instead ofbuttonAssert.isBlinking();
to have easier to read assertions: ** * @param{@literal @}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(); * }
the generic type of the user-defined assert. * @param assertion the assertion to return. * @return the given assertion. */ public static T assertThat(T assertion) { return assertion; } /** * Creates a new {@link Assertions}. */ protected Assertions() {} }