diff --git a/testing-modules/assertion-libraries/README.md b/testing-modules/assertion-libraries/README.md new file mode 100644 index 0000000000..5be5c7e004 --- /dev/null +++ b/testing-modules/assertion-libraries/README.md @@ -0,0 +1,12 @@ + +## Relevant Articles + +- [AssertJā€™s Java 8 Features](http://www.baeldung.com/assertJ-java-8-features) +- [AssertJ for Guava](http://www.baeldung.com/assertJ-for-guava) +- [Introduction to AssertJ](http://www.baeldung.com/introduction-to-assertj) +- [Testing with Google Truth](http://www.baeldung.com/google-truth) +- [Testing with JGoTesting](http://www.baeldung.com/jgotesting) +- [Guide to JSpec](http://www.baeldung.com/jspec) +- [Custom Assertions with AssertJ](http://www.baeldung.com/assertj-custom-assertion) +- [Using Conditions with AssertJ Assertions](http://www.baeldung.com/assertj-conditions) +- [AssertJ Exception Assertions](http://www.baeldung.com/assertj-exception-assertion) diff --git a/testing-modules/assertion-libraries/pom.xml b/testing-modules/assertion-libraries/pom.xml new file mode 100644 index 0000000000..3c21e46b61 --- /dev/null +++ b/testing-modules/assertion-libraries/pom.xml @@ -0,0 +1,85 @@ + + + 4.0.0 + assertion-libraries + 0.1-SNAPSHOT + assertion-libraries + + + com.ossez + testing-modules + 0.0.2-SNAPSHOT + + + + + com.google.truth + truth + ${truth.version} + + + + junit + junit + + + + + com.google.truth.extensions + truth-java8-extension + ${truth.version} + test + + + org.assertj + assertj-guava + ${assertj-guava.version} + + + org.javalite + javalite-common + ${javalite.version} + + + org.jgotesting + jgotesting + ${jgotesting.version} + test + + + + junit + junit + + + + + + + + + org.assertj + assertj-assertions-generator-maven-plugin + ${assertj-generator.version} + + + com.baeldung.testing.assertj.custom.Person + + + + + + + + 0.32 + 3.4.0 + 2.1.0 + 1.4.13 + 0.12 + + + \ No newline at end of file diff --git a/testing-modules/assertion-libraries/src/main/java/com/ossez/assertj/Dog.java b/testing-modules/assertion-libraries/src/main/java/com/ossez/assertj/Dog.java new file mode 100644 index 0000000000..f050cab1db --- /dev/null +++ b/testing-modules/assertion-libraries/src/main/java/com/ossez/assertj/Dog.java @@ -0,0 +1,19 @@ +package com.ossez.assertj; + +public class Dog { + private String name; + private Float weight; + + public Dog(String name, Float weight) { + this.name = name; + this.weight = weight; + } + + public String getName() { + return name; + } + + public Float getWeight() { + return weight; + } +} diff --git a/testing-modules/assertion-libraries/src/main/java/com/ossez/assertj/Member.java b/testing-modules/assertion-libraries/src/main/java/com/ossez/assertj/Member.java new file mode 100644 index 0000000000..4381b73276 --- /dev/null +++ b/testing-modules/assertion-libraries/src/main/java/com/ossez/assertj/Member.java @@ -0,0 +1,19 @@ +package com.ossez.assertj; + +public class Member { + private String name; + private int age; + + public Member(String name, int age) { + this.name = name; + this.age = age; + } + + public String getName() { + return name; + } + + public int getAge() { + return age; + } +} diff --git a/testing-modules/assertion-libraries/src/main/java/com/ossez/assertj/Person.java b/testing-modules/assertion-libraries/src/main/java/com/ossez/assertj/Person.java new file mode 100644 index 0000000000..f47fbb2fb9 --- /dev/null +++ b/testing-modules/assertion-libraries/src/main/java/com/ossez/assertj/Person.java @@ -0,0 +1,19 @@ +package com.ossez.assertj; + +public class Person { + private String name; + private Integer age; + + public Person(String name, Integer age) { + this.name = name; + this.age = age; + } + + public String getName() { + return name; + } + + public Integer getAge() { + return age; + } +} diff --git a/testing-modules/assertion-libraries/src/main/java/com/ossez/assertj/custom/Person.java b/testing-modules/assertion-libraries/src/main/java/com/ossez/assertj/custom/Person.java new file mode 100644 index 0000000000..e3fc7bb123 --- /dev/null +++ b/testing-modules/assertion-libraries/src/main/java/com/ossez/assertj/custom/Person.java @@ -0,0 +1,32 @@ +package com.ossez.assertj.custom; + +import java.util.ArrayList; +import java.util.List; + +public class Person { + private String fullName; + private int age; + private List nicknames; + + public Person(String fullName, int age) { + this.fullName = fullName; + this.age = age; + this.nicknames = new ArrayList<>(); + } + + public void addNickname(String nickname) { + nicknames.add(nickname); + } + + public String getFullName() { + return fullName; + } + + public int getAge() { + return age; + } + + public List getNicknames() { + return nicknames; + } +} diff --git a/testing-modules/assertion-libraries/src/main/java/com/ossez/jspec/Animal.java b/testing-modules/assertion-libraries/src/main/java/com/ossez/jspec/Animal.java new file mode 100644 index 0000000000..e3a6024c48 --- /dev/null +++ b/testing-modules/assertion-libraries/src/main/java/com/ossez/jspec/Animal.java @@ -0,0 +1,41 @@ +package com.ossez.jspec; + +public abstract class Animal { + + protected String name; + + public Animal(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Animal other = (Animal) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + + +} diff --git a/testing-modules/assertion-libraries/src/main/java/com/ossez/jspec/Cage.java b/testing-modules/assertion-libraries/src/main/java/com/ossez/jspec/Cage.java new file mode 100644 index 0000000000..b2b0889786 --- /dev/null +++ b/testing-modules/assertion-libraries/src/main/java/com/ossez/jspec/Cage.java @@ -0,0 +1,48 @@ +package com.ossez.jspec; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +public class Cage { + + private Set animals = new HashSet<>(); + + public void put(Animal animal) { + animals.add(animal); + } + + public void put(Animal... animals) { + this.animals.addAll(Arrays.asList(animals)); + } + + public Animal release(Animal animal) { + return animals.remove(animal) ? animal : null; + } + + public void open() { + animals.clear(); + } + + public boolean hasAnimals() { + return animals.size() > 0; + } + + public boolean isEmpty() { + return animals.isEmpty(); + } + + public Set getAnimals() { + return this.animals; + } + + public int size() { + return animals.size(); + } + + @Override + public String toString() { + return "Cage [animals=" + animals + "]"; + } + +} diff --git a/testing-modules/assertion-libraries/src/main/java/com/ossez/jspec/Cat.java b/testing-modules/assertion-libraries/src/main/java/com/ossez/jspec/Cat.java new file mode 100644 index 0000000000..d1d9eedaca --- /dev/null +++ b/testing-modules/assertion-libraries/src/main/java/com/ossez/jspec/Cat.java @@ -0,0 +1,14 @@ +package com.ossez.jspec; + +public class Cat extends Animal { + + public Cat(String name) { + super(name); + } + + @Override + public String toString() { + return "Cat [name=" + name + "]"; + } + +} diff --git a/testing-modules/assertion-libraries/src/main/java/com/ossez/jspec/Dog.java b/testing-modules/assertion-libraries/src/main/java/com/ossez/jspec/Dog.java new file mode 100644 index 0000000000..935308527c --- /dev/null +++ b/testing-modules/assertion-libraries/src/main/java/com/ossez/jspec/Dog.java @@ -0,0 +1,14 @@ +package com.ossez.jspec; + +public class Dog extends Animal { + + public Dog(String name) { + super(name); + } + + @Override + public String toString() { + return "Dog [name=" + name + "]"; + } + +} diff --git a/testing-modules/assertion-libraries/src/main/java/com/ossez/truth/User.java b/testing-modules/assertion-libraries/src/main/java/com/ossez/truth/User.java new file mode 100644 index 0000000000..2123c9e443 --- /dev/null +++ b/testing-modules/assertion-libraries/src/main/java/com/ossez/truth/User.java @@ -0,0 +1,57 @@ +package com.ossez.truth; + +import java.util.Arrays; +import java.util.List; +import java.util.Objects; + +public class User implements Comparable { + private String name = "John Doe"; + private List emails = Arrays.asList("contact@baeldung.com", "staff@baeldung.com"); + + public User() { + } + + public User(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getEmails() { + return emails; + } + + public void setEmails(List emails) { + this.emails = emails; + } + + @Override + public int hashCode() { + int hash = 5; + hash = 37 * hash + Objects.hashCode(this.name); + return hash; + } + + @Override + public boolean equals(Object obj) { + if (obj == null || getClass() != obj.getClass()) { + return false; + } + + final User other = (User) obj; + return Objects.equals(this.name, other.name); + } + + @Override + public int compareTo(User o) { + return this.getName() + .compareToIgnoreCase(o.getName()); + } + +} diff --git a/testing-modules/assertion-libraries/src/main/java/com/ossez/truth/UserSubject.java b/testing-modules/assertion-libraries/src/main/java/com/ossez/truth/UserSubject.java new file mode 100644 index 0000000000..09577a34d7 --- /dev/null +++ b/testing-modules/assertion-libraries/src/main/java/com/ossez/truth/UserSubject.java @@ -0,0 +1,46 @@ +package com.ossez.truth; + +import com.google.common.truth.ComparableSubject; +import com.google.common.truth.FailureStrategy; +import com.google.common.truth.IterableSubject; +import com.google.common.truth.SubjectFactory; +import com.google.common.truth.Truth; + +public class UserSubject extends ComparableSubject { + + private UserSubject(FailureStrategy failureStrategy, User target) { + super(failureStrategy, target); + } + + private static final SubjectFactory USER_SUBJECT_FACTORY = new SubjectFactory() { + @Override + public UserSubject getSubject(FailureStrategy failureStrategy, User target) { + return new UserSubject(failureStrategy, target); + } + }; + + public static UserSubject assertThat(User user) { + return Truth.assertAbout(USER_SUBJECT_FACTORY) + .that(user); + } + + // Our API begins here + public void hasName(String name) { + if (!actual().getName() + .equals(name)) { + fail("has name", name); + } + } + + public void hasNameIgnoringCase(String name) { + if (!actual().getName() + .equalsIgnoreCase(name)) { + fail("has name ignoring case", name); + } + } + + public IterableSubject emails() { + return Truth.assertThat(actual().getEmails()); + } + +} \ No newline at end of file diff --git a/testing-modules/assertion-libraries/src/test/java/com/ossez/assertj/AssertJConditionUnitTest.java b/testing-modules/assertion-libraries/src/test/java/com/ossez/assertj/AssertJConditionUnitTest.java new file mode 100644 index 0000000000..14efd95b21 --- /dev/null +++ b/testing-modules/assertion-libraries/src/test/java/com/ossez/assertj/AssertJConditionUnitTest.java @@ -0,0 +1,72 @@ +package com.ossez.assertj; + +import static org.assertj.core.api.Assertions.allOf; +import static org.assertj.core.api.Assertions.anyOf; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.not; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.List; + +import org.assertj.core.api.Condition; +import org.junit.Test; + +public class AssertJConditionUnitTest { + private Condition senior = new Condition<>(m -> m.getAge() >= 60, "senior"); + private Condition nameJohn = new Condition<>(m -> m.getName().equalsIgnoreCase("John"), "name John"); + + @Test + public void whenUsingMemberAgeCondition_thenCorrect() { + Member member = new Member("John", 65); + assertThat(member).is(senior); + + try { + assertThat(member).isNot(senior); + fail(); + } catch (AssertionError e) { + assertThat(e).hasMessageContaining("not to be senior"); + } + } + + @Test + public void whenUsingMemberNameCondition_thenCorrect() { + Member member = new Member("Jane", 60); + assertThat(member).doesNotHave(nameJohn); + + try { + assertThat(member).has(nameJohn); + fail(); + } catch (AssertionError e) { + assertThat(e).hasMessageContaining("name John"); + } + } + + @Test + public void whenCollectionConditionsAreSatisfied_thenCorrect() { + List members = new ArrayList<>(); + members.add(new Member("Alice", 50)); + members.add(new Member("Bob", 60)); + + assertThat(members).haveExactly(1, senior); + assertThat(members).doNotHave(nameJohn); + } + + @Test + public void whenCombiningAllOfConditions_thenCorrect() { + Member john = new Member("John", 60); + Member jane = new Member("Jane", 50); + + assertThat(john).is(allOf(senior, nameJohn)); + assertThat(jane).is(allOf(not(nameJohn), not(senior))); + } + + @Test + public void whenCombiningAnyOfConditions_thenCorrect() { + Member john = new Member("John", 50); + Member jane = new Member("Jane", 60); + + assertThat(john).is(anyOf(senior, nameJohn)); + assertThat(jane).is(anyOf(nameJohn, senior)); + } +} diff --git a/testing-modules/assertion-libraries/src/test/java/com/ossez/assertj/AssertJCoreUnitTest.java b/testing-modules/assertion-libraries/src/test/java/com/ossez/assertj/AssertJCoreUnitTest.java new file mode 100644 index 0000000000..f80c332c3e --- /dev/null +++ b/testing-modules/assertion-libraries/src/test/java/com/ossez/assertj/AssertJCoreUnitTest.java @@ -0,0 +1,117 @@ +package com.ossez.assertj; + +import org.assertj.core.util.Maps; +import org.junit.Ignore; +import org.junit.Test; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.InputStream; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; + +import static org.assertj.core.api.Assertions.*; + +public class AssertJCoreUnitTest { + + @Test + public void whenComparingReferences_thenNotEqual() throws Exception { + Dog fido = new Dog("Fido", 5.15f); + Dog fidosClone = new Dog("Fido", 5.15f); + + assertThat(fido).isNotEqualTo(fidosClone); + } + + @Test + public void whenComparingFields_thenEqual() throws Exception { + Dog fido = new Dog("Fido", 5.15f); + Dog fidosClone = new Dog("Fido", 5.15f); + + assertThat(fido).isEqualToComparingFieldByFieldRecursively(fidosClone); + } + + @Test + public void whenCheckingForElement_thenContains() throws Exception { + List list = Arrays.asList("1", "2", "3"); + + assertThat(list).contains("1"); + } + + @Test + public void whenCheckingForElement_thenMultipleAssertions() throws Exception { + List list = Arrays.asList("1", "2", "3"); + + assertThat(list).isNotEmpty(); + assertThat(list).startsWith("1"); + assertThat(list).doesNotContainNull(); + + assertThat(list).isNotEmpty().contains("1").startsWith("1").doesNotContainNull().containsSequence("2", "3"); + } + + @Test + public void whenCheckingRunnable_thenIsInterface() throws Exception { + assertThat(Runnable.class).isInterface(); + } + + @Test + public void whenCheckingCharacter_thenIsUnicode() throws Exception { + char someCharacter = 'c'; + + assertThat(someCharacter).isNotEqualTo('a').inUnicode().isGreaterThanOrEqualTo('b').isLowerCase(); + } + + @Test + public void whenAssigningNSEExToException_thenIsAssignable() throws Exception { + assertThat(Exception.class).isAssignableFrom(NoSuchElementException.class); + } + + @Test + public void whenComparingWithOffset_thenEquals() throws Exception { + assertThat(5.1).isEqualTo(5, withPrecision(1d)); + } + + @Test + public void whenCheckingString_then() throws Exception { + assertThat("".isEmpty()).isTrue(); + } + + @Test + public void whenCheckingFile_then() throws Exception { + final File someFile = File.createTempFile("aaa", "bbb"); + someFile.deleteOnExit(); + + assertThat(someFile).exists().isFile().canRead().canWrite(); + } + + @Test + public void whenCheckingIS_then() throws Exception { + InputStream given = new ByteArrayInputStream("foo".getBytes()); + InputStream expected = new ByteArrayInputStream("foo".getBytes()); + + assertThat(given).hasSameContentAs(expected); + } + + @Test + public void whenGivenMap_then() throws Exception { + Map map = Maps.newHashMap(2, "a"); + + assertThat(map).isNotEmpty().containsKey(2).doesNotContainKeys(10).contains(entry(2, "a")); + } + + @Test + public void whenGivenException_then() throws Exception { + Exception ex = new Exception("abc"); + + assertThat(ex).hasNoCause().hasMessageEndingWith("c"); + } + + @Ignore // IN ORDER TO TEST, REMOVE THIS LINE + @Test + public void whenRunningAssertion_thenDescribed() throws Exception { + Person person = new Person("Alex", 34); + + assertThat(person.getAge()).as("%s's age should be equal to 100").isEqualTo(100); + } +} diff --git a/testing-modules/assertion-libraries/src/test/java/com/ossez/assertj/AssertJGuavaUnitTest.java b/testing-modules/assertion-libraries/src/test/java/com/ossez/assertj/AssertJGuavaUnitTest.java new file mode 100644 index 0000000000..bfc48e8d58 --- /dev/null +++ b/testing-modules/assertion-libraries/src/test/java/com/ossez/assertj/AssertJGuavaUnitTest.java @@ -0,0 +1,96 @@ +package com.ossez.assertj; + +import com.google.common.base.Optional; +import com.google.common.collect.ArrayListMultimap; +import com.google.common.collect.HashBasedTable; +import com.google.common.collect.Multimap; +import com.google.common.collect.Multimaps; +import com.google.common.collect.Range; +import com.google.common.collect.Table; +import com.google.common.collect.TreeRangeMap; +import com.google.common.io.Files; +import org.assertj.guava.data.MapEntry; +import org.junit.Test; + +import java.io.File; +import java.util.HashMap; +import java.util.HashSet; + +import static org.assertj.guava.api.Assertions.assertThat; +import static org.assertj.guava.api.Assertions.entry; + +public class AssertJGuavaUnitTest { + + @Test + public void givenTwoEmptyFiles_whenComparingContent_thenEqual() throws Exception { + final File temp1 = File.createTempFile("bael", "dung1"); + final File temp2 = File.createTempFile("bael", "dung2"); + + assertThat(Files.asByteSource(temp1)).hasSize(0).hasSameContentAs(Files.asByteSource(temp2)); + } + + @Test + public void givenMultimap_whenVerifying_thenCorrect() throws Exception { + final Multimap mmap = ArrayListMultimap.create(); + mmap.put(1, "one"); + mmap.put(1, "1"); + + assertThat(mmap).hasSize(2).containsKeys(1).contains(entry(1, "one")).contains(entry(1, "1")); + } + + @Test + public void givenMultimaps_whenVerifyingContent_thenCorrect() throws Exception { + final Multimap mmap1 = ArrayListMultimap.create(); + mmap1.put(1, "one"); + mmap1.put(1, "1"); + mmap1.put(2, "two"); + mmap1.put(2, "2"); + + final Multimap mmap1_clone = Multimaps.newSetMultimap(new HashMap<>(), HashSet::new); + mmap1_clone.put(1, "one"); + mmap1_clone.put(1, "1"); + mmap1_clone.put(2, "two"); + mmap1_clone.put(2, "2"); + + final Multimap mmap2 = Multimaps.newSetMultimap(new HashMap<>(), HashSet::new); + mmap2.put(1, "one"); + mmap2.put(1, "1"); + + assertThat(mmap1).containsAllEntriesOf(mmap2).containsAllEntriesOf(mmap1_clone).hasSameEntriesAs(mmap1_clone); + } + + @Test + public void givenOptional_whenVerifyingContent_thenShouldBeEqual() throws Exception { + final Optional something = Optional.of("something"); + + assertThat(something).isPresent().extractingValue().isEqualTo("something"); + } + + @Test + public void givenRange_whenVerifying_thenShouldBeCorrect() throws Exception { + final Range range = Range.openClosed("a", "g"); + + assertThat(range).hasOpenedLowerBound().isNotEmpty().hasClosedUpperBound().contains("b"); + } + + @Test + public void givenRangeMap_whenVerifying_thenShouldBeCorrect() throws Exception { + final TreeRangeMap map = TreeRangeMap.create(); + + map.put(Range.closed(0, 60), "F"); + map.put(Range.closed(61, 70), "D"); + + assertThat(map).isNotEmpty().containsKeys(0).contains(MapEntry.entry(34, "F")); + } + + @Test + public void givenTable_whenVerifying_thenShouldBeCorrect() throws Exception { + final Table table = HashBasedTable.create(2, 2); + + table.put(1, "A", "PRESENT"); + table.put(1, "B", "ABSENT"); + + assertThat(table).hasRowCount(1).containsValues("ABSENT").containsCell(1, "B", "ABSENT"); + } + +} diff --git a/testing-modules/assertion-libraries/src/test/java/com/ossez/assertj/AssertJJava8UnitTest.java b/testing-modules/assertion-libraries/src/test/java/com/ossez/assertj/AssertJJava8UnitTest.java new file mode 100644 index 0000000000..7cc8453236 --- /dev/null +++ b/testing-modules/assertion-libraries/src/test/java/com/ossez/assertj/AssertJJava8UnitTest.java @@ -0,0 +1,108 @@ +package com.ossez.assertj; + +import org.junit.Test; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.function.Predicate; + +import static java.time.LocalDate.ofYearDay; +import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThat; + +public class AssertJJava8UnitTest { + + @Test + public void givenOptional_shouldAssert() throws Exception { + final Optional givenOptional = Optional.of("something"); + + assertThat(givenOptional).isPresent().hasValue("something"); + } + + @Test + public void givenPredicate_shouldAssert() throws Exception { + final Predicate predicate = s -> s.length() > 4; + + assertThat(predicate).accepts("aaaaa", "bbbbb").rejects("a", "b").acceptsAll(asList("aaaaa", "bbbbb")).rejectsAll(asList("a", "b")); + } + + @Test + public void givenLocalDate_shouldAssert() throws Exception { + final LocalDate givenLocalDate = LocalDate.of(2016, 7, 8); + final LocalDate todayDate = LocalDate.now(); + + assertThat(givenLocalDate).isBefore(LocalDate.of(2020, 7, 8)).isAfterOrEqualTo(LocalDate.of(1989, 7, 8)); + + assertThat(todayDate).isAfter(LocalDate.of(1989, 7, 8)).isToday(); + } + + @Test + public void givenLocalDateTime_shouldAssert() throws Exception { + final LocalDateTime givenLocalDate = LocalDateTime.of(2016, 7, 8, 12, 0); + + assertThat(givenLocalDate).isBefore(LocalDateTime.of(2020, 7, 8, 11, 2)); + } + + @Test + public void givenLocalTime_shouldAssert() throws Exception { + final LocalTime givenLocalTime = LocalTime.of(12, 15); + + assertThat(givenLocalTime).isAfter(LocalTime.of(1, 0)).hasSameHourAs(LocalTime.of(12, 0)); + } + + @Test + public void givenList_shouldAssertFlatExtracting() throws Exception { + final List givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6)); + + assertThat(givenList).flatExtracting(LocalDate::getYear).contains(2015); + } + + @Test + public void givenList_shouldAssertFlatExtractingLeapYear() throws Exception { + final List givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6)); + + assertThat(givenList).flatExtracting(LocalDate::isLeapYear).contains(true); + } + + @Test + public void givenList_shouldAssertFlatExtractingClass() throws Exception { + final List givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6)); + + assertThat(givenList).flatExtracting(Object::getClass).contains(LocalDate.class); + } + + @Test + public void givenList_shouldAssertMultipleFlatExtracting() throws Exception { + final List givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6)); + + assertThat(givenList).flatExtracting(LocalDate::getYear, LocalDate::getDayOfMonth).contains(2015, 6); + } + + @Test + public void givenString_shouldSatisfy() throws Exception { + final String givenString = "someString"; + + assertThat(givenString).satisfies(s -> { + assertThat(s).isNotEmpty(); + assertThat(s).hasSize(10); + }); + } + + @Test + public void givenString_shouldMatch() throws Exception { + final String emptyString = ""; + + assertThat(emptyString).matches(String::isEmpty); + } + + @Test + public void givenList_shouldHasOnlyOneElementSatisfying() throws Exception { + final List givenList = Arrays.asList(""); + + assertThat(givenList).hasOnlyOneElementSatisfying(s -> assertThat(s).isEmpty()); + } +} diff --git a/testing-modules/assertion-libraries/src/test/java/com/ossez/assertj/custom/AssertJCustomAssertionsUnitTest.java b/testing-modules/assertion-libraries/src/test/java/com/ossez/assertj/custom/AssertJCustomAssertionsUnitTest.java new file mode 100644 index 0000000000..eaec9f03b0 --- /dev/null +++ b/testing-modules/assertion-libraries/src/test/java/com/ossez/assertj/custom/AssertJCustomAssertionsUnitTest.java @@ -0,0 +1,43 @@ +package com.ossez.assertj.custom; + +import static org.junit.Assert.fail; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +public class AssertJCustomAssertionsUnitTest { + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void whenPersonNameMatches_thenCorrect() { + Person person = new Person("John Doe", 20); + Assertions.assertThat(person).hasFullName("John Doe"); + } + + @Test + public void whenPersonAgeLessThanEighteen_thenNotAdult() { + Person person = new Person("Jane Roe", 16); + + try { + Assertions.assertThat(person).isAdult(); + fail(); + } catch (AssertionError e) { + org.assertj.core.api.Assertions.assertThat(e).hasMessage("Expected person to be adult"); + } + } + + @Test + public void whenPersonDoesNotHaveAMatchingNickname_thenIncorrect() { + Person person = new Person("John Doe", 20); + person.addNickname("Nick"); + + try { + Assertions.assertThat(person).hasNickname("John"); + fail(); + } catch (AssertionError e) { + org.assertj.core.api.Assertions.assertThat(e).hasMessage("Expected person to have nickname John"); + } + } +} diff --git a/testing-modules/assertion-libraries/src/test/java/com/ossez/assertj/custom/Assertions.java b/testing-modules/assertion-libraries/src/test/java/com/ossez/assertj/custom/Assertions.java new file mode 100644 index 0000000000..13f3ad4086 --- /dev/null +++ b/testing-modules/assertion-libraries/src/test/java/com/ossez/assertj/custom/Assertions.java @@ -0,0 +1,9 @@ +package com.ossez.assertj.custom; + +public class Assertions { + public static PersonAssert assertThat(Person actual) { + return new PersonAssert(actual); + } + + // static factory methods of other assertion classes +} diff --git a/testing-modules/assertion-libraries/src/test/java/com/ossez/assertj/custom/PersonAssert.java b/testing-modules/assertion-libraries/src/test/java/com/ossez/assertj/custom/PersonAssert.java new file mode 100644 index 0000000000..ab99d59f4c --- /dev/null +++ b/testing-modules/assertion-libraries/src/test/java/com/ossez/assertj/custom/PersonAssert.java @@ -0,0 +1,38 @@ +package com.ossez.assertj.custom; + +import org.assertj.core.api.AbstractAssert; + +public class PersonAssert extends AbstractAssert { + + public PersonAssert(Person actual) { + super(actual, PersonAssert.class); + } + + public static PersonAssert assertThat(Person actual) { + return new PersonAssert(actual); + } + + public PersonAssert hasFullName(String fullName) { + isNotNull(); + if (!actual.getFullName().equals(fullName)) { + failWithMessage("Expected person to have full name %s but was %s", fullName, actual.getFullName()); + } + return this; + } + + public PersonAssert isAdult() { + isNotNull(); + if (actual.getAge() < 18) { + failWithMessage("Expected person to be adult"); + } + return this; + } + + public PersonAssert hasNickname(String nickName) { + isNotNull(); + if (!actual.getNicknames().contains(nickName)) { + failWithMessage("Expected person to have nickname %s", nickName); + } + return this; + } +} diff --git a/testing-modules/assertion-libraries/src/test/java/com/ossez/assertj/exceptions/Java7StyleAssertions.java b/testing-modules/assertion-libraries/src/test/java/com/ossez/assertj/exceptions/Java7StyleAssertions.java new file mode 100644 index 0000000000..6bd84be141 --- /dev/null +++ b/testing-modules/assertion-libraries/src/test/java/com/ossez/assertj/exceptions/Java7StyleAssertions.java @@ -0,0 +1,24 @@ +package com.ossez.assertj.exceptions; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; + +import org.junit.Test; + +public class Java7StyleAssertions { + + @Test + public void whenDividingByZero_thenArithmeticException() { + try { + int numerator = 10; + int denominator = 0; + int quotient = numerator / denominator; + fail("ArithmeticException expected because dividing by zero yields an ArithmeticException."); + failBecauseExceptionWasNotThrown(ArithmeticException.class); + } catch (Exception e) { + assertThat(e).hasMessage("/ by zero"); + assertThat(e).isInstanceOf(ArithmeticException.class); + } + } +} diff --git a/testing-modules/assertion-libraries/src/test/java/com/ossez/assertj/exceptions/Java8StyleAssertions.java b/testing-modules/assertion-libraries/src/test/java/com/ossez/assertj/exceptions/Java8StyleAssertions.java new file mode 100644 index 0000000000..266e4e5c73 --- /dev/null +++ b/testing-modules/assertion-libraries/src/test/java/com/ossez/assertj/exceptions/Java8StyleAssertions.java @@ -0,0 +1,66 @@ +package com.ossez.assertj.exceptions; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.catchThrowable; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import org.junit.Test; + +public class Java8StyleAssertions { + + @Test + public void whenGettingOutOfBoundsItem_thenIndexOutOfBoundsException() { + assertThatThrownBy(() -> { + ArrayList myStringList = new ArrayList(Arrays.asList("Strine one", "String two")); + myStringList.get(2); + }).isInstanceOf(IndexOutOfBoundsException.class) + .hasMessageStartingWith("Index: 2") + .hasMessageContaining("2") + .hasMessageEndingWith("Size: 2") + .hasMessageContaining("Index: 2, Size: 2") + .hasMessage("Index: %s, Size: %s", 2, 2) + .hasMessageMatching("Index: \\d+, Size: \\d+") + .hasNoCause(); + } + + @Test + public void whenWrappingException_thenCauseInstanceOfWrappedExceptionType() { + assertThatThrownBy(() -> { + try { + throw new IOException(); + } catch (IOException e) { + throw new RuntimeException(e); + } + }).isInstanceOf(RuntimeException.class) + .hasCauseInstanceOf(IOException.class) + .hasStackTraceContaining("IOException"); + } + + @Test + public void whenDividingByZero_thenArithmeticException() { + assertThatExceptionOfType(ArithmeticException.class).isThrownBy(() -> { + int numerator = 10; + int denominator = 0; + int quotient = numerator / denominator; + }) + .withMessageContaining("/ by zero"); + + // Alternatively: + + // when + Throwable thrown = catchThrowable(() -> { + int numerator = 10; + int denominator = 0; + int quotient = numerator / denominator; + }); + + // then + assertThat(thrown).isInstanceOf(ArithmeticException.class) + .hasMessageContaining("/ by zero"); + + } +} diff --git a/testing-modules/assertion-libraries/src/test/java/com/ossez/jgotesting/JGoTestingUnitTest.java b/testing-modules/assertion-libraries/src/test/java/com/ossez/jgotesting/JGoTestingUnitTest.java new file mode 100644 index 0000000000..a7720da5b7 --- /dev/null +++ b/testing-modules/assertion-libraries/src/test/java/com/ossez/jgotesting/JGoTestingUnitTest.java @@ -0,0 +1,93 @@ +package com.ossez.jgotesting; + +import java.io.File; +import static org.hamcrest.Matchers.equalToIgnoringCase; +import static org.hamcrest.Matchers.is; +import org.jgotesting.rule.JGoTestRule; +import static org.jgotesting.Assert.*; // same methods as org.junit.Assert.* +import static org.jgotesting.Check.*; // ditto, with different names +import static org.jgotesting.Testing.*; +import org.jgotesting.Checker; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; + +public class JGoTestingUnitTest { + @Rule + public final JGoTestRule test = new JGoTestRule(); + + @Test + public void whenComparingIntegers_thenEqual() { + int anInt = 10; + + assertEquals(anInt, 10); + checkEquals(anInt, 10); + } + + @Ignore + @Test + public void whenComparingNumbers_thenLoggedMessage() { + log("There was something wrong when comparing numbers"); + + int anInt = 10; + int anotherInt = 10; + + checkEquals(anInt, 10); + checkTrue("First number should be bigger", 10 > anotherInt); + checkSame(anInt, anotherInt); + } + + @Ignore + @Test + public void whenComparingNumbers_thenFormattedMessage() { + int anInt = 10; + int anotherInt = 10; + + logf("There was something wrong when comparing numbers %d and %d", anInt, anotherInt); + + checkEquals(anInt, 10); + checkTrue("First number should be bigger", 10 > anotherInt); + checkSame(anInt, anotherInt); + } + + @Test + public void whenComparingStrings_thenMultipleAssertions() { + String aString = "This is a string"; + String anotherString = "This Is A String"; + + test.check(aString, equalToIgnoringCase(anotherString)) + .check(aString.length() == 16) + .check(aString.startsWith("This")); + } + + @Ignore + @Test + public void whenComparingStrings_thenMultipleFailingAssertions() { + String aString = "the test string"; + String anotherString = "The Test String"; + + checkEquals("Strings are not equal!", aString, anotherString); + checkTrue("String is longer than one character", aString.length() == 1); + checkSame("Strings are not the same", aString, anotherString); + } + + @Ignore + @Test + public void givenFile_whenDoesnotExists_thenTerminated() throws Exception { + File aFile = new File("a_dummy_file.txt"); + terminateIf(aFile.exists(), is(false)); + + // This doesn't get executed + checkEquals(aFile.getName(), "a_dummy_file.txt"); + } + + @Test + public void givenChecker_whenComparingStrings_thenEqual() throws Exception { + Checker aChecker = s -> s.matches("\\d+"); + + String aString = "1235"; + test.check(aString, aChecker); + } + +} + diff --git a/testing-modules/assertion-libraries/src/test/java/com/ossez/jspec/CageUnitTest.java b/testing-modules/assertion-libraries/src/test/java/com/ossez/jspec/CageUnitTest.java new file mode 100644 index 0000000000..8dab2b6e6b --- /dev/null +++ b/testing-modules/assertion-libraries/src/test/java/com/ossez/jspec/CageUnitTest.java @@ -0,0 +1,126 @@ +package com.ossez.jspec; + +import static org.javalite.test.jspec.JSpec.$; +import static org.javalite.test.jspec.JSpec.expect; +import static org.javalite.test.jspec.JSpec.the; + +import java.util.Set; + +import org.javalite.test.jspec.DifferenceExpectation; +import org.junit.Test; + +public class CageUnitTest { + + Cat tomCat = new Cat("Tom"); + Cat felixCat = new Cat("Felix"); + Dog boltDog = new Dog("Bolt"); + Cage cage = new Cage(); + + + @Test + public void puttingAnimals_shouldIncreaseCageSize() { + // When + cage.put(tomCat, boltDog); + + // Then + the(cage.size()).shouldEqual(2); + } + + @Test + public void releasingAnimals_shouldDecreaseCageSize() { + // When + cage.put(tomCat, boltDog); + cage.release(tomCat); + + // Then + the(cage.size()).shouldEqual(1); + } + + @Test + public void puttingAnimals_shouldLeaveThemInsideTheCage() { + // When + cage.put(tomCat, boltDog); + + // Then + the(cage).shouldHave("animals"); + } + + @Test + public void openingTheCage_shouldReleaseAllAnimals() { + // When + cage.put(tomCat, boltDog); + + // Then + the(cage).shouldNotBe("empty"); + + // When + cage.open(); + + // Then + the(cage).shouldBe("empty"); + the(cage.isEmpty()).shouldBeTrue(); + } + + @Test + public void comparingTwoDogs() { + // When + Dog firstDog = new Dog("Rex"); + Dog secondDog = new Dog("Rex"); + + // Then + $(firstDog).shouldEqual(secondDog); + $(firstDog).shouldNotBeTheSameAs(secondDog); + } + + @Test + public void puttingCatsOnly_shouldLetCageAnimalsToContainCats() { + // When + cage.put(tomCat, felixCat); + + // Then + Set animals = cage.getAnimals(); + the(animals).shouldContain(tomCat); + the(animals).shouldContain(felixCat); + the(animals).shouldNotContain(boltDog); + } + + @Test + public void puttingCatsOnly_shouldLetCageToContainCats() { + // When + cage.put(tomCat, felixCat); + + // Then + // Check with toString of the tested objects + the(cage).shouldContain(tomCat); + the(cage).shouldContain(felixCat); + the(cage).shouldNotContain(boltDog); + } + + @Test + public void puttingMoreAnimals_shouldChangeSize() { + // When + cage.put(tomCat, boltDog); + + // Then + expect( new DifferenceExpectation(cage.size()) { + + @Override + public Integer exec() { + cage.release(tomCat); + return cage.size(); + } + } ); + } + + + @Test + public void releasingTheDog_shouldReleaseAnAnimalOfDogType() { + // When + cage.put(boltDog); + Animal releasedAnimal = cage.release(boltDog); + + // Then + the(releasedAnimal).shouldNotBeNull(); + the(releasedAnimal).shouldBeA(Dog.class); + } +} diff --git a/testing-modules/assertion-libraries/src/test/java/com/ossez/jspec/JSpecUnitTest.java b/testing-modules/assertion-libraries/src/test/java/com/ossez/jspec/JSpecUnitTest.java new file mode 100644 index 0000000000..37f5dd9d78 --- /dev/null +++ b/testing-modules/assertion-libraries/src/test/java/com/ossez/jspec/JSpecUnitTest.java @@ -0,0 +1,57 @@ +package com.ossez.jspec; + +import static org.javalite.test.jspec.JSpec.$; +import static org.javalite.test.jspec.JSpec.a; +import static org.javalite.test.jspec.JSpec.expect; +import static org.javalite.test.jspec.JSpec.it; +import static org.javalite.test.jspec.JSpec.the; + +import java.util.Arrays; +import java.util.List; + +import org.javalite.test.jspec.ExceptionExpectation; +import org.junit.Test; + +public class JSpecUnitTest { + + @Test + public void onePlusTwo_shouldEqualThree() { + $(1 + 2).shouldEqual(3); + a(1 + 2).shouldEqual(3); + the(1 + 2).shouldEqual(3); + it(1 + 2).shouldEqual(3); + } + + @Test + public void messageShouldContainJSpec() { + String message = "Welcome to JSpec demo"; + // The message should not be empty + the(message).shouldNotBe("empty"); + // The message should contain JSpec + the(message).shouldContain("JSpec"); + } + + public void colorsListShouldContainRed() { + List colorsList = Arrays.asList("red", "green", "blue"); + $(colorsList).shouldContain("red"); + } + + public void guessedNumberShouldEqualHiddenNumber() { + Integer guessedNumber = 11; + Integer hiddenNumber = 11; + + $(guessedNumber).shouldEqual(hiddenNumber); + $(guessedNumber).shouldNotBeTheSameAs(hiddenNumber); + } + + @Test + public void dividingByThero_shouldThrowArithmeticException() { + expect(new ExceptionExpectation(ArithmeticException.class) { + @Override + public void exec() throws ArithmeticException { + System.out.println(1 / 0); + } + } ); + } + +} diff --git a/testing-modules/assertion-libraries/src/test/java/com/ossez/truth/GoogleTruthUnitTest.java b/testing-modules/assertion-libraries/src/test/java/com/ossez/truth/GoogleTruthUnitTest.java new file mode 100644 index 0000000000..ea4471562f --- /dev/null +++ b/testing-modules/assertion-libraries/src/test/java/com/ossez/truth/GoogleTruthUnitTest.java @@ -0,0 +1,561 @@ +package com.ossez.truth; + +import com.google.common.collect.ArrayListMultimap; +import com.google.common.collect.Multimap; +import com.google.common.collect.Range; +import com.google.common.collect.Table; +import com.google.common.collect.TreeBasedTable; +import com.google.common.collect.TreeMultiset; + +import static com.google.common.truth.Truth.*; +import static com.google.common.truth.Truth8.*; +import java.math.BigDecimal; +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.regex.Pattern; +import java.util.stream.IntStream; +import java.util.stream.Stream; +import org.junit.Ignore; +import org.junit.Test; + +public class GoogleTruthUnitTest { + + @Test + public void whenComparingInteger_thenEqual() { + int anInt = 10; + + assertThat(anInt).isEqualTo(10); + } + + @Test + public void whenComparingFloat_thenIsBigger() { + float aFloat = 10.0f; + + assertThat(aFloat).isGreaterThan(1.0f); + } + + @Test + public void whenComparingDouble_thenIsSmaller() { + double aDouble = 10.0f; + + assertThat(aDouble).isLessThan(20.0); + } + + @Test + public void whenComparingFloat_thenWithinPrecision() { + float aFloat = 23.04f; + + assertThat(aFloat).isWithin(1.3f) + .of(23.3f); + } + + @Test + public void whenComparingFloat_thenNotWithinPrecision() { + float aFloat = 23.04f; + + assertThat(aFloat).isNotWithin(1.3f) + .of(100f); + } + + @Test + public void whenComparingDouble_thenWithinPrecision() { + double aDouble = 22.18; + + assertThat(aDouble).isWithin(2) + .of(23d); + } + + @Test + public void whenComparingDouble_thenNotWithinPrecision() { + double aDouble = 22.08; + + assertThat(aDouble).isNotWithin(2) + .of(100); + } + + @Test + public void whenComparingBigDecimal_thenEqualIgnoringScale() { + BigDecimal aBigDecimal = BigDecimal.valueOf(1000, 3); + + assertThat(aBigDecimal).isEqualToIgnoringScale(new BigDecimal(1.0)); + } + + @Test + public void whenCheckingBoolean_thenTrue() { + boolean aBoolean = true; + + assertThat(aBoolean).isTrue(); + } + + @Test + public void whenCheckingBoolean_thenFalse() { + boolean aBoolean = false; + + assertThat(aBoolean).isFalse(); + } + + @Test + public void whenComparingArrays_thenEqual() { + String[] firstArrayOfStrings = { "one", "two", "three" }; + String[] secondArrayOfStrings = { "one", "two", "three" }; + + assertThat(firstArrayOfStrings).isEqualTo(secondArrayOfStrings); + } + + @Test + public void whenComparingArrays_thenNotEqual() { + String[] firstArrayOfStrings = { "one", "two", "three" }; + String[] secondArrayOfStrings = { "three", "two", "one" }; + + assertThat(firstArrayOfStrings).isNotEqualTo(secondArrayOfStrings); + } + + @Test + public void whenCheckingArray_thenEmpty() { + Object[] anArray = {}; + + assertThat(anArray).isEmpty(); + } + + @Test + public void whenCheckingArray_thenNotEmpty() { + String[] arrayOfStrings = { "One String " }; + + assertThat(arrayOfStrings).isNotEmpty(); + } + + @Test + public void whenCheckingArrayOfDoubles_thenWithinPrecision() { + double[] arrayOfDoubles = { 1, 2, 3, 4, 5 }; + + assertThat(arrayOfDoubles).hasValuesWithin(5) + .of(6, 7, 8, 9, 10); + } + + @Test + public void whenComparingUsers_thenEqual() { + User aUser = new User("John Doe"); + User anotherUser = new User("John Doe"); + + UserSubject.assertThat(aUser).isEqualTo(anotherUser); + } + + @Test + public void whenComparingUser_thenIsNull() { + User aUser = null; + + UserSubject.assertThat(aUser).isNull(); + } + + @Test + public void whenComparingUser_thenNotNull() { + User aUser = new User(); + + UserSubject.assertThat(aUser).isNotNull(); + } + + @Test + public void whenComparingUser_thenInstanceOf() { + User aUser = new User(); + + UserSubject.assertThat(aUser).isInstanceOf(User.class); + } + + @Test + public void whenComparingUser_thenInList() { + User aUser = new User(); + + UserSubject.assertThat(aUser).isIn(Arrays.asList(1, 3, aUser, null)); + } + + @Test + public void whenComparingUser_thenNotInList() { + User aUser = new User(); + + UserSubject.assertThat(aUser).isNotIn(Arrays.asList(1, 3, "Three")); + } + + @Test + public void whenComparingNullUser_thenInList() { + User aUser = null; + User anotherUser = new User(); + + UserSubject.assertThat(aUser).isIn(Arrays.asList(1, 3, anotherUser, null)); + } + + @Test + public void whenCheckingString_thenStartsWithString() { + String aString = "This is a string"; + + assertThat(aString).startsWith("This"); + } + + @Test + public void whenCheckingString_thenContainsString() { + String aString = "This is a string"; + + assertThat(aString).contains("is a"); + } + + @Test + public void whenCheckingString_thenEndsWithString() { + String aString = "This is a string"; + + assertThat(aString).endsWith("string"); + } + + @Test + public void whenCheckingString_thenExpectedLength() { + String aString = "This is a string"; + + assertThat(aString).hasLength(16); + } + + @Test + public void whenCheckingString_thenEmpty() { + String aString = ""; + + assertThat(aString).isEmpty(); + } + + @Test + public void whenCheckingString_thenMatches() { + String aString = "The string to match"; + + assertThat(aString).matches(Pattern.compile("[a-zA-Z\\s]+")); + } + + @Test + public void whenCheckingComparable_thenAtLeast() { + Comparable aComparable = 5; + + assertThat(aComparable).isAtLeast(1); + } + + @Test + public void whenCheckingComparable_thenAtMost() { + Comparable aComparable = 5; + + assertThat(aComparable).isAtMost(10); + } + + @Test + public void whenCheckingComparable_thenInList() { + Comparable aComparable = 5; + + assertThat(aComparable).isIn(Arrays.asList(4, 5, 6)); + } + + @Test + public void whenCheckingComparable_thenInRange() { + Comparable aComparable = 5; + + assertThat(aComparable).isIn(Range.closed(1, 10)); + } + + @Test + public void whenCheckingComparable_thenNotInRange() { + Comparable aComparable = 5; + + assertThat(aComparable).isNotIn(Range.closed(10, 15)); + } + + @Test + public void whenComparingUsers_thenEquivalent() { + User aUser = new User(); + aUser.setName("John Doe"); + + User anotherUser = new User(); + anotherUser.setName("john doe"); + + UserSubject.assertThat(aUser).isEquivalentAccordingToCompareTo(anotherUser); + } + + @Test + public void whenCheckingIterable_thenContains() { + List aList = Arrays.asList(4, 5, 6); + + assertThat(aList).contains(5); + } + + @Test + public void whenCheckingIterable_thenDoesNotContains() { + List aList = Arrays.asList(4, 5, 6); + + assertThat(aList).doesNotContain(9); + } + + @Test + public void whenCheckingIterable_thenContainsAny() { + List aList = Arrays.asList(4, 5, 6); + + assertThat(aList).containsAnyOf(0, 5, 10); + } + + @Test + public void whenCheckingIterable_thenContainsAnyInList() { + List aList = Arrays.asList(1, 2, 3); + + assertThat(aList).containsAnyIn(Arrays.asList(1, 5, 10)); + } + + @Test + public void whenCheckingIterable_thenNoDuplicates() { + List aList = Arrays.asList(-2, -1, 0, 1, 2); + + assertThat(aList).containsNoDuplicates(); + } + + @Test + public void whenCheckingIterable_thenContainsNoneOf() { + List aList = Arrays.asList(4, 5, 6); + + assertThat(aList).containsNoneOf(9, 8, 7); + } + + @Test + public void whenCheckingIterable_thenContainsNoneIn() { + List aList = Arrays.asList(4, 5, 6); + + assertThat(aList).containsNoneIn(Arrays.asList(9, 10, 11)); + } + + @Test + public void whenCheckingIterable_thenContainsExactElements() { + List aList = Arrays.asList("10", "20", "30"); + List anotherList = Arrays.asList("10", "20", "30"); + + assertThat(aList).containsExactlyElementsIn(anotherList) + .inOrder(); + } + + @Test + public void whenCheckingIterable_thenOrdered() { + Set aSet = new LinkedHashSet<>(Arrays.asList("one", "three", "two")); + + assertThat(aSet).isOrdered(); + } + + @Test + public void givenComparator_whenCheckingIterable_thenOrdered() { + Comparator aComparator = (a, b) -> new Float(a).compareTo(new Float(b)); + + List aList = Arrays.asList("1", "012", "0020", "100"); + + assertThat(aList).isOrdered(aComparator); + } + + @Test + public void whenCheckingMap_thenContainsEntry() { + Map aMap = new HashMap<>(); + aMap.put("one", 1L); + + assertThat(aMap).containsEntry("one", 1L); + } + + @Test + public void whenCheckingMap_thenContainsKey() { + Map map = new HashMap<>(); + map.put("one", 1L); + + assertThat(map).containsKey("one"); + } + + @Test + public void whenCheckingMap_thenContainsEntries() { + Map aMap = new HashMap<>(); + aMap.put("first", 1L); + aMap.put("second", 2.0); + aMap.put("third", 3f); + + Map anotherMap = new HashMap<>(aMap); + + assertThat(aMap).containsExactlyEntriesIn(anotherMap); + } + + @Test + public void whenCheckingException_thenInstanceOf() { + Exception anException = new IllegalArgumentException(new NumberFormatException()); + + assertThat(anException).hasCauseThat() + .isInstanceOf(NumberFormatException.class); + } + + @Test + public void whenCheckingException_thenCauseMessageIsKnown() { + Exception anException = new IllegalArgumentException("Bad value"); + + assertThat(anException).hasMessageThat() + .startsWith("Bad"); + } + + @Test + public void whenCheckingClass_thenIsAssignable() { + Class aClass = Double.class; + + assertThat(aClass).isAssignableTo(Number.class); + } + + // Java 8 Tests + @Test + public void whenCheckingJavaOptional_thenHasValue() { + Optional anOptional = Optional.of(1); + + assertThat(anOptional).hasValue(1); + } + + @Test + public void whenCheckingJavaOptional_thenPresent() { + Optional anOptional = Optional.of("Baeldung"); + + assertThat(anOptional).isPresent(); + } + + @Test + public void whenCheckingJavaOptional_thenEmpty() { + Optional anOptional = Optional.empty(); + + assertThat(anOptional).isEmpty(); + } + + @Test + public void whenCheckingStream_thenContainsInOrder() { + Stream anStream = Stream.of(1, 2, 3); + + assertThat(anStream).containsAllOf(1, 2, 3) + .inOrder(); + } + + @Test + public void whenCheckingStream_thenDoesNotContain() { + Stream anStream = IntStream.range(1, 100) + .boxed(); + + assertThat(anStream).doesNotContain(0); + } + + // Guava Tests + @Test + public void whenCheckingGuavaOptional_thenIsAbsent() { + com.google.common.base.Optional anOptional = com.google.common.base.Optional.absent(); + + assertThat(anOptional).isAbsent(); + } + + @Test + public void whenCheckingGuavaMultimap_thenExpectedSize() { + Multimap aMultimap = ArrayListMultimap.create(); + aMultimap.put("one", 1L); + aMultimap.put("one", 2.0); + + assertThat(aMultimap).valuesForKey("one") + .hasSize(2); + } + + @Test + public void whenCheckingGuavaMultiset_thenExpectedCount() { + TreeMultiset aMultiset = TreeMultiset.create(); + aMultiset.add("baeldung", 10); + + assertThat(aMultiset).hasCount("baeldung", 10); + } + + @Test + public void whenCheckingGuavaTable_thenContains() { + Table aTable = getDummyGuavaTable(); + + assertThat(aTable).contains("firstRow", "firstColumn"); + } + + @Test + public void whenCheckingGuavaTable_thenContainsCell() { + Table aTable = getDummyGuavaTable(); + + assertThat(aTable).containsCell("firstRow", "firstColumn", "baeldung"); + } + + @Test + public void whenCheckingGuavaTable_thenContainsRow() { + Table aTable = getDummyGuavaTable(); + + assertThat(aTable).containsRow("firstRow"); + } + + @Test + public void whenCheckingGuavaTable_thenContainsColumn() { + Table aTable = getDummyGuavaTable(); + + assertThat(aTable).containsColumn("firstColumn"); + } + + @Test + public void whenCheckingGuavaTable_thenContainsValue() { + Table aTable = getDummyGuavaTable(); + + assertThat(aTable).containsValue("baeldung"); + } + + @Ignore + @Test + public void whenFailingAssertion_thenMessagePrefix() { + User aUser = new User(); + + UserSubject.assertThat(aUser).named("User [%s]", aUser.getName()) + .isNull(); + } + + @Ignore + @Test + public void whenFailingAssertion_thenCustomMessage() { + User aUser = new User(); + + assertWithMessage("TEST-985: Secret user subject was NOT null!").that(aUser) + .isNull(); + } + + @Ignore + @Test + public void whenFailingAssertion_thenCustomMessageAndPrefix() { + User aUser = new User(); + + assertWithMessage("TEST-985: Secret user subject was NOT null!").that(aUser) + .named("User [%s]", aUser.getName()) + .isNull(); + } + + private Table getDummyGuavaTable() { + Table aTable = TreeBasedTable.create(); + aTable.put("firstRow", "firstColumn", "baeldung"); + return aTable; + } + + // Custom User type + @Test + public void whenCheckingUser_thenHasName() { + User aUser = new User(); + + UserSubject.assertThat(aUser).hasName("John Doe"); + } + + @Test + public void whenCheckingUser_thenHasNameIgnoringCase() { + User aUser = new User(); + + UserSubject.assertThat(aUser).hasNameIgnoringCase("john doe"); + } + + @Test + public void givenUser_whenCheckingEmails_thenExpectedSize() { + User aUser = new User(); + + UserSubject.assertThat(aUser).emails() + .hasSize(2); + } + +}