添加断言库的测试类
This commit is contained in:
parent
e63fc82dbb
commit
c9fd41936a
|
@ -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)
|
|
@ -0,0 +1,85 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>assertion-libraries</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
<name>assertion-libraries</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.ossez</groupId>
|
||||
<artifactId>testing-modules</artifactId>
|
||||
<version>0.0.2-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.google.truth</groupId>
|
||||
<artifactId>truth</artifactId>
|
||||
<version>${truth.version}</version>
|
||||
<exclusions>
|
||||
<!-- junit4 dependency is excluded as it should to be resolved from junit-vintage-engine
|
||||
included in parent-modules. -->
|
||||
<exclusion>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.truth.extensions</groupId>
|
||||
<artifactId>truth-java8-extension</artifactId>
|
||||
<version>${truth.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-guava</artifactId>
|
||||
<version>${assertj-guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.javalite</groupId>
|
||||
<artifactId>javalite-common</artifactId>
|
||||
<version>${javalite.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jgotesting</groupId>
|
||||
<artifactId>jgotesting</artifactId>
|
||||
<version>${jgotesting.version}</version>
|
||||
<scope>test</scope>
|
||||
<exclusions>
|
||||
<!-- junit4 dependency is excluded as it should to be resolved from junit-vintage-engine
|
||||
included in parent-modules. -->
|
||||
<exclusion>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-assertions-generator-maven-plugin</artifactId>
|
||||
<version>${assertj-generator.version}</version>
|
||||
<configuration>
|
||||
<classes>
|
||||
<param>com.baeldung.testing.assertj.custom.Person</param>
|
||||
</classes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<truth.version>0.32</truth.version>
|
||||
<assertj-guava.version>3.4.0</assertj-guava.version>
|
||||
<assertj-generator.version>2.1.0</assertj-generator.version>
|
||||
<javalite.version>1.4.13</javalite.version>
|
||||
<jgotesting.version>0.12</jgotesting.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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<String> 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<String> getNicknames() {
|
||||
return nicknames;
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -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<Animal> 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<Animal> getAnimals() {
|
||||
return this.animals;
|
||||
}
|
||||
|
||||
public int size() {
|
||||
return animals.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Cage [animals=" + animals + "]";
|
||||
}
|
||||
|
||||
}
|
|
@ -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 + "]";
|
||||
}
|
||||
|
||||
}
|
|
@ -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 + "]";
|
||||
}
|
||||
|
||||
}
|
|
@ -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<User> {
|
||||
private String name = "John Doe";
|
||||
private List<String> 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<String> getEmails() {
|
||||
return emails;
|
||||
}
|
||||
|
||||
public void setEmails(List<String> 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());
|
||||
}
|
||||
|
||||
}
|
|
@ -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<UserSubject, User> {
|
||||
|
||||
private UserSubject(FailureStrategy failureStrategy, User target) {
|
||||
super(failureStrategy, target);
|
||||
}
|
||||
|
||||
private static final SubjectFactory<UserSubject, User> USER_SUBJECT_FACTORY = new SubjectFactory<UserSubject, User>() {
|
||||
@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());
|
||||
}
|
||||
|
||||
}
|
|
@ -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<Member> senior = new Condition<>(m -> m.getAge() >= 60, "senior");
|
||||
private Condition<Member> 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<Member> 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));
|
||||
}
|
||||
}
|
|
@ -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<String> list = Arrays.asList("1", "2", "3");
|
||||
|
||||
assertThat(list).contains("1");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingForElement_thenMultipleAssertions() throws Exception {
|
||||
List<String> 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<Integer, String> 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);
|
||||
}
|
||||
}
|
|
@ -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<Integer, String> 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<Integer, String> mmap1 = ArrayListMultimap.create();
|
||||
mmap1.put(1, "one");
|
||||
mmap1.put(1, "1");
|
||||
mmap1.put(2, "two");
|
||||
mmap1.put(2, "2");
|
||||
|
||||
final Multimap<Integer, String> 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<Integer, String> 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<String> something = Optional.of("something");
|
||||
|
||||
assertThat(something).isPresent().extractingValue().isEqualTo("something");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRange_whenVerifying_thenShouldBeCorrect() throws Exception {
|
||||
final Range<String> range = Range.openClosed("a", "g");
|
||||
|
||||
assertThat(range).hasOpenedLowerBound().isNotEmpty().hasClosedUpperBound().contains("b");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRangeMap_whenVerifying_thenShouldBeCorrect() throws Exception {
|
||||
final TreeRangeMap<Integer, String> 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<Integer, String, String> 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");
|
||||
}
|
||||
|
||||
}
|
|
@ -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<String> givenOptional = Optional.of("something");
|
||||
|
||||
assertThat(givenOptional).isPresent().hasValue("something");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPredicate_shouldAssert() throws Exception {
|
||||
final Predicate<String> 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<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
||||
|
||||
assertThat(givenList).flatExtracting(LocalDate::getYear).contains(2015);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_shouldAssertFlatExtractingLeapYear() throws Exception {
|
||||
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
||||
|
||||
assertThat(givenList).flatExtracting(LocalDate::isLeapYear).contains(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_shouldAssertFlatExtractingClass() throws Exception {
|
||||
final List<LocalDate> 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<LocalDate> 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<String> givenList = Arrays.asList("");
|
||||
|
||||
assertThat(givenList).hasOnlyOneElementSatisfying(s -> assertThat(s).isEmpty());
|
||||
}
|
||||
}
|
|
@ -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");
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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
|
||||
}
|
|
@ -0,0 +1,38 @@
|
|||
package com.ossez.assertj.custom;
|
||||
|
||||
import org.assertj.core.api.AbstractAssert;
|
||||
|
||||
public class PersonAssert extends AbstractAssert<PersonAssert, Person> {
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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<String> myStringList = new ArrayList<String>(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");
|
||||
|
||||
}
|
||||
}
|
|
@ -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<String> aChecker = s -> s.matches("\\d+");
|
||||
|
||||
String aString = "1235";
|
||||
test.check(aString, aChecker);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -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<Animal> 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<Integer>(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);
|
||||
}
|
||||
}
|
|
@ -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<String> 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>(ArithmeticException.class) {
|
||||
@Override
|
||||
public void exec() throws ArithmeticException {
|
||||
System.out.println(1 / 0);
|
||||
}
|
||||
} );
|
||||
}
|
||||
|
||||
}
|
|
@ -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<Integer> aComparable = 5;
|
||||
|
||||
assertThat(aComparable).isAtLeast(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingComparable_thenAtMost() {
|
||||
Comparable<Integer> aComparable = 5;
|
||||
|
||||
assertThat(aComparable).isAtMost(10);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingComparable_thenInList() {
|
||||
Comparable<Integer> aComparable = 5;
|
||||
|
||||
assertThat(aComparable).isIn(Arrays.asList(4, 5, 6));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingComparable_thenInRange() {
|
||||
Comparable<Integer> aComparable = 5;
|
||||
|
||||
assertThat(aComparable).isIn(Range.closed(1, 10));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingComparable_thenNotInRange() {
|
||||
Comparable<Integer> 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<Integer> aList = Arrays.asList(4, 5, 6);
|
||||
|
||||
assertThat(aList).contains(5);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingIterable_thenDoesNotContains() {
|
||||
List<Integer> aList = Arrays.asList(4, 5, 6);
|
||||
|
||||
assertThat(aList).doesNotContain(9);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingIterable_thenContainsAny() {
|
||||
List<Integer> aList = Arrays.asList(4, 5, 6);
|
||||
|
||||
assertThat(aList).containsAnyOf(0, 5, 10);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingIterable_thenContainsAnyInList() {
|
||||
List<Integer> aList = Arrays.asList(1, 2, 3);
|
||||
|
||||
assertThat(aList).containsAnyIn(Arrays.asList(1, 5, 10));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingIterable_thenNoDuplicates() {
|
||||
List<Integer> aList = Arrays.asList(-2, -1, 0, 1, 2);
|
||||
|
||||
assertThat(aList).containsNoDuplicates();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingIterable_thenContainsNoneOf() {
|
||||
List<Integer> aList = Arrays.asList(4, 5, 6);
|
||||
|
||||
assertThat(aList).containsNoneOf(9, 8, 7);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingIterable_thenContainsNoneIn() {
|
||||
List<Integer> aList = Arrays.asList(4, 5, 6);
|
||||
|
||||
assertThat(aList).containsNoneIn(Arrays.asList(9, 10, 11));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingIterable_thenContainsExactElements() {
|
||||
List<String> aList = Arrays.asList("10", "20", "30");
|
||||
List<String> anotherList = Arrays.asList("10", "20", "30");
|
||||
|
||||
assertThat(aList).containsExactlyElementsIn(anotherList)
|
||||
.inOrder();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingIterable_thenOrdered() {
|
||||
Set<String> aSet = new LinkedHashSet<>(Arrays.asList("one", "three", "two"));
|
||||
|
||||
assertThat(aSet).isOrdered();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenComparator_whenCheckingIterable_thenOrdered() {
|
||||
Comparator<String> aComparator = (a, b) -> new Float(a).compareTo(new Float(b));
|
||||
|
||||
List<String> aList = Arrays.asList("1", "012", "0020", "100");
|
||||
|
||||
assertThat(aList).isOrdered(aComparator);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingMap_thenContainsEntry() {
|
||||
Map<String, Object> aMap = new HashMap<>();
|
||||
aMap.put("one", 1L);
|
||||
|
||||
assertThat(aMap).containsEntry("one", 1L);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingMap_thenContainsKey() {
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("one", 1L);
|
||||
|
||||
assertThat(map).containsKey("one");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingMap_thenContainsEntries() {
|
||||
Map<String, Object> aMap = new HashMap<>();
|
||||
aMap.put("first", 1L);
|
||||
aMap.put("second", 2.0);
|
||||
aMap.put("third", 3f);
|
||||
|
||||
Map<String, Object> 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<Double> aClass = Double.class;
|
||||
|
||||
assertThat(aClass).isAssignableTo(Number.class);
|
||||
}
|
||||
|
||||
// Java 8 Tests
|
||||
@Test
|
||||
public void whenCheckingJavaOptional_thenHasValue() {
|
||||
Optional<Integer> anOptional = Optional.of(1);
|
||||
|
||||
assertThat(anOptional).hasValue(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingJavaOptional_thenPresent() {
|
||||
Optional<String> 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<Integer> anStream = Stream.of(1, 2, 3);
|
||||
|
||||
assertThat(anStream).containsAllOf(1, 2, 3)
|
||||
.inOrder();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingStream_thenDoesNotContain() {
|
||||
Stream<Integer> 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<String, Object> aMultimap = ArrayListMultimap.create();
|
||||
aMultimap.put("one", 1L);
|
||||
aMultimap.put("one", 2.0);
|
||||
|
||||
assertThat(aMultimap).valuesForKey("one")
|
||||
.hasSize(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingGuavaMultiset_thenExpectedCount() {
|
||||
TreeMultiset<String> aMultiset = TreeMultiset.create();
|
||||
aMultiset.add("baeldung", 10);
|
||||
|
||||
assertThat(aMultiset).hasCount("baeldung", 10);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingGuavaTable_thenContains() {
|
||||
Table<String, String, String> aTable = getDummyGuavaTable();
|
||||
|
||||
assertThat(aTable).contains("firstRow", "firstColumn");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingGuavaTable_thenContainsCell() {
|
||||
Table<String, String, String> aTable = getDummyGuavaTable();
|
||||
|
||||
assertThat(aTable).containsCell("firstRow", "firstColumn", "baeldung");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingGuavaTable_thenContainsRow() {
|
||||
Table<String, String, String> aTable = getDummyGuavaTable();
|
||||
|
||||
assertThat(aTable).containsRow("firstRow");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingGuavaTable_thenContainsColumn() {
|
||||
Table<String, String, String> aTable = getDummyGuavaTable();
|
||||
|
||||
assertThat(aTable).containsColumn("firstColumn");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingGuavaTable_thenContainsValue() {
|
||||
Table<String, String, String> 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<String, String, String> getDummyGuavaTable() {
|
||||
Table<String, String, String> 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);
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue