Merge branch 'master' into BAEL-16646-2

This commit is contained in:
Alessio Stalla
2019-10-24 13:20:08 +02:00
parent db85c8f275
commit c499158763
20506 changed files with 1643665 additions and 0 deletions
+3
View File
@@ -0,0 +1,3 @@
## Testing Modules
This is an aggregator module containing multiple modules focused on testing libraries.
@@ -0,0 +1,13 @@
## Relevant Articles
- [AssertJs 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,75 @@
<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>
<groupId>com.baeldung</groupId>
<artifactId>assertion-libraries</artifactId>
<version>0.1-SNAPSHOT</version>
<name>assertion-libraries</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>testing-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>com.google.truth</groupId>
<artifactId>truth</artifactId>
<version>${truth.version}</version>
</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.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</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>
</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.1.0</assertj-guava.version>
<assertj-core.version>3.9.0</assertj-core.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.baeldung.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.baeldung.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.baeldung.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.baeldung.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.baeldung.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.baeldung.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.baeldung.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.baeldung.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.baeldung.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.baeldung.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.baeldung.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.baeldung.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.baeldung.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.baeldung.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,44 @@
package com.baeldung.assertj.custom;
import static com.baeldung.assertj.custom.Assertions.assertThat;
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);
assertThat(person).hasFullName("John Doe");
}
@Test
public void whenPersonAgeLessThanEighteen_thenNotAdult() {
Person person = new Person("Jane Roe", 16);
try {
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 {
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.baeldung.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.baeldung.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.baeldung.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.baeldung.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.baeldung.testing.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.baeldung.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.baeldung.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.baeldung.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.baeldung.truth.UserSubject.*;
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");
assertThat(aUser).isEqualTo(anotherUser);
}
@Test
public void whenComparingUser_thenIsNull() {
User aUser = null;
assertThat(aUser).isNull();
}
@Test
public void whenComparingUser_thenNotNull() {
User aUser = new User();
assertThat(aUser).isNotNull();
}
@Test
public void whenComparingUser_thenInstanceOf() {
User aUser = new User();
assertThat(aUser).isInstanceOf(User.class);
}
@Test
public void whenComparingUser_thenInList() {
User aUser = new User();
assertThat(aUser).isIn(Arrays.asList(1, 3, aUser, null));
}
@Test
public void whenComparingUser_thenNotInList() {
User aUser = new User();
assertThat(aUser).isNotIn(Arrays.asList(1, 3, "Three"));
}
@Test
public void whenComparingNullUser_thenInList() {
User aUser = null;
User anotherUser = new User();
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");
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();
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();
assertThat(aUser).hasName("John Doe");
}
@Test
public void whenCheckingUser_thenHasNameIgnoringCase() {
User aUser = new User();
assertThat(aUser).hasNameIgnoringCase("john doe");
}
@Test
public void givenUser_whenCheckingEmails_thenExpectedSize() {
User aUser = new User();
assertThat(aUser).emails()
.hasSize(2);
}
}
+3
View File
@@ -0,0 +1,3 @@
## Relevant Articles:
- [Quick Guide to EasyRandom in Java](https://www.baeldung.com/java-easy-random)
+28
View File
@@ -0,0 +1,28 @@
<?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>easy-random</artifactId>
<name>easy-random</name>
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.jeasy</groupId>
<artifactId>easy-random-core</artifactId>
<version>${easy-random-core.version}</version>
</dependency>
</dependencies>
<properties>
<easy-random-core.version>4.0.0</easy-random-core.version>
</properties>
</project>
@@ -0,0 +1,17 @@
package org.baeldung.easy.random.model;
import java.util.StringJoiner;
public class Department {
private String depName;
public Department(String depName) {
this.depName = depName;
}
@Override
public String toString() {
return new StringJoiner(", ", Department.class.getSimpleName() + "[", "]").add("depName='" + depName + "'")
.toString();
}
}
@@ -0,0 +1,70 @@
package org.baeldung.easy.random.model;
import java.util.*;
public class Employee {
private long id;
private String firstName;
private String lastName;
private Department department;
private Collection<Employee> coworkers;
private Map<YearQuarter, Grade> quarterGrades;
public Employee(long id, String firstName, String lastName, Department department) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.department = department;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Employee employee = (Employee) o;
return id == employee.id;
}
@Override
public int hashCode() {
return Objects.hash(id);
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public long getId() {
return id;
}
public Department getDepartment() {
return department;
}
public Collection<Employee> getCoworkers() {
return Collections.unmodifiableCollection(coworkers);
}
public Map<YearQuarter, Grade> getQuarterGrades() {
return Collections.unmodifiableMap(quarterGrades);
}
@Override
public String toString() {
return new StringJoiner(", ", Employee.class.getSimpleName() + "[", "]").add("id=" + id)
.add("firstName='" + firstName + "'")
.add("lastName='" + lastName + "'")
.add("department=" + department)
.add("coworkers size=" + ((coworkers == null) ? 0 : coworkers.size()))
.add("quarterGrades=" + quarterGrades)
.toString();
}
}
@@ -0,0 +1,22 @@
package org.baeldung.easy.random.model;
import java.util.StringJoiner;
public class Grade {
private int grade;
public Grade(int grade) {
this.grade = grade;
}
public int getGrade() {
return grade;
}
@Override
public String toString() {
return new StringJoiner(", ", Grade.class.getSimpleName() + "[", "]").add("grade=" + grade)
.toString();
}
}
@@ -0,0 +1,30 @@
package org.baeldung.easy.random.model;
import java.util.StringJoiner;
public class Person {
private String firstName;
private String lastName;
private Integer age;
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public Integer getAge() {
return age;
}
@Override
public String toString() {
return new StringJoiner(", ", Person.class.getSimpleName() + "[", "]").add("firstName='" + firstName + "'")
.add("lastName='" + lastName + "'")
.add("age=" + age)
.toString();
}
}
@@ -0,0 +1,50 @@
package org.baeldung.easy.random.model;
import java.time.LocalDate;
import java.util.Objects;
import java.util.StringJoiner;
public class YearQuarter {
private LocalDate startDate;
private LocalDate endDate;
public YearQuarter(LocalDate startDate) {
this.startDate = startDate;
autoAdjustEndDate();
}
private void autoAdjustEndDate() {
endDate = startDate.plusMonths(3L);
}
public LocalDate getStartDate() {
return startDate;
}
public LocalDate getEndDate() {
return endDate;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
YearQuarter quarter = (YearQuarter) o;
return Objects.equals(startDate, quarter.startDate) && Objects.equals(endDate, quarter.endDate);
}
@Override
public int hashCode() {
return Objects.hash(startDate, endDate);
}
@Override
public String toString() {
return new StringJoiner(", ", YearQuarter.class.getSimpleName() + "[", "]").add("startDate=" + startDate)
.add("endDate=" + endDate)
.toString();
}
}
@@ -0,0 +1,18 @@
package org.baeldung.easy.random.randomizer;
import org.baeldung.easy.random.model.YearQuarter;
import org.jeasy.random.api.Randomizer;
import java.time.LocalDate;
import java.time.Month;
public class YearQuarterRandomizer implements Randomizer<YearQuarter> {
private LocalDate date = LocalDate.of(1990, Month.SEPTEMBER, 25);
@Override
public YearQuarter getRandomValue() {
date = date.plusMonths(3);
return new YearQuarter(date);
}
}
@@ -0,0 +1,63 @@
package org.baeldung.easy.random;
import org.baeldung.easy.random.model.Employee;
import org.baeldung.easy.random.model.Person;
import org.baeldung.easy.random.model.YearQuarter;
import org.baeldung.easy.random.randomizer.YearQuarterRandomizer;
import org.jeasy.random.EasyRandom;
import org.jeasy.random.EasyRandomParameters;
import org.jeasy.random.FieldPredicates;
import org.jeasy.random.TypePredicates;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.*;
class EasyRandomUnitTest {
@Test
void givenDefaultConfiguration_thenGenerateSingleObject() {
EasyRandom generator = new EasyRandom();
Person person = generator.nextObject(Person.class);
assertNotNull(person.getAge());
assertNotNull(person.getFirstName());
assertNotNull(person.getLastName());
}
@Test
void givenDefaultConfiguration_thenGenerateObjectsList() {
EasyRandom generator = new EasyRandom();
List<Person> persons = generator.objects(Person.class, 5)
.collect(Collectors.toList());
assertEquals(5, persons.size());
}
@Test
void givenCustomConfiguration_thenGenerateSingleEmployee() {
EasyRandomParameters parameters = new EasyRandomParameters();
parameters.stringLengthRange(3, 3);
parameters.collectionSizeRange(5, 5);
parameters.excludeField(FieldPredicates.named("lastName").and(FieldPredicates.inClass(Employee.class)));
parameters.excludeType(TypePredicates.inPackage("not.existing.pkg"));
parameters.randomize(YearQuarter.class, new YearQuarterRandomizer());
EasyRandom generator = new EasyRandom(parameters);
Employee employee = generator.nextObject(Employee.class);
assertEquals(3, employee.getFirstName().length());
assertEquals(5, employee.getCoworkers().size());
assertEquals(5, employee.getQuarterGrades().size());
assertNotNull(employee.getDepartment());
assertNull(employee.getLastName());
for (YearQuarter key : employee.getQuarterGrades().keySet()) {
assertEquals(key.getStartDate(), key.getEndDate().minusMonths(3L));
}
}
}
+3
View File
@@ -0,0 +1,3 @@
## Relevant Articles
- [Mocking a Void Method with EasyMock](https://www.baeldung.com/easymock-mocking-void-method)
+30
View File
@@ -0,0 +1,30 @@
<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<artifactId>easymock</artifactId>
<name>easymock</name>
<url>http://maven.apache.org</url>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>testing-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymock</artifactId>
<version>${easymock.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<easymock.version>4.0.2</easymock.version>
</properties>
</project>
@@ -0,0 +1,28 @@
package com.baeldung.testing.easymock;
import java.math.BigDecimal;
public class ForecastProcessor {
private WeatherService weatherService;
public BigDecimal getMaximumTemperature(String locationName) {
Location location = new Location(locationName);
try {
weatherService.populateTemperature(location);
} catch (ServiceUnavailableException e) {
return null;
}
return location.getMaximumTemparature();
}
public WeatherService getWeatherService() {
return weatherService;
}
public void setWeatherService(WeatherService weatherService) {
this.weatherService = weatherService;
}
}
@@ -0,0 +1,33 @@
package com.baeldung.testing.easymock;
import java.math.BigDecimal;
public class Location {
private String name;
private BigDecimal minimumTemperature;
private BigDecimal maximumTemparature;
public Location(String name) {
this.name = name;
}
public String getName() {
return name;
}
public BigDecimal getMinimumTemperature() {
return minimumTemperature;
}
public void setMinimumTemperature(BigDecimal minimumTemperature) {
this.minimumTemperature = minimumTemperature;
}
public BigDecimal getMaximumTemparature() {
return maximumTemparature;
}
public void setMaximumTemparature(BigDecimal maximumTemparature) {
this.maximumTemparature = maximumTemparature;
}
}
@@ -0,0 +1,7 @@
package com.baeldung.testing.easymock;
public class ServiceUnavailableException extends Exception {
private static final long serialVersionUID = 6961151537340723535L;
}
@@ -0,0 +1,5 @@
package com.baeldung.testing.easymock;
public interface WeatherService {
void populateTemperature(Location location) throws ServiceUnavailableException;
}
@@ -0,0 +1,49 @@
package com.baeldung.testing.easymock;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import java.math.BigDecimal;
import org.easymock.EasyMock;
import org.easymock.EasyMockRule;
import org.easymock.Mock;
import org.easymock.TestSubject;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
public class ForecastProcessorUnitTest {
private static int MAX_TEMP = 90;
@Rule
public EasyMockRule rule = new EasyMockRule(this);
@TestSubject
private ForecastProcessor forecastProcessor = new ForecastProcessor();
@Mock
private WeatherService mockWeatherService;
@Before
public void setUp() {
forecastProcessor.setWeatherService(mockWeatherService);
}
@SuppressWarnings("unchecked")
@Test
public void givenLocationName_whenWeatherServicePopulatesTemperatures_thenMaxTempReturned() throws ServiceUnavailableException {
mockWeatherService.populateTemperature(EasyMock.anyObject(Location.class));
EasyMock.expectLastCall()
.andAnswer(() -> {
Location passedLocation = (Location) EasyMock.getCurrentArguments()[0];
passedLocation.setMaximumTemparature(new BigDecimal(MAX_TEMP));
passedLocation.setMinimumTemperature(new BigDecimal(MAX_TEMP - 10));
return null;
});
EasyMock.replay(mockWeatherService);
BigDecimal maxTemperature = forecastProcessor.getMaximumTemperature("New York");
EasyMock.verify(mockWeatherService);
assertThat(maxTemperature, equalTo(new BigDecimal(MAX_TEMP)));
}
}
+5
View File
@@ -0,0 +1,5 @@
### Relevant Articles:
- [Intro to Gatling](http://www.baeldung.com/introduction-to-gatling)
### Running a simualtion
- To run a simulation use "simulation" profile, command - `mvn install -Psimulation -Dgib.enabled=false`
+136
View File
@@ -0,0 +1,136 @@
<?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>
<groupId>org.baeldung</groupId>
<artifactId>gatling</artifactId>
<version>1.0-SNAPSHOT</version>
<name>gatling</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.gatling</groupId>
<artifactId>gatling-app</artifactId>
<version>${gatling.version}</version>
</dependency>
<dependency>
<groupId>io.gatling</groupId>
<artifactId>gatling-recorder</artifactId>
<version>${gatling.version}</version>
</dependency>
<dependency>
<groupId>io.gatling.highcharts</groupId>
<artifactId>gatling-charts-highcharts</artifactId>
<version>${gatling.version}</version>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>${scala.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>io.gatling.highcharts</groupId>
<artifactId>gatling-charts-highcharts</artifactId>
</dependency>
<dependency>
<groupId>io.gatling</groupId>
<artifactId>gatling-app</artifactId>
</dependency>
<dependency>
<groupId>io.gatling</groupId>
<artifactId>gatling-recorder</artifactId>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
</dependency>
</dependencies>
<build>
<testSourceDirectory>src/test/scala</testSourceDirectory>
<pluginManagement>
<plugins>
<plugin>
<groupId>net.alchim31.maven</groupId>
<artifactId>scala-maven-plugin</artifactId>
<version>${scala-maven-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>net.alchim31.maven</groupId>
<artifactId>scala-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>testCompile</goal>
</goals>
<configuration>
<args>
<!--<arg>-Ybackend:GenBCode</arg> -->
<arg>-Ydelambdafy:method</arg>
<arg>-target:jvm-1.8</arg>
<arg>-deprecation</arg>
<arg>-feature</arg>
<arg>-unchecked</arg>
<arg>-language:implicitConversions</arg>
<arg>-language:postfixOps</arg>
</args>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>simulation</id>
<build>
<plugins>
<plugin>
<groupId>io.gatling</groupId>
<artifactId>gatling-maven-plugin</artifactId>
<version>${gatling-maven-plugin.version}</version>
<executions>
<execution>
<phase>test</phase>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<disableCompiler>true</disableCompiler>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<encoding>UTF-8</encoding>
<scala.version>2.12.6</scala.version> <!--2.11.12 --> <!--2.12.6 -->
<gatling.version>2.3.1</gatling.version> <!--2.2.5 --> <!--2.3.1 -->
<scala-maven-plugin.version>3.2.2</scala-maven-plugin.version> <!--3.2.2 --> <!--3.3.2 -->
<gatling-maven-plugin.version>2.2.4</gatling-maven-plugin.version> <!--2.2.1 --> <!--2.2.4 -->
</properties>
</project>
@@ -0,0 +1,127 @@
#########################
# Gatling Configuration #
#########################
# This file contains all the settings configurable for Gatling with their default values
gatling {
core {
#outputDirectoryBaseName = "" # The prefix for each simulation result folder (then suffixed by the report generation timestamp)
#runDescription = "" # The description for this simulation run, displayed in each report
#encoding = "utf-8" # Encoding to use throughout Gatling for file and string manipulation
#simulationClass = "" # The FQCN of the simulation to run (when used in conjunction with noReports, the simulation for which assertions will be validated)
#mute = false # When set to true, don't ask for simulation name nor run description (currently only used by Gatling SBT plugin)
#elFileBodiesCacheMaxCapacity = 200 # Cache size for request body EL templates, set to 0 to disable
#rawFileBodiesCacheMaxCapacity = 200 # Cache size for request body Raw templates, set to 0 to disable
#rawFileBodiesInMemoryMaxSize = 1000 # Below this limit, raw file bodies will be cached in memory
extract {
regex {
#cacheMaxCapacity = 200 # Cache size for the compiled regexes, set to 0 to disable caching
}
xpath {
#cacheMaxCapacity = 200 # Cache size for the compiled XPath queries, set to 0 to disable caching
}
jsonPath {
#cacheMaxCapacity = 200 # Cache size for the compiled jsonPath queries, set to 0 to disable caching
#preferJackson = false # When set to true, prefer Jackson over Boon for JSON-related operations
}
css {
#cacheMaxCapacity = 200 # Cache size for the compiled CSS selectors queries, set to 0 to disable caching
}
}
directory {
#data = user-files/data # Folder where user's data (e.g. files used by Feeders) is located
#bodies = user-files/bodies # Folder where bodies are located
#simulations = user-files/simulations # Folder where the bundle's simulations are located
#reportsOnly = "" # If set, name of report folder to look for in order to generate its report
#binaries = "" # If set, name of the folder where compiles classes are located: Defaults to GATLING_HOME/target.
#results = results # Name of the folder where all reports folder are located
}
}
charting {
#noReports = false # When set to true, don't generate HTML reports
#maxPlotPerSeries = 1000 # Number of points per graph in Gatling reports
#useGroupDurationMetric = false # Switch group timings from cumulated response time to group duration.
indicators {
#lowerBound = 800 # Lower bound for the requests' response time to track in the reports and the console summary
#higherBound = 1200 # Higher bound for the requests' response time to track in the reports and the console summary
#percentile1 = 50 # Value for the 1st percentile to track in the reports, the console summary and Graphite
#percentile2 = 75 # Value for the 2nd percentile to track in the reports, the console summary and Graphite
#percentile3 = 95 # Value for the 3rd percentile to track in the reports, the console summary and Graphite
#percentile4 = 99 # Value for the 4th percentile to track in the reports, the console summary and Graphite
}
}
http {
#fetchedCssCacheMaxCapacity = 200 # Cache size for CSS parsed content, set to 0 to disable
#fetchedHtmlCacheMaxCapacity = 200 # Cache size for HTML parsed content, set to 0 to disable
#perUserCacheMaxCapacity = 200 # Per virtual user cache size, set to 0 to disable
#warmUpUrl = "http://gatling.io" # The URL to use to warm-up the HTTP stack (blank means disabled)
#enableGA = true # Very light Google Analytics, please support
ssl {
keyStore {
#type = "" # Type of SSLContext's KeyManagers store
#file = "" # Location of SSLContext's KeyManagers store
#password = "" # Password for SSLContext's KeyManagers store
#algorithm = "" # Algorithm used SSLContext's KeyManagers store
}
trustStore {
#type = "" # Type of SSLContext's TrustManagers store
#file = "" # Location of SSLContext's TrustManagers store
#password = "" # Password for SSLContext's TrustManagers store
#algorithm = "" # Algorithm used by SSLContext's TrustManagers store
}
}
ahc {
#keepAlive = true # Allow pooling HTTP connections (keep-alive header automatically added)
#connectTimeout = 60000 # Timeout when establishing a connection
#pooledConnectionIdleTimeout = 60000 # Timeout when a connection stays unused in the pool
#readTimeout = 60000 # Timeout when a used connection stays idle
#maxRetry = 2 # Number of times that a request should be tried again
#requestTimeout = 60000 # Timeout of the requests
#acceptAnyCertificate = true # When set to true, doesn't validate SSL certificates
#httpClientCodecMaxInitialLineLength = 4096 # Maximum length of the initial line of the response (e.g. "HTTP/1.0 200 OK")
#httpClientCodecMaxHeaderSize = 8192 # Maximum size, in bytes, of each request's headers
#httpClientCodecMaxChunkSize = 8192 # Maximum length of the content or each chunk
#webSocketMaxFrameSize = 10240000 # Maximum frame payload size
#sslEnabledProtocols = [TLSv1.2, TLSv1.1, TLSv1] # Array of enabled protocols for HTTPS, if empty use the JDK defaults
#sslEnabledCipherSuites = [] # Array of enabled cipher suites for HTTPS, if empty use the JDK defaults
#sslSessionCacheSize = 0 # SSLSession cache size, set to 0 to use JDK's default
#sslSessionTimeout = 0 # SSLSession timeout in seconds, set to 0 to use JDK's default (24h)
#useOpenSsl = false # if OpenSSL should be used instead of JSSE (requires tcnative jar)
#useNativeTransport = false # if native transport should be used instead of Java NIO (requires netty-transport-native-epoll, currently Linux only)
#usePooledMemory = true # if Gatling should use pooled memory
#tcpNoDelay = true
#soReuseAddress = false
#soLinger = -1
#soSndBuf = -1
#soRcvBuf = -1
}
dns {
#queryTimeout = 5000 # Timeout of each DNS query in millis
#maxQueriesPerResolve = 3 # Maximum allowed number of DNS queries for a given name resolution
}
}
data {
#writers = [console, file] # The list of DataWriters to which Gatling write simulation data (currently supported : console, file, graphite, jdbc)
console {
#light = false # When set to true, displays a light version without detailed request stats
}
file {
#bufferSize = 8192 # FileDataWriter's internal data buffer size, in bytes
}
leak {
#noActivityTimeout = 30 # Period, in seconds, for which Gatling may have no activity before considering a leak may be happening
}
graphite {
#light = false # only send the all* stats
#host = "localhost" # The host where the Carbon server is located
#port = 2003 # The port to which the Carbon server listens to (2003 is default for plaintext, 2004 is default for pickle)
#protocol = "tcp" # The protocol used to send data to Carbon (currently supported : "tcp", "udp")
#rootPathPrefix = "gatling" # The common prefix of all metrics sent to Graphite
#bufferSize = 8192 # GraphiteDataWriter's internal data buffer size, in bytes
#writeInterval = 1 # GraphiteDataWriter's write interval, in seconds
}
}
}
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%-5level] %logger{15} - %msg%n%rEx</pattern>
<immediateFlush>false</immediateFlush>
</encoder>
</appender>
<!-- Uncomment for logging ALL HTTP request and responses -->
<!-- <logger name="io.gatling.http.ahc" level="TRACE" /> -->
<!-- <logger name="io.gatling.http.response" level="TRACE" /> -->
<!-- Uncomment for logging ONLY FAILED HTTP request and responses -->
<!-- <logger name="io.gatling.http.ahc" level="DEBUG" /> -->
<!-- <logger name="io.gatling.http.response" level="DEBUG" /> -->
<root level="WARN">
<appender-ref ref="CONSOLE" />
</root>
</configuration>
@@ -0,0 +1,53 @@
recorder {
core {
#mode = "Proxy"
#encoding = "utf-8" # The encoding used for reading/writing request bodies and the generated simulation
#outputFolder = "" # The folder where generated simulation will we written
#package = "" # The package's name of the generated simulation
#className = "RecordedSimulation" # The name of the generated Simulation class
#thresholdForPauseCreation = 100 # The minimum time, in milliseconds, that must pass between requests to trigger a pause creation
#saveConfig = false # When set to true, the configuration from the Recorder GUI overwrites this configuration
#headless = false # When set to true, run the Recorder in headless mode instead of the GUI
#harFilePath = "" # The path of the HAR file to convert
}
filters {
#filterStrategy = "Disabled" # The selected filter resources filter strategy (currently supported : "Disabled", "BlackList", "WhiteList")
#whitelist = [] # The list of ressources patterns that are part of the Recorder's whitelist
#blacklist = [] # The list of ressources patterns that are part of the Recorder's blacklist
}
http {
#automaticReferer = true # When set to false, write the referer + enable 'disableAutoReferer' in the generated simulation
#followRedirect = true # When set to false, write redirect requests + enable 'disableFollowRedirect' in the generated simulation
#removeCacheHeaders = true # When set to true, removes from the generated requests headers leading to request caching
#inferHtmlResources = true # When set to true, add inferred resources + set 'inferHtmlResources' with the configured blacklist/whitelist in the generated simulation
#checkResponseBodies = false # When set to true, save response bodies as files and add raw checks in the generated simulation
}
proxy {
#port = 8000 # Local port used by Gatling's Proxy for HTTP/HTTPS
https {
#mode = "SelfSignedCertificate" # The selected "HTTPS mode" (currently supported : "SelfSignedCertificate", "ProvidedKeyStore", "GatlingCertificateAuthority", "CustomCertificateAuthority")
keyStore {
#path = "" # The path of the custom key store
#password = "" # The password for this key store
#type = "JKS" # The type of the key store (currently supported: "JKS")
}
certificateAuthority {
#certificatePath = "" # The path of the custom certificate
#privateKeyPath = "" # The certificate's private key path
}
}
outgoing {
#host = "" # The outgoing proxy's hostname
#username = "" # The username to use to connect to the outgoing proxy
#password = "" # The password corresponding to the user to use to connect to the outgoing proxy
#port = 0 # The HTTP port to use to connect to the outgoing proxy
#sslPort = 0 # If set, The HTTPS port to use to connect to the outgoing proxy
}
}
netty {
#maxInitialLineLength = 10000 # Maximum length of the initial line of the response (e.g. "HTTP/1.0 200 OK")
#maxHeaderSize = 20000 # Maximum size, in bytes, of each request's headers
#maxChunkSize = 8192 # Maximum length of the content or each chunk
#maxContentLength = 100000000 # Maximum length of the aggregated content of each response
}
}
@@ -0,0 +1,13 @@
import io.gatling.app.Gatling
import io.gatling.core.config.GatlingPropertiesBuilder
object Engine extends App {
val props = new GatlingPropertiesBuilder
props.dataDirectory(IDEPathHelper.dataDirectory.toString)
props.resultsDirectory(IDEPathHelper.resultsDirectory.toString)
props.bodiesDirectory(IDEPathHelper.bodiesDirectory.toString)
props.binariesDirectory(IDEPathHelper.mavenBinariesDirectory.toString)
Gatling.fromMap(props.build)
}
@@ -0,0 +1,22 @@
import java.nio.file.Path
import io.gatling.commons.util.PathHelper._
object IDEPathHelper {
val gatlingConfUrl: Path = getClass.getClassLoader.getResource("gatling.conf").toURI
val projectRootDir = gatlingConfUrl.ancestor(3)
val mavenSourcesDirectory = projectRootDir / "src" / "test" / "scala"
val mavenResourcesDirectory = projectRootDir / "src" / "test" / "resources"
val mavenTargetDirectory = projectRootDir / "target"
val mavenBinariesDirectory = mavenTargetDirectory / "test-classes"
val dataDirectory = mavenResourcesDirectory / "data"
val bodiesDirectory = mavenResourcesDirectory / "bodies"
val recorderOutputDirectory = mavenSourcesDirectory
val resultsDirectory = mavenTargetDirectory / "gatling"
val recorderConfigFile = mavenResourcesDirectory / "recorder.conf"
}
@@ -0,0 +1,12 @@
import io.gatling.recorder.GatlingRecorder
import io.gatling.recorder.config.RecorderPropertiesBuilder
object Recorder extends App {
val props = new RecorderPropertiesBuilder
props.simulationOutputFolder(IDEPathHelper.recorderOutputDirectory.toString)
props.simulationPackage("org.baeldung")
props.bodiesFolder(IDEPathHelper.bodiesDirectory.toString)
GatlingRecorder.fromMap(props.build, Some(IDEPathHelper.recorderConfigFile))
}
@@ -0,0 +1,45 @@
package org.baeldung
import scala.concurrent.duration._
import io.gatling.core.Predef._
import io.gatling.http.Predef._
import io.gatling.jdbc.Predef._
class RecordedSimulation extends Simulation {
val httpProtocol = http
.baseURL("http://computer-database.gatling.io")
.inferHtmlResources(BlackList(""".*\.css""", """.*\.js""", """.*\.ico"""), WhiteList())
.acceptHeader("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
.acceptEncodingHeader("gzip, deflate")
.acceptLanguageHeader("it-IT,it;q=0.8,en-US;q=0.5,en;q=0.3")
.userAgentHeader("Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0")
val scn = scenario("RecordedSimulation")
.exec(http("request_0")
.get("/"))
.pause(5)
.exec(http("request_1")
.get("/computers?f=amstrad"))
.pause(4)
.exec(http("request_2")
.get("/computers/412"))
.pause(2)
.exec(http("request_3")
.get("/"))
.pause(2)
.exec(http("request_4")
.get("/computers?p=1"))
.pause(1)
.exec(http("request_5")
.get("/computers?p=2"))
.pause(2)
.exec(http("request_6")
.get("/computers?p=3"))
setUp(scn.inject(atOnceUsers(1))).protocols(httpProtocol)
}
+1
View File
@@ -0,0 +1 @@
/report-*.json
+5
View File
@@ -0,0 +1,5 @@
### Relevant articles
- [Introduction to Testing with Spock and Groovy](http://www.baeldung.com/groovy-spock)
- [Difference Between Stub, Mock, and Spy in the Spock Framework](https://www.baeldung.com/spock-stub-mock-spy)
- [Guide to Spock Extensions](https://www.baeldung.com/spock-extensions)
+56
View File
@@ -0,0 +1,56 @@
<?xml version="1.0"?>
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.spockframework</groupId>
<artifactId>groovy-spock</artifactId>
<version>1.0-SNAPSHOT</version>
<name>groovy-spock</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-core</artifactId>
<version>${spock-core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>${groovy-all.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.gmavenplus</groupId>
<artifactId>gmavenplus-plugin</artifactId>
<version>${gmavenplus-plugin.version}</version>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<spock-core.version>1.3-groovy-2.4</spock-core.version>
<groovy-all.version>2.4.7</groovy-all.version>
<gmavenplus-plugin.version>1.5</gmavenplus-plugin.version>
</properties>
</project>
@@ -0,0 +1,7 @@
package mocks;
public interface EventPublisher {
void publish(String addedOfferId);
}
@@ -0,0 +1,5 @@
package mocks;
public class ExternalItemProviderException extends RuntimeException {
}
@@ -0,0 +1,36 @@
package mocks;
import java.util.Objects;
public class Item {
private final String id;
private final String name;
public Item(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Item item = (Item) o;
return Objects.equals(id, item.id) &&
Objects.equals(name, item.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
}
@@ -0,0 +1,9 @@
package mocks;
import java.util.List;
public interface ItemProvider {
List<Item> getItems(List<String> itemIds);
}
@@ -0,0 +1,37 @@
package mocks;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class ItemService {
private final ItemProvider itemProvider;
private final EventPublisher eventPublisher;
public ItemService(ItemProvider itemProvider, EventPublisher eventPublisher) {
this.itemProvider = itemProvider;
this.eventPublisher = eventPublisher;
}
List<Item> getAllItemsSortedByName(List<String> itemIds) {
List<Item> items;
try{
items = itemProvider.getItems(itemIds);
} catch (RuntimeException ex) {
throw new ExternalItemProviderException();
}
return items.stream()
.sorted(Comparator.comparing(Item::getName))
.collect(Collectors.toList());
}
void saveItems(List<String> itemIds) {
List<String> notEmptyOfferIds = itemIds.stream()
.filter(itemId -> !itemId.isEmpty())
.collect(Collectors.toList());
// save in database
notEmptyOfferIds.forEach(eventPublisher::publish);
}
}
@@ -0,0 +1,10 @@
package mocks;
public class LoggingEventPublisher implements EventPublisher {
@Override
public void publish(String addedOfferId) {
System.out.println("I've published: " + addedOfferId);
}
}
@@ -0,0 +1,89 @@
import spock.lang.Specification
class FirstSpecification extends Specification {
def "one plus one should equal two"() {
expect:
1 + 1 == 2
}
def "two plus two should equal four"() {
given:
int left = 2
int right = 2
when:
int result = left + right
then:
result == 4
}
def "Should be able to remove from list"() {
given:
def list = [1, 2, 3, 4]
when:
list.remove(0)
then:
list == [2, 3, 4]
}
def "Should get an index out of bounds when removing a non-existent item"() {
given:
def list = [1, 2, 3, 4]
when:
list.remove(20)
then:
thrown(IndexOutOfBoundsException)
list.size() == 4
}
def "numbers to the power of two"(int a, int b, int c) {
expect:
Math.pow(a, b) == c
where:
a | b | c
1 | 2 | 1
2 | 2 | 4
3 | 2 | 9
}
def "Should return default value for mock"() {
given:
def paymentGateway = Mock(PaymentGateway)
when:
def result = paymentGateway.makePayment(12.99)
then:
!result
}
def "Should return true value for mock"() {
given:
def paymentGateway = Mock(PaymentGateway)
paymentGateway.makePayment(20) >> true
when:
def result = paymentGateway.makePayment(20)
then:
result
}
def "Should verify notify was called"() {
given:
def notifier = Mock(Notifier)
when:
notifier.notify('foo')
then:
1 * notifier.notify('foo')
}
}
@@ -0,0 +1,3 @@
interface Notifier {
void notify(String message)
}
@@ -0,0 +1,3 @@
interface PaymentGateway {
boolean makePayment(BigDecimal amount)
}
@@ -0,0 +1,20 @@
package extensions
import spock.lang.Narrative
import spock.lang.Specification
import spock.lang.Title
@Title("""This title is easy to read for humans""")
class CustomTitleTest extends Specification {
}
@Narrative("""
as a user
i want to save favourite items
and then get the list of them
""")
class NarrativeDescriptionTest extends Specification {
}
@@ -0,0 +1,22 @@
package extensions
import spock.lang.IgnoreIf
import spock.lang.Specification
class IgnoreIfTest extends Specification {
@IgnoreIf({System.getProperty("os.name").contains("windows")})
def "I won't run on windows"() {
expect:
true
}
@IgnoreIf({ os.isWindows() })
def "I'm using Spock helper classes to run only on windows"() {
expect:
true
}
}
@@ -0,0 +1,16 @@
package extensions
import spock.lang.IgnoreRest
import spock.lang.Specification
class IgnoreRestTest extends Specification {
def "I won't run"() { }
@IgnoreRest
def 'I will run'() { }
def "I won't run too"() { }
}
@@ -0,0 +1,20 @@
package extensions
import spock.lang.Ignore
import spock.lang.Specification
@Ignore
class IgnoreTest extends Specification {
@Ignore
def "I won't be executed"() {
expect:
true
}
def 'Example test'() {
expect:
true
}
}
@@ -0,0 +1,25 @@
package extensions
import spock.lang.Issue
import spock.lang.Specification
class IssueTest extends Specification {
@Issue("http://jira.org/issues/LO-531")
def 'single issue'() {
}
@Issue(["http://jira.org/issues/LO-531", "http://jira.org/issues/LO-123"])
def 'multiple issues'() {
}
@Issue("LO-1000")
def "I'm using Spock configuration file"() {
expect:
true
}
}
@@ -0,0 +1,11 @@
package extensions
import spock.lang.PendingFeature
class PendingFeatureTest {
@PendingFeature
def 'test for not implemented yet feature'() {
}
}
@@ -0,0 +1,14 @@
package extensions
import spock.lang.Requires
import spock.lang.Specification
class RequiresTest extends Specification {
@Requires({ System.getProperty("os.name").contains("windows") })
def "I will run only on Windows"() {
expect:
true
}
}
@@ -0,0 +1,18 @@
package extensions
import spock.lang.Specification
import spock.util.environment.RestoreSystemProperties
class RestoreSystemPropertiesTest extends Specification {
@RestoreSystemProperties
def 'all environment variables will be saved before execution and restored after tests'() {
given:
System.setProperty('os.name', 'Mac OS')
expect:
true
}
}
@@ -0,0 +1,20 @@
package extensions
import spock.lang.Retry
import spock.lang.Specification
@Retry
class RetryTest extends Specification {
@Retry
def 'I will retry three times'() { }
@Retry(exceptions = [RuntimeException])
def 'I will retry only on RuntimeException'() { }
@Retry(condition = { failure.message.contains('error') })
def 'I will retry with a specific message'() { }
@Retry(delay = 1000)
def 'I will retry after 1000 millis'() { }
}
@@ -0,0 +1,20 @@
package extensions
import spock.lang.See
import spock.lang.Specification
class SeeTest extends Specification {
@See("https://example.org")
def 'Look at the reference'() {
}
@See(["https://example.org/first", "https://example.org/first"])
def 'Look at the references'() {
}
}
@@ -0,0 +1,13 @@
package extensions
import org.junit.Ignore
import spock.lang.Specification
class StackTraceTest extends Specification {
def 'stkacktrace'() {
// expect:
// throw new RuntimeException("blabla")
}
}
@@ -0,0 +1,14 @@
package extensions
import spock.lang.Specification
import spock.lang.Stepwise
@Stepwise
class StepwiseTest extends Specification {
def 'I will run as first'() { }
def 'I will run as second'() { }
}
@@ -0,0 +1,13 @@
package extensions
import mocks.ItemService
import spock.lang.Specification
import spock.lang.Subject
class SubjectTest extends Specification {
@Subject
ItemService itemService // initialization here...
}
@@ -0,0 +1,24 @@
package extensions
import spock.lang.Specification
import spock.lang.Timeout
import java.util.concurrent.TimeUnit
@Timeout(5)
class TimeoutTest extends Specification {
@Timeout(1)
def 'I have one second to finish'() {
}
def 'I will have 5 seconds timeout'() {}
@Timeout(value = 200, unit = TimeUnit.SECONDS)
def 'I will fail after 200 millis'() {
expect:
true
}
}
@@ -0,0 +1,131 @@
package mocks
import spock.lang.Specification
class ItemServiceUnitTest extends Specification {
ItemProvider itemProvider
ItemService itemService
EventPublisher eventPublisher
def setup() {
itemProvider = Stub(ItemProvider)
eventPublisher = Mock(EventPublisher)
itemService = new ItemService(itemProvider, eventPublisher)
}
def 'should return items sorted by name'() {
given:
def ids = ['offer-id', 'offer-id-2']
itemProvider.getItems(ids) >> [new Item('offer-id-2', 'Zname'), new Item('offer-id', 'Aname')]
when:
List<Item> items = itemService.getAllItemsSortedByName(ids)
then:
items.collect { it.name } == ['Aname', 'Zname']
}
def 'arguments constraints'() {
itemProvider.getItems(['offer-id'])
itemProvider.getItems(_) >> []
itemProvider.getItems(*_) >> []
itemProvider.getItems(!null) >> []
itemProvider.getItems({ it.size > 0 }) >> []
}
def 'should return different items on subsequent call'() {
given:
itemProvider.getItems(_) >>> [
[],
[new Item('1', 'name')],
[new Item('2', 'name')]
]
when: 'method is called for the first time'
List<Item> items = itemService.getAllItemsSortedByName(['not-important'])
then: 'empty list is returned'
items == []
when: 'method is called for the second time'
items = itemService.getAllItemsSortedByName(['not-important'])
then: 'item with id=1 is returned'
items == [new Item('1', 'name')]
when: 'method is called for the thirdtime'
items = itemService.getAllItemsSortedByName(['not-important'])
then: 'item with id=2 is returned'
items == [new Item('2', 'name')]
}
def 'should throw ExternalItemProviderException when ItemProvider fails'() {
given:
itemProvider.getItems(_) >> { new RuntimeException()}
when:
itemService.getAllItemsSortedByName([])
then:
thrown(ExternalItemProviderException)
}
def 'chaining response'() {
itemProvider.getItems(_) >>> { new RuntimeException() } >> new SocketTimeoutException() >> [new Item('id', 'name')]
}
def 'should return different items for different ids lists'() {
given:
def firstIds = ['first']
def secondIds = ['second']
itemProvider.getItems(firstIds) >> [new Item('first', 'Zname')]
itemProvider.getItems(secondIds) >> [new Item('second', 'Aname')]
when:
def firstItems = itemService.getAllItemsSortedByName(firstIds)
def secondItems = itemService.getAllItemsSortedByName(secondIds)
then:
firstItems.first().name == 'Zname'
secondItems.first().name == 'Aname'
}
def 'should publish events about new non-empty saved offers'() {
given:
def offerIds = ['', 'a', 'b']
when:
itemService.saveItems(offerIds)
then:
2 * eventPublisher.publish({ it != null && !it.isEmpty()})
}
def 'should return items'() {
given:
itemProvider = Mock(ItemProvider)
itemProvider.getItems(['item-id']) >> [new Item('item-id', 'name')]
itemService = new ItemService(itemProvider, eventPublisher)
when:
def items = itemService.getAllItemsSortedByName(['item-id'])
then:
items == [new Item('item-id', 'name')]
}
def 'should spy on EventPublisher method call'() {
given:
LoggingEventPublisher eventPublisher = Spy(LoggingEventPublisher)
itemService = new ItemService(itemProvider, eventPublisher)
when:
itemService.saveItems(['item-id'])
then:
1 * eventPublisher.publish('item-id')
}
}
@@ -0,0 +1,30 @@
import extensions.TimeoutTest
import spock.lang.Issue
runner {
if (System.getenv("FILTER_STACKTRACE") == null) {
filterStackTrace false
}
report {
issueNamePrefix 'Bug '
issueUrlPrefix 'http://jira.org/issues/'
}
optimizeRunOrder true
// exclude TimeoutTest
// exclude {
// baseClass TimeoutTest
// annotation Issue
// }
report {
enabled true
logFileDir '.'
logFileName 'report.json'
logFileSuffix new Date().format('yyyy-MM-dd')
}
}
+12
View File
@@ -0,0 +1,12 @@
## Hamcrest
This module contains articles about Hamcrest
### Relevant articles
- [Hamcrest Text Matchers](https://www.baeldung.com/hamcrest-text-matchers)
- [Hamcrest File Matchers](https://www.baeldung.com/hamcrest-file-matchers)
- [Hamcrest Object Matchers](https://www.baeldung.com/hamcrest-object-matchers)
- [Hamcrest Bean Matchers](https://www.baeldung.com/hamcrest-bean-matchers)
- [Hamcrest Number Matchers](https://www.baeldung.com/hamcrest-number-matchers)
- [Hamcrest Common Core Matchers](https://www.baeldung.com/hamcrest-core-matchers)
- [Hamcrest Custom Matchers](https://www.baeldung.com/hamcrest-custom-matchers)
+29
View File
@@ -0,0 +1,29 @@
<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>
<groupId>com.baeldung</groupId>
<artifactId>hamcrest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>hamcrest</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>java-hamcrest</artifactId>
<version>${hamcrest.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<hamcrest.version>2.0.0.0</hamcrest.version>
</properties>
</project>
@@ -0,0 +1,41 @@
package com.baeldung.hamcrest.objectmatchers;
public class City extends Location {
String name;
String state;
public City(String name, String state) {
this.name = name;
this.state = state;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setState(String state) {
this.state = state;
}
public String getState() {
return state;
}
@Override
public String toString() {
if (this.name == null && this.state == null) return null;
StringBuilder sb = new StringBuilder();
sb.append("[");
sb.append("Name: ");
sb.append(this.name);
sb.append(", ");
sb.append("State: ");
sb.append(this.state);
sb.append("]");
return sb.toString();
}
}
@@ -0,0 +1,4 @@
package com.baeldung.hamcrest.objectmatchers;
public class Location {
}
@@ -0,0 +1,86 @@
package com.baeldung.hamcrest;
import com.baeldung.hamcrest.objectmatchers.City;
import org.junit.Test;
import java.beans.PropertyDescriptor;
import java.util.Arrays;
import java.util.List;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.beans.PropertyUtil.getPropertyDescriptor;
import static org.hamcrest.beans.PropertyUtil.propertyDescriptorsFor;
public class HamcrestBeansUnitTest {
@Test
public void givenACity_whenHasProperty_thenCorrect() {
City city = new City("San Francisco", "CA");
assertThat(city, hasProperty("name"));
}
@Test
public void givenACity_whenNotHasProperty_thenCorrect() {
City city = new City("San Francisco", "CA");
assertThat(city, not(hasProperty("country")));
}
@Test
public void givenACity_whenHasPropertyWithValueEqualTo_thenCorrect() {
City city = new City("San Francisco", "CA");
assertThat(city, hasProperty("name", equalTo("San Francisco")));
}
@Test
public void givenACity_whenHasPropertyWithValueEqualToIgnoringCase_thenCorrect() {
City city = new City("San Francisco", "CA");
assertThat(city, hasProperty("state", equalToIgnoringCase("ca")));
}
@Test
public void givenACity_whenSamePropertyValuesAs_thenCorrect() {
City city = new City("San Francisco", "CA");
City city2 = new City("San Francisco", "CA");
assertThat(city, samePropertyValuesAs(city2));
}
@Test
public void givenACity_whenNotSamePropertyValuesAs_thenCorrect() {
City city = new City("San Francisco", "CA");
City city2 = new City("Los Angeles", "CA");
assertThat(city, not(samePropertyValuesAs(city2)));
}
@Test
public void givenACity_whenGetPropertyDescriptor_thenCorrect() {
City city = new City("San Francisco", "CA");
PropertyDescriptor descriptor = getPropertyDescriptor("state", city);
assertThat(descriptor
.getReadMethod()
.getName(), is(equalTo("getState")));
}
@Test
public void givenACity_whenGetPropertyDescriptorsFor_thenCorrect() {
City city = new City("San Francisco", "CA");
PropertyDescriptor[] descriptors = propertyDescriptorsFor(city, Object.class);
List<String> getters = Arrays
.stream(descriptors)
.map(x -> x
.getReadMethod()
.getName())
.collect(toList());
assertThat(getters, containsInAnyOrder("getName", "getState"));
}
}
@@ -0,0 +1,256 @@
package com.baeldung.hamcrest;
import com.google.common.collect.Lists;
import org.junit.Test;
import java.util.List;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringEndsWith.endsWith;
import static org.hamcrest.core.StringStartsWith.startsWith;
public class HamcrestCoreMatchersUnitTest {
@Test
public void givenTestInput_WhenUsingIsForMatch() {
// GIVEN
String testString = "hamcrest core";
// ASSERT
assertThat(testString, is("hamcrest core"));
assertThat(testString, is(equalTo("hamcrest core")));
}
@Test
public void givenDifferentStaticTypeTestInput_WhenUsingEqualToObject_ThenCorrect() {
// GIVEN
Object original = 100;
// ASSERT
assertThat(original, equalToObject(100));
}
@Test
public void givenTestInput_WhenUsingInstanceOfForClassTypeCheck() {
assertThat("hamcrest", is(instanceOf(String.class)));
}
@Test
public void givenTestInput_WhenUsingIsA_ThenAssertType() {
assertThat("hamcrest core", isA(String.class));
}
@Test
public void givenTestInput_WhenUsingEqualToMatcherForEquality() {
// GIVEN
String actualString = "Hamcrest Core";
List<String> actualList = Lists.newArrayList("hamcrest", "core");
// ASSERT
assertThat(actualString, is(equalTo("Hamcrest Core")));
assertThat(actualList, is(equalTo(Lists.newArrayList("hamcrest", "core"))));
}
@Test
public void givenTestInput_WhenUsingNotForMatch() {
// GIVEN
String testString = "hamcrest";
// ASSERT
assertThat(testString, not("hamcrest core"));
assertThat(testString, is(not(equalTo("hamcrest core"))));
assertThat(testString, is(not(instanceOf(Integer.class))));
}
@Test
public void givenTestInput_WhenUsingNullValueForNullCheck() {
// GIVEN
Integer nullObject = null;
// ASSERT
assertThat(nullObject, is(nullValue()));
assertThat(nullObject, is(nullValue(Integer.class)));
}
@Test
public void givenTestInput_WhenUsingNotNullValueForNotNullCheck() {
// GIVEN
Integer testNumber = 123;
// ASSERT
assertThat(testNumber, is(notNullValue()));
assertThat(testNumber, is(notNullValue(Integer.class)));
}
@Test
public void givenString_WhenStartsWith_ThenCorrect() {
// GIVEN
String testString = "hamcrest core";
// ASSERT
assertThat(testString, startsWith("hamcrest"));
}
@Test
public void giveString_WhenStartsWithIgnoringCase_ThenCorrect() {
// GIVEN
String testString = "hamcrest core";
// ASSERT
assertThat(testString, startsWithIgnoringCase("HAMCREST"));
}
@Test
public void givenString_WhenEndsWith_ThenCorrect() {
// GIVEN
String testString = "hamcrest core";
// ASSERT
assertThat(testString, endsWith("core"));
}
@Test
public void givenString_WhenEndsWithIgnoringCase_ThenCorrect() {
// GIVEN
String testString = "hamcrest core";
// ASSERT
assertThat(testString, endsWithIgnoringCase("CORE"));
}
@Test
public void givenString_WhenContainsString_ThenCorrect() {
// GIVEN
String testString = "hamcrest core";
// ASSERT
assertThat(testString, containsString("co"));
}
@Test
public void givenString_WhenContainsStringIgnoringCase_ThenCorrect() {
// GIVEN
String testString = "hamcrest core";
// ASSERT
assertThat(testString, containsStringIgnoringCase("CO"));
}
@Test
public void givenTestInput_WhenUsingHasItemInCollection() {
// GIVEN
List<String> list = Lists.newArrayList("java", "spring", "baeldung");
// ASSERT
assertThat(list, hasItem("java"));
assertThat(list, hasItem(isA(String.class)));
}
@Test
public void givenTestInput_WhenUsingHasItemsInCollection() {
// GIVEN
List<String> list = Lists.newArrayList("java", "spring", "baeldung");
// ASSERT
assertThat(list, hasItems("java", "baeldung"));
assertThat(list, hasItems(isA(String.class), endsWith("ing")));
}
@Test
public void givenTestInput_WhenUsingAnyForClassType() {
assertThat("hamcrest", is(any(String.class)));
assertThat("hamcrest", is(any(Object.class)));
}
@Test
public void givenTestInput_WhenUsingAllOfForAllMatchers() {
// GIVEN
String testString = "Hamcrest Core";
// ASSERT
assertThat(testString, allOf(startsWith("Ham"), endsWith("ore"), containsString("Core")));
}
@Test
public void givenTestInput_WhenUsingAnyOfForAnyMatcher() {
// GIVEN
String testString = "Hamcrest Core";
// ASSERT
assertThat(testString, anyOf(startsWith("Ham"), containsString("baeldung")));
}
@Test
public void givenTestInput_WhenUsingBothForMatcher() {
// GIVEN
String testString = "Hamcrest Core Matchers";
// ASSERT
assertThat(testString, both(startsWith("Ham")).and(containsString("Core")));
}
@Test
public void givenTestInput_WhenUsingEitherForMatcher() {
// GIVEN
String testString = "Hamcrest Core Matchers";
// ASSERT
assertThat(testString, either(startsWith("Bael")).or(containsString("Core")));
}
@Test
public void givenTestInput_WhenUsingEveryItemForMatchInCollection() {
// GIVEN
List<String> testItems = Lists.newArrayList("Common", "Core", "Combinable");
// ASSERT
assertThat(testItems, everyItem(startsWith("Co")));
}
@Test
public void givenTwoTestInputs_WhenUsingSameInstanceForMatch() {
// GIVEN
String string1 = "hamcrest";
String string2 = string1;
// ASSERT
assertThat(string1, is(sameInstance(string2)));
}
@Test
public void givenTwoTestInputs_WhenUsingTheInstanceForMatch() {
// GIVEN
String string1 = "hamcrest";
String string2 = string1;
// ASSERT
assertThat(string1, is(theInstance(string2)));
}
}
@@ -0,0 +1,55 @@
package com.baeldung.hamcrest;
import org.junit.Test;
import java.io.File;
import static org.hamcrest.io.FileMatchers.*;
import static org.hamcrest.number.OrderingComparison.greaterThan;
import static org.hamcrest.text.IsEqualIgnoringCase.equalToIgnoringCase;
import static org.junit.Assert.assertThat;
public class HamcrestFileUnitTest {
@Test
public final void whenVerifyingFileName_thenCorrect() {
File file = new File("src/test/resources/test1.in");
assertThat(file, aFileNamed(equalToIgnoringCase("test1.in")));
}
@Test
public final void whenVerifyingFileOrDirExist_thenCorrect() {
File file = new File("src/test/resources/test1.in");
File dir = new File("src/test/resources");
assertThat(file, anExistingFile());
assertThat(dir, anExistingDirectory());
assertThat(file, anExistingFileOrDirectory());
assertThat(dir, anExistingFileOrDirectory());
}
@Test
public final void whenVerifyingFileIsReadableAndWritable_thenCorrect() {
File file = new File("src/test/resources/test1.in");
assertThat(file, aReadableFile());
assertThat(file, aWritableFile());
}
@Test
public final void whenVerifyingFileSize_thenCorrect() {
File file = new File("src/test/resources/test1.in");
assertThat(file, aFileWithSize(11));
assertThat(file, aFileWithSize(greaterThan(1L)));;
}
/*@Test
public final void whenVerifyingFilePath_thenCorrect() {
File file = new File("src/test/resources/test1.in");
assertThat(file, aFileWithCanonicalPath(containsString("src/test/resources")));
assertThat(file, aFileWithAbsolutePath(containsString("src/test/resources")));
}*/
}
@@ -0,0 +1,170 @@
package com.baeldung.hamcrest;
import org.junit.Test;
import java.math.BigDecimal;
import java.time.LocalDate;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
public class HamcrestNumberUnitTest {
@Test
public void givenADouble_whenCloseTo_thenCorrect() {
double actual = 1.3;
double operand = 1;
double error = 0.5;
assertThat(actual, is(closeTo(operand, error)));
}
@Test
public void givenADouble_whenNotCloseTo_thenCorrect() {
double actual = 1.6;
double operand = 1;
double error = 0.5;
assertThat(actual, is(not(closeTo(operand, error))));
}
@Test
public void givenABigDecimal_whenCloseTo_thenCorrect() {
BigDecimal actual = new BigDecimal("1.0003");
BigDecimal operand = new BigDecimal("1");
BigDecimal error = new BigDecimal("0.0005");
assertThat(actual, is(closeTo(operand, error)));
}
@Test
public void givenABigDecimal_whenNotCloseTo_thenCorrect() {
BigDecimal actual = new BigDecimal("1.0006");
BigDecimal operand = new BigDecimal("1");
BigDecimal error = new BigDecimal("0.0005");
assertThat(actual, is(not(closeTo(operand, error))));
}
@Test
public void given5_whenComparesEqualTo5_thenCorrect() {
Integer five = 5;
assertThat(five, comparesEqualTo(five));
}
@Test
public void given5_whenNotComparesEqualTo7_thenCorrect() {
Integer seven = 7;
Integer five = 5;
assertThat(five, not(comparesEqualTo(seven)));
}
@Test
public void given7_whenGreaterThan5_thenCorrect() {
Integer seven = 7;
Integer five = 5;
assertThat(seven, is(greaterThan(five)));
}
@Test
public void given7_whenGreaterThanOrEqualTo5_thenCorrect() {
Integer seven = 7;
Integer five = 5;
assertThat(seven, is(greaterThanOrEqualTo(five)));
}
@Test
public void given5_whenGreaterThanOrEqualTo5_thenCorrect() {
Integer five = 5;
assertThat(five, is(greaterThanOrEqualTo(five)));
}
@Test
public void given3_whenLessThan5_thenCorrect() {
Integer three = 3;
Integer five = 5;
assertThat(three, is(lessThan(five)));
}
@Test
public void given3_whenLessThanOrEqualTo5_thenCorrect() {
Integer three = 3;
Integer five = 5;
assertThat(three, is(lessThanOrEqualTo(five)));
}
@Test
public void given5_whenLessThanOrEqualTo5_thenCorrect() {
Integer five = 5;
assertThat(five, is(lessThanOrEqualTo(five)));
}
@Test
public void givenBenjamin_whenGreaterThanAmanda_thenCorrect() {
String amanda = "Amanda";
String benjamin = "Benjamin";
assertThat(benjamin, is(greaterThan(amanda)));
}
@Test
public void givenAmanda_whenLessThanBenajmin_thenCorrect() {
String amanda = "Amanda";
String benjamin = "Benjamin";
assertThat(amanda, is(lessThan(benjamin)));
}
@Test
public void givenToday_whenGreaterThanYesterday_thenCorrect() {
LocalDate today = LocalDate.now();
LocalDate yesterday = today.minusDays(1);
assertThat(today, is(greaterThan(yesterday)));
}
@Test
public void givenToday_whenLessThanTomorrow_thenCorrect() {
LocalDate today = LocalDate.now();
LocalDate tomorrow = today.plusDays(1);
assertThat(today, is(lessThan(tomorrow)));
}
@Test
public void givenAmanda_whenOlderThanBenjamin_thenCorrect() {
Person amanda = new Person("Amanda", 20);
Person benjamin = new Person("Benjamin", 18);
assertThat(amanda, is(greaterThan(benjamin)));
}
@Test
public void givenBenjamin_whenYoungerThanAmanda_thenCorrect() {
Person amanda = new Person("Amanda", 20);
Person benjamin = new Person("Benjamin", 18);
assertThat(benjamin, is(lessThan(amanda)));
}
class Person implements Comparable<Person> {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public int compareTo(Person o) {
if (this.age == o.getAge()) return 0;
if (this.age > o.age) return 1;
else return -1;
}
}
@Test
public void givenNaN_whenIsNotANumber_thenCorrect() {
double zero = 0d;
assertThat(zero / zero, is(notANumber()));
}
}
@@ -0,0 +1,54 @@
package com.baeldung.hamcrest;
import com.baeldung.hamcrest.objectmatchers.City;
import com.baeldung.hamcrest.objectmatchers.Location;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
public class HamcrestObjectUnitTest {
@Test
public void givenACity_whenHasToString_thenCorrect() {
City city = new City("San Francisco", "CA");
assertThat(city, hasToString("[Name: San Francisco, State: CA]"));
}
@Test
public void givenACity_whenHasToStringEqualToIgnoringCase_thenCorrect() {
City city = new City("San Francisco", "CA");
assertThat(city, hasToString(equalToIgnoringCase("[NAME: SAN FRANCISCO, STATE: CA]")));
}
@Test
public void givenACity_whenHasToStringEmptyOrNullString_thenCorrect() {
City city = new City(null, null);
assertThat(city, hasToString(emptyOrNullString()));
}
@Test
public void givenACity_whenTypeCompatibleWithLocation_thenCorrect() {
City city = new City("San Francisco", "CA");
assertThat(city.getClass(), is(typeCompatibleWith(Location.class)));
}
@Test
public void givenACity_whenTypeNotCompatibleWithString_thenCorrect() {
City city = new City("San Francisco", "CA");
assertThat(city.getClass(), is(not(typeCompatibleWith(String.class))));
}
@Test
public void givenACity_whenTypeCompatibleWithObject_thenCorrect() {
City city = new City("San Francisco", "CA");
assertThat(city.getClass(), is(typeCompatibleWith(Object.class)));
}
}
@@ -0,0 +1,97 @@
package com.baeldung.hamcrest;
import org.junit.Test;
import static org.hamcrest.core.StringContains.containsString;
import static org.hamcrest.core.StringContains.containsStringIgnoringCase;
import static org.hamcrest.core.StringEndsWith.endsWith;
import static org.hamcrest.core.StringEndsWith.endsWithIgnoringCase;
import static org.hamcrest.core.StringStartsWith.startsWith;
import static org.hamcrest.core.StringStartsWith.startsWithIgnoringCase;
import static org.hamcrest.text.IsBlankString.blankOrNullString;
import static org.hamcrest.text.IsBlankString.blankString;
import static org.hamcrest.text.IsEmptyString.emptyOrNullString;
import static org.hamcrest.text.IsEmptyString.emptyString;
import static org.hamcrest.text.IsEqualIgnoringCase.equalToIgnoringCase;
import static org.hamcrest.text.IsEqualIgnoringWhiteSpace.equalToIgnoringWhiteSpace;
import static org.hamcrest.text.MatchesPattern.matchesPattern;
import static org.hamcrest.text.StringContainsInOrder.stringContainsInOrder;
import static org.junit.Assert.assertThat;
public class HamcrestTextUnitTest {
@Test
public final void whenTwoStringsAreEqual_thenCorrect() {
String first = "hello";
String second = "Hello";
assertThat(first, equalToIgnoringCase(second));
}
@Test
public final void whenTwoStringsAreEqualWithWhiteSpace_thenCorrect() {
String first = "hello";
String second = " Hello ";
assertThat(first, equalToIgnoringWhiteSpace(second));
}
@Test
public final void whenStringIsBlank_thenCorrect() {
String first = " ";
String second = null;
assertThat(first, blankString());
assertThat(first, blankOrNullString());
assertThat(second, blankOrNullString());
}
@Test
public final void whenStringIsEmpty_thenCorrect() {
String first = "";
String second = null;
assertThat(first, emptyString());
assertThat(first, emptyOrNullString());
assertThat(second, emptyOrNullString());
}
@Test
public final void whenStringMatchPattern_thenCorrect() {
String first = "hello";
assertThat(first, matchesPattern("[a-z]+"));
}
@Test
public final void whenVerifyStringContains_thenCorrect() {
String first = "hello";
assertThat(first, containsString("lo"));
assertThat(first, containsStringIgnoringCase("EL"));
}
@Test
public final void whenVerifyStringContainsInOrder_thenCorrect() {
String first = "hello";
assertThat(first, stringContainsInOrder("e","l","o"));
}
@Test
public final void whenVerifyStringStartsWith_thenCorrect() {
String first = "hello";
assertThat(first, startsWith("he"));
assertThat(first, startsWithIgnoringCase("HEL"));
}
@Test
public final void whenVerifyStringEndsWith_thenCorrect() {
String first = "hello";
assertThat(first, endsWith("lo"));
assertThat(first, endsWithIgnoringCase("LO"));
}
}
@@ -0,0 +1,50 @@
package com.baeldung.hamcrest.custommatchers;
import org.junit.Test;
import static com.baeldung.hamcrest.custommatchers.IsDivisibleBy.divisibleBy;
import static com.baeldung.hamcrest.custommatchers.IsOnlyDigits.onlyDigits;
import static com.baeldung.hamcrest.custommatchers.IsUppercase.uppercase;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
public class HamcrestCustomUnitTest {
@Test
public final void givenAString_whenIsOnlyDigits_thenCorrect() {
String digits = "123";
assertThat(digits, is(onlyDigits()));
}
@Test
public final void givenAString_whenIsNotOnlyDigits_thenCorrect() {
String aphanumeric = "123ABC";
assertThat(aphanumeric, is(not(onlyDigits())));
}
@Test
public final void givenAString_whenIsUppercase_thenCorrect() {
String uppercaseWord = "HELLO";
assertThat(uppercaseWord, is(uppercase()));
}
@Test
public final void givenAnEvenInteger_whenDivisibleByTwo_thenCorrect() {
Integer ten = 10;
Integer two = 2;
assertThat(ten, is(divisibleBy(two)));
}
@Test
public final void givenAnOddInteger_whenNotDivisibleByTwo_thenCorrect() {
Integer eleven = 11;
Integer two = 2;
assertThat(eleven, is(not(divisibleBy(two))));
}
}
@@ -0,0 +1,29 @@
package com.baeldung.hamcrest.custommatchers;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
public class IsDivisibleBy extends TypeSafeMatcher<Integer> {
private Integer divider;
private IsDivisibleBy(Integer divider) {
this.divider = divider;
}
@Override
protected boolean matchesSafely(Integer dividend) {
if (divider == 0) return false;
return ((dividend % divider) == 0);
}
@Override
public void describeTo(Description description) {
description.appendText("divisible by " + divider);
}
public static Matcher<Integer> divisibleBy(Integer divider) {
return new IsDivisibleBy(divider);
}
}
@@ -0,0 +1,27 @@
package com.baeldung.hamcrest.custommatchers;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
public class IsOnlyDigits extends TypeSafeMatcher<String> {
@Override
protected boolean matchesSafely(String s) {
try {
Integer.parseInt(s);
return true;
} catch (NumberFormatException nfe) {
return false;
}
}
@Override
public void describeTo(Description description) {
description.appendText("only digits");
}
public static Matcher<String> onlyDigits() {
return new IsOnlyDigits();
}
}
@@ -0,0 +1,22 @@
package com.baeldung.hamcrest.custommatchers;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
public class IsUppercase extends TypeSafeMatcher<String> {
@Override
protected boolean matchesSafely(String s) {
return s.equals(s.toUpperCase());
}
@Override
public void describeTo(Description description) {
description.appendText("all uppercase");
}
public static Matcher<String> uppercase() {
return new IsUppercase();
}
}
@@ -0,0 +1 @@
Hello world
+6
View File
@@ -0,0 +1,6 @@
### Relevant Articles
- [Guide to JUnit 4 Rules](https://www.baeldung.com/junit-4-rules)
- [Custom JUnit 4 Test Runners](http://www.baeldung.com/junit-4-custom-runners)
- [Introduction to JUnitParams](http://www.baeldung.com/junit-params)
- [Running JUnit Tests Programmatically, from a Java Application](https://www.baeldung.com/junit-tests-run-programmatically-from-java)
+31
View File
@@ -0,0 +1,31 @@
<?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>junit-4</artifactId>
<version>1.0-SNAPSHOT</version>
<name>junit-4</name>
<description>JUnit 4 Topics</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>pl.pragmatists</groupId>
<artifactId>JUnitParams</artifactId>
<version>${jUnitParams.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<jUnitParams.version>1.1.0</jUnitParams.version>
</properties>
</project>
@@ -0,0 +1,11 @@
package com.baeldung.junit;
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int sub(int a, int b) {
return a - b;
}
}
@@ -0,0 +1,15 @@
package com.baeldung.junitparams;
public class SafeAdditionUtil {
public int safeAdd(int a, int b) {
long result = ((long) a) + b;
if (result > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
} else if (result < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
return (int) result;
}
}
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
@@ -0,0 +1,14 @@
package com.baeldung.junit;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class AdditionUnitTest {
Calculator calculator = new Calculator();
@Test
public void testAddition() {
assertEquals("addition", 8, calculator.add(5, 3));
}
}

Some files were not shown because too many files have changed in this diff Show More