Merge pull request #8125 from eugenp/revert-8119-BAEL-3275-2

Revert "BAEL-3275: Using blocking queue for pub-sub"
This commit is contained in:
Eric Martin
2019-10-31 20:43:47 -05:00
committed by GitHub
parent db85c8f275
commit 3225470df5
20543 changed files with 1642750 additions and 0 deletions
+13
View File
@@ -0,0 +1,13 @@
## Testing
This module contains articles about test libraries.
### Relevant articles
- [Introduction to Serenity BDD](https://www.baeldung.com/serenity-bdd)
- [Introduction to JSONassert](https://www.baeldung.com/jsonassert)
- [Serenity BDD and Screenplay](https://www.baeldung.com/serenity-screenplay)
- [Serenity BDD with Spring and JBehave](https://www.baeldung.com/serenity-spring-jbehave)
- [Introduction to Awaitlity](https://www.baeldung.com/awaitlity-testing)
- [Introduction to Hoverfly in Java](https://www.baeldung.com/hoverfly)
- [Testing with Hamcrest](https://www.baeldung.com/java-junit-hamcrest-guide)
+5
View File
@@ -0,0 +1,5 @@
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
+171
View File
@@ -0,0 +1,171 @@
<?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>libraries-testing</artifactId>
<name>libraries-testing</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>net.serenity-bdd</groupId>
<artifactId>serenity-core</artifactId>
<version>${serenity.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctorj</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>net.serenity-bdd</groupId>
<artifactId>serenity-junit</artifactId>
<version>${serenity.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.serenity-bdd</groupId>
<artifactId>serenity-jbehave</artifactId>
<version>${serenity.jbehave.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.serenity-bdd</groupId>
<artifactId>serenity-rest-assured</artifactId>
<version>${serenity.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>net.serenity-bdd</groupId>
<artifactId>serenity-jira-requirements-provider</artifactId>
<version>${serenity.jira.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.serenity-bdd</groupId>
<artifactId>serenity-spring</artifactId>
<version>${serenity.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>net.serenity-bdd</groupId>
<artifactId>serenity-screenplay</artifactId>
<version>${serenity.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.serenity-bdd</groupId>
<artifactId>serenity-screenplay-webdriver</artifactId>
<version>${serenity.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.skyscreamer</groupId>
<artifactId>jsonassert</artifactId>
<version>${jsonassert.version}</version>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${awaitility.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility-proxy</artifactId>
<version>${awaitility.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.specto</groupId>
<artifactId>hoverfly-java</artifactId>
<version>${hoverfly-java.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>spring-mock-mvc</artifactId>
<version>${spring-mock-mvc.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hamcrest/java-hamcrest -->
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>java-hamcrest</artifactId>
<version>${java-hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
<version>1.5.7.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>net.serenity-bdd.maven.plugins</groupId>
<artifactId>serenity-maven-plugin</artifactId>
<version>${serenity.plugin.version}</version>
<executions>
<execution>
<id>serenity-reports</id>
<phase>post-integration-test</phase>
<goals>
<goal>aggregate</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<serenity.version>1.9.9</serenity.version>
<serenity.jbehave.version>1.9.0</serenity.jbehave.version>
<serenity.jira.version>1.9.0</serenity.jira.version>
<serenity.plugin.version>1.9.27</serenity.plugin.version>
<jsonassert.version>1.5.0</jsonassert.version>
<awaitility.version>3.0.0</awaitility.version>
<hoverfly-java.version>0.8.1</hoverfly-java.version>
<spring.version>4.3.8.RELEASE</spring.version>
<spring-mock-mvc.version>4.1.1</spring-mock-mvc.version>
<assertj.version>3.6.2</assertj.version>
<java-hamcrest.version>2.0.0.0</java-hamcrest.version>
</properties>
</project>
+4
View File
@@ -0,0 +1,4 @@
jira.url=<jira-url>
jira.project=<jira-project>
jira.username=<jira-username>
jira.password=<jira-password>
@@ -0,0 +1,52 @@
package com.baeldung.awaitility;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;
public class AsyncService {
private final int DELAY = 1000;
private final int INIT_DELAY = 2000;
private final AtomicLong value = new AtomicLong(0);
private final Executor executor = Executors.newFixedThreadPool(4);
private volatile boolean initialized = false;
void initialize() {
executor.execute(() -> {
sleep(INIT_DELAY);
initialized = true;
});
}
boolean isInitialized() {
return initialized;
}
void addValue(long val) {
throwIfNotInitialized();
executor.execute(() -> {
sleep(DELAY);
value.addAndGet(val);
});
}
public long getValue() {
throwIfNotInitialized();
return value.longValue();
}
private void sleep(int delay) {
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void throwIfNotInitialized() {
if (!initialized) {
throw new IllegalStateException("Service is not initialized");
}
}
}
@@ -0,0 +1,19 @@
package com.baeldung.serenity.github;
public class GitHubUser {
private String login;
public GitHubUser() {
super();
}
public String getLogin() {
return login;
}
public void setLogin(final String login) {
this.login = login;
}
}
@@ -0,0 +1,16 @@
package com.baeldung.serenity.membership;
/**
* @author aiet
*/
public enum Commodity {
MacBookPro(1499), GoProHero5(400);
public final int price;
Commodity(int price) {
this.price = price;
}
}
@@ -0,0 +1,38 @@
package com.baeldung.serenity.membership;
import static com.baeldung.serenity.membership.MemberGrade.Bronze;
import static com.baeldung.serenity.membership.MemberGrade.Gold;
import static com.baeldung.serenity.membership.MemberGrade.Silver;
/**
* @author aiet
*/
public class Member {
private int points;
private Member(int points) {
if (points < 0)
throw new IllegalArgumentException("points must not be negative!");
this.points = points;
}
public static Member withInitialPoints(int initialPoints) {
return new Member(initialPoints);
}
public MemberGrade getGrade() {
if (points < 1000)
return Bronze;
else if (points >= 1000 && points < 5000)
return Silver;
else
return Gold;
}
public void spend(int moneySpent) {
points += moneySpent / 10;
}
}
@@ -0,0 +1,10 @@
package com.baeldung.serenity.membership;
/**
* @author aiet
*/
public enum MemberGrade {
Bronze, Silver, Gold;
}
@@ -0,0 +1,29 @@
package com.baeldung.serenity.spring;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
/**
* @author aiet
*/
@RequestMapping(value = "/adder", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
public class AdderController {
private AdderService adderService;
public AdderController(AdderService adderService) {
this.adderService = adderService;
}
@GetMapping("/current")
public int currentNum() {
return adderService.currentBase();
}
@PostMapping
public int add(@RequestParam int num) {
return adderService.add(num);
}
}
@@ -0,0 +1,25 @@
package com.baeldung.serenity.spring;
import org.springframework.stereotype.Service;
@Service
public class AdderService {
private int num;
public void baseNum(int base) {
this.num = base;
}
public int currentBase() {
return num;
}
public int add(int adder) {
return this.num + adder;
}
public int accumulate(int adder) {
return this.num += adder;
}
}
@@ -0,0 +1,26 @@
package com.baeldung.serenity.spring;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
/**
* @author aiet
*/
@RequestMapping(value = "/adder", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
public class PlainAdderController {
private final int currentNumber = RandomUtils.nextInt();
@GetMapping("/current")
public int currentNum() {
return currentNumber;
}
@PostMapping
public int add(@RequestParam int num) {
return currentNumber + num;
}
}
@@ -0,0 +1,77 @@
package com.baeldung.awaitility;
import org.awaitility.Duration;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import static org.awaitility.Awaitility.await;
import static org.awaitility.Awaitility.fieldIn;
import static org.awaitility.Awaitility.given;
import static org.awaitility.Awaitility.setDefaultPollDelay;
import static org.awaitility.Awaitility.setDefaultPollInterval;
import static org.awaitility.Awaitility.setDefaultTimeout;
import static org.awaitility.proxy.AwaitilityClassProxy.to;
import static org.hamcrest.Matchers.equalTo;
public class AsyncServiceLongRunningManualTest {
private AsyncService asyncService;
@Before
public void setUp() {
asyncService = new AsyncService();
}
@Test
public void givenAsyncService_whenInitialize_thenInitOccurs1() {
asyncService.initialize();
Callable<Boolean> isInitialized = asyncService::isInitialized;
await().until(isInitialized);
}
@Test
public void givenAsyncService_whenInitialize_thenInitOccurs2() {
asyncService.initialize();
Callable<Boolean> isInitialized = asyncService::isInitialized;
await().atLeast(Duration.ONE_HUNDRED_MILLISECONDS).atMost(Duration.FIVE_SECONDS).with().pollInterval(Duration.ONE_HUNDRED_MILLISECONDS).until(isInitialized);
}
@Test
public void givenAsyncService_whenInitialize_thenInitOccurs_withDefualts() {
setDefaultPollInterval(10, TimeUnit.MILLISECONDS);
setDefaultPollDelay(Duration.ZERO);
setDefaultTimeout(Duration.ONE_MINUTE);
asyncService.initialize();
await().until(asyncService::isInitialized);
}
@Test
public void givenAsyncService_whenInitialize_thenInitOccurs_withProxy() {
asyncService.initialize();
await().untilCall(to(asyncService).isInitialized(), equalTo(true));
}
@Test
public void givenAsyncService_whenInitialize_thenInitOccurs3() {
asyncService.initialize();
await().until(fieldIn(asyncService).ofType(boolean.class).andWithName("initialized"), equalTo(true));
}
@Test
public void givenValue_whenAddValue_thenValueAdded() {
asyncService.initialize();
await().until(asyncService::isInitialized);
long value = 5;
asyncService.addValue(value);
await().until(asyncService::getValue, equalTo(value));
}
@Test
public void givenAsyncService_whenGetValue_thenExceptionIgnored() {
asyncService.initialize();
given().ignoreException(IllegalStateException.class).await().atMost(Duration.FIVE_SECONDS).atLeast(Duration.FIVE_HUNDRED_MILLISECONDS).until(asyncService::getValue, equalTo(0L));
}
}
@@ -0,0 +1,33 @@
package com.baeldung.hamcrest;
public class Animal {
String name;
boolean wild;
String sound;
public Animal(String name, boolean wild, String sound) {
super();
this.name = name;
this.wild = wild;
this.sound = sound;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isWild() {
return wild;
}
public void setWild(boolean wild) {
this.wild = wild;
}
public String getSound() {
return sound;
}
public void setSound(String sound) {
this.sound = sound;
}
}
@@ -0,0 +1,13 @@
package com.baeldung.hamcrest;
public class Cat extends Animal {
public Cat() {
super("cat", false, "meow");
}
public String makeSound() {
return getSound();
}
}
@@ -0,0 +1,331 @@
package com.baeldung.hamcrest;
import org.junit.Test;
import java.util.*;
import static com.baeldung.hamcrest.IsPositiveInteger.isAPositiveInteger;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.beans.HasProperty.hasProperty;
import static org.hamcrest.beans.HasPropertyWithValue.hasProperty;
import static org.hamcrest.beans.SamePropertyValuesAs.samePropertyValuesAs;
import static org.hamcrest.collection.IsArrayContaining.hasItemInArray;
import static org.hamcrest.collection.IsArrayContainingInAnyOrder.arrayContainingInAnyOrder;
import static org.hamcrest.collection.IsArrayContainingInOrder.arrayContaining;
import static org.hamcrest.collection.IsArrayWithSize.arrayWithSize;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.hamcrest.collection.IsEmptyCollection.empty;
import static org.hamcrest.collection.IsIn.isIn;
import static org.hamcrest.collection.IsIn.isOneOf;
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
import static org.hamcrest.collection.IsMapContaining.hasEntry;
import static org.hamcrest.collection.IsMapContaining.hasKey;
import static org.hamcrest.collection.IsMapContaining.hasValue;
import static org.hamcrest.core.AllOf.allOf;
import static org.hamcrest.core.AnyOf.anyOf;
import static org.hamcrest.core.Every.everyItem;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
import static org.hamcrest.core.IsNot.not;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.hamcrest.core.IsSame.sameInstance;
import static org.hamcrest.core.StringContains.containsString;
import static org.hamcrest.core.StringEndsWith.endsWith;
import static org.hamcrest.core.StringStartsWith.startsWith;
import static org.hamcrest.object.HasToString.hasToString;
import static org.hamcrest.object.IsCompatibleType.typeCompatibleWith;
import static org.hamcrest.text.IsEmptyString.isEmptyOrNullString;
import static org.hamcrest.text.IsEmptyString.isEmptyString;
import static org.hamcrest.text.IsEqualIgnoringCase.equalToIgnoringCase;
import static org.hamcrest.text.IsEqualIgnoringWhiteSpace.equalToIgnoringWhiteSpace;
import static org.hamcrest.text.StringContainsInOrder.stringContainsInOrder;
public class HamcrestMatcherUnitTest {
@Test
public void given2Strings_whenEqual_thenCorrect() {
String a = "foo";
String b = "FOO";
assertThat(a, equalToIgnoringCase(b));
}
@Test
public void givenBean_whenHasValue_thenCorrect() {
Person person = new Person("Baeldung", "New York");
assertThat(person, hasProperty("name"));
}
@Test
public void givenBean_whenHasCorrectValue_thenCorrect() {
Person person = new Person("Baeldung", "New York");
assertThat(person, hasProperty("address", equalTo("New York")));
}
@Test
public void given2Beans_whenHavingSameValues_thenCorrect() {
Person person1 = new Person("Baeldung", "New York");
Person person2 = new Person("Baeldung", "New York");
assertThat(person1, samePropertyValuesAs(person2));
}
@Test
public void givenAList_whenChecksSize_thenCorrect() {
List<String> hamcrestMatchers = Arrays.asList("collections", "beans",
"text", "number");
assertThat(hamcrestMatchers, hasSize(4));
}
@Test
public void givenArray_whenChecksSize_thenCorrect() {
String[] hamcrestMatchers = { "collections", "beans", "text", "number" };
assertThat(hamcrestMatchers, arrayWithSize(4));
}
@Test
public void givenAListAndValues_whenChecksListForGivenValues_thenCorrect() {
List<String> hamcrestMatchers = Arrays.asList("collections", "beans",
"text", "number");
assertThat(hamcrestMatchers,
containsInAnyOrder("beans", "text", "collections", "number"));
}
@Test
public void givenAListAndValues_whenChecksListForGivenValuesWithOrder_thenCorrect() {
List<String> hamcrestMatchers = Arrays.asList("collections", "beans",
"text", "number");
assertThat(hamcrestMatchers,
contains("collections", "beans", "text", "number"));
}
@Test
public void givenArrayAndValue_whenValueFoundInArray_thenCorrect() {
String[] hamcrestMatchers = { "collections", "beans", "text", "number" };
assertThat(hamcrestMatchers, hasItemInArray("text"));
}
@Test
public void givenValueAndArray_whenValueIsOneOfArrayElements_thenCorrect() {
String[] hamcrestMatchers = { "collections", "beans", "text", "number" };
assertThat("text", isOneOf(hamcrestMatchers));
}
@Test
public void givenArrayAndValues_whenValuesFoundInArray_thenCorrect() {
String[] hamcrestMatchers = { "collections", "beans", "text", "number" };
assertThat(
hamcrestMatchers,
arrayContainingInAnyOrder("beans", "collections", "number",
"text"));
}
@Test
public void givenArrayAndValues_whenValuesFoundInArrayInOrder_thenCorrect() {
String[] hamcrestMatchers = { "collections", "beans", "text", "number" };
assertThat(hamcrestMatchers,
arrayContaining("collections", "beans", "text", "number"));
}
@Test
public void givenCollection_whenEmpty_thenCorrect() {
List<String> emptyList = new ArrayList<>();
assertThat(emptyList, empty());
}
@Test
public void givenValueAndArray_whenValueFoundInArray_thenCorrect() {
String[] array = new String[] { "collections", "beans", "text",
"number" };
assertThat("beans", isIn(array));
}
@Test
public void givenMapAndKey_whenKeyFoundInMap_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("blogname", "baeldung");
assertThat(map, hasKey("blogname"));
}
@Test
public void givenMapAndEntry_whenEntryFoundInMap_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("blogname", "baeldung");
assertThat(map, hasEntry("blogname", "baeldung"));
}
@Test
public void givenMapAndValue_whenValueFoundInMap_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("blogname", "baeldung");
assertThat(map, hasValue("baeldung"));
}
@Test
public void givenString_whenEmpty_thenCorrect() {
String str = "";
assertThat(str, isEmptyString());
}
@Test
public void givenString_whenEmptyOrNull_thenCorrect() {
String str = null;
assertThat(str, isEmptyOrNullString());
}
@Test
public void given2Strings_whenEqualRegardlessWhiteSpace_thenCorrect() {
String str1 = "text";
String str2 = " text ";
assertThat(str1, equalToIgnoringWhiteSpace(str2));
}
@Test
public void givenString_whenContainsGivenSubstring_thenCorrect() {
String str = "calligraphy";
assertThat(str, stringContainsInOrder(Arrays.asList("call", "graph")));
}
@Test
public void givenBean_whenToStringReturnsRequiredString_thenCorrect() {
Person person = new Person("Barrack", "Washington");
String str = person.toString();
assertThat(person, hasToString(str));
}
@Test
public void given2Classes_whenOneInheritsFromOther_thenCorrect() {
assertThat(Cat.class, typeCompatibleWith(Animal.class));
}
@Test
public void given2Strings_whenIsEqualRegardlessWhiteSpace_thenCorrect() {
String str1 = "text";
String str2 = " text ";
assertThat(str1, is(equalToIgnoringWhiteSpace(str2)));
}
@Test
public void given2Strings_whenIsNotEqualRegardlessWhiteSpace_thenCorrect() {
String str1 = "text";
String str2 = " texts ";
assertThat(str1, not(equalToIgnoringWhiteSpace(str2)));
}
@Test
public void given2Strings_whenNotEqual_thenCorrect() {
String str1 = "text";
String str2 = "texts";
assertThat(str1, not(str2));
}
@Test
public void given2Strings_whenIsEqual_thenCorrect() {
String str1 = "text";
String str2 = "text";
assertThat(str1, is(str2));
}
@Test
public void givenAStrings_whenContainsAnotherGivenString_thenCorrect() {
String str1 = "calligraphy";
String str2 = "call";
assertThat(str1, containsString(str2));
}
@Test
public void givenAString_whenEndsWithAnotherGivenString_thenCorrect() {
String str1 = "calligraphy";
String str2 = "phy";
assertThat(str1, endsWith(str2));
}
@Test
public void givenAString_whenStartsWithAnotherGivenString_thenCorrect() {
String str1 = "calligraphy";
String str2 = "call";
assertThat(str1, startsWith(str2));
}
@Test
public void given2Objects_whenSameInstance_thenCorrect() {
Cat cat = new Cat();
assertThat(cat, sameInstance(cat));
}
@Test
public void givenAnObject_whenInstanceOfGivenClass_thenCorrect() {
Cat cat = new Cat();
assertThat(cat, instanceOf(Cat.class));
}
@Test
public void givenList_whenEachElementGreaterThan0_thenCorrect() {
List<Integer> list = Arrays.asList(1, 2, 3);
int baseCase = 0;
assertThat(list, everyItem(greaterThan(baseCase)));
}
@Test
public void givenString_whenNotNull_thenCorrect() {
String str = "notnull";
assertThat(str, notNullValue());
}
@Test
public void givenString_whenMeetsAnyOfGivenConditions_thenCorrect() {
String str = "calligraphy";
String start = "call";
String end = "foo";
assertThat(str, anyOf(startsWith(start), containsString(end)));
}
@Test
public void givenString_whenMeetsAllOfGivenConditions_thenCorrect() {
String str = "calligraphy";
String start = "call";
String end = "phy";
assertThat(str, allOf(startsWith(start), endsWith(end)));
}
@Test
public void givenInteger_whenAPositiveValue_thenCorrect() {
int num = 1;
assertThat(num, isAPositiveInteger());
}
@Test
public void givenAnInteger_whenGreaterThan0_thenCorrect() {
int num = 1;
assertThat(num, greaterThan(0));
}
@Test
public void givenAnInteger_whenGreaterThanOrEqTo5_thenCorrect() {
int num = 5;
assertThat(num, greaterThanOrEqualTo(5));
}
@Test
public void givenAnInteger_whenLessThan0_thenCorrect() {
int num = -1;
assertThat(num, lessThan(0));
}
@Test
public void givenAnInteger_whenLessThanOrEqTo5_thenCorrect() {
assertThat(-1, lessThanOrEqualTo(5));
}
@Test
public void givenADouble_whenCloseTo_thenCorrect() {
assertThat(1.2, closeTo(1, 0.5));
}
}
@@ -0,0 +1,24 @@
package com.baeldung.hamcrest;
import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
public class IsPositiveInteger extends TypeSafeMatcher<Integer> {
public void describeTo(Description description) {
description.appendText("a positive integer");
}
@Factory
public static Matcher<Integer> isAPositiveInteger() {
return new IsPositiveInteger();
}
@Override
protected boolean matchesSafely(Integer integer) {
return integer > 0;
}
}
@@ -0,0 +1,37 @@
package com.baeldung.hamcrest;
public class Person {
String name;
String address;
public Person(String personName, String personAddress) {
name = personName;
address = personAddress;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
String str="[address:"+address+",name:"+name+"]";
return str;
}
}
@@ -0,0 +1,112 @@
package com.baeldung.hoverfly;
import static io.specto.hoverfly.junit.core.SimulationSource.dsl;
import static io.specto.hoverfly.junit.dsl.HoverflyDsl.service;
import static io.specto.hoverfly.junit.dsl.HttpBodyConverter.jsonWithSingleQuotes;
import static io.specto.hoverfly.junit.dsl.ResponseCreators.success;
import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.any;
import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.equalsTo;
import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.equalsToJson;
import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.equalsToXml;
import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.matches;
import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.startsWith;
import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.matchesJsonPath;
import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.matchesXPath;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.time.StopWatch;
import org.junit.ClassRule;
import org.junit.Test;
import org.springframework.http.HttpStatus;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import io.specto.hoverfly.junit.core.SimulationSource;
import io.specto.hoverfly.junit.rule.HoverflyRule;
public class HoverflyApiLiveTest {
private static final SimulationSource source = dsl(service("http://www.baeldung.com").get("/api/courses/1").willReturn(success().body(jsonWithSingleQuotes("{'id':'1','name':'HCI'}")))
.post("/api/courses").willReturn(success())
.andDelay(3, TimeUnit.SECONDS).forMethod("POST"),
service(matches("www.*dung.com")).get(startsWith("/api/student")).queryParam("page", any()).willReturn(success())
.post(equalsTo("/api/student")).body(equalsToJson(jsonWithSingleQuotes("{'id':'1','name':'Joe'}"))).willReturn(success())
.put("/api/student/1").body(matchesJsonPath("$.name")).willReturn(success())
.post("/api/student").body(equalsToXml("<student><id>2</id><name>John</name></student>")).willReturn(success())
.put("/api/student/2").body(matchesXPath("/student/name")).willReturn(success()));
@ClassRule
public static final HoverflyRule rule = HoverflyRule.inSimulationMode(source);
private final RestTemplate restTemplate = new RestTemplate();
@Test
public void givenGetCourseById_whenRequestSimulated_thenAPICalledSuccessfully() throws URISyntaxException {
final ResponseEntity<String> courseResponse = restTemplate.getForEntity("http://www.baeldung.com/api/courses/1", String.class);
assertEquals(HttpStatus.OK, courseResponse.getStatusCode());
assertEquals("{\"id\":\"1\",\"name\":\"HCI\"}", courseResponse.getBody());
}
@Test
public void givenPostCourse_whenDelayInRequest_thenResponseIsDelayed() throws URISyntaxException {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
final ResponseEntity<Void> postResponse = restTemplate.postForEntity("http://www.baeldung.com/api/courses", null, Void.class);
stopWatch.stop();
long postTime = stopWatch.getTime();
assertEquals(HttpStatus.OK, postResponse.getStatusCode());
assertTrue(3L <= TimeUnit.MILLISECONDS.toSeconds(postTime));
}
@Test
public void givenGetStudent_whenRequestMatcher_thenAPICalledSuccessfully() throws URISyntaxException {
final ResponseEntity<Void> courseResponse = restTemplate.getForEntity("http://www.baeldung.com/api/student?page=3", Void.class);
assertEquals(HttpStatus.OK, courseResponse.getStatusCode());
}
@Test
public void givenPostStudent_whenBodyRequestMatcherJson_thenResponseContainsEqualJson() throws URISyntaxException {
final ResponseEntity<Void> postResponse = restTemplate.postForEntity("http://www.baeldung.com/api/student", "{\"id\":\"1\",\"name\":\"Joe\"}", Void.class);
assertEquals(HttpStatus.OK, postResponse.getStatusCode());
}
@Test
public void givenPutStudent_whenJsonPathMatcher_thenRequestJsonContainsElementInPath() throws URISyntaxException {
RequestEntity<String> putRequest = RequestEntity.put(new URI("http://www.baeldung.com/api/student/1")).body("{\"id\":\"1\",\"name\":\"Trevor\"}");
ResponseEntity<String> putResponse = restTemplate.exchange(putRequest, String.class);
assertEquals(HttpStatus.OK, putResponse.getStatusCode());
}
@Test
public void givenPostStudent_whenBodyRequestMatcherXml_thenResponseContainsEqualXml() throws URISyntaxException {
final ResponseEntity<Void> postResponse = restTemplate.postForEntity("http://www.baeldung.com/api/student", "<student><id>2</id><name>John</name></student>", Void.class);
assertEquals(HttpStatus.OK, postResponse.getStatusCode());
}
@Test
public void givenPutStudent_whenXPathMatcher_thenRequestXmlContainsElementInXPath() throws URISyntaxException {
RequestEntity<String> putRequest = RequestEntity.put(new URI("http://www.baeldung.com/api/student/2")).body("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + "<student><id>2</id><name>Monica</name></student>");
ResponseEntity<String> putResponse = restTemplate.exchange(putRequest, String.class);
assertEquals(HttpStatus.OK, putResponse.getStatusCode());
}
}
@@ -0,0 +1,113 @@
package com.baeldung.jsonassert;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;
import org.skyscreamer.jsonassert.Customization;
import org.skyscreamer.jsonassert.JSONAssert;
import org.skyscreamer.jsonassert.JSONCompareMode;
import org.skyscreamer.jsonassert.RegularExpressionValueMatcher;
import org.skyscreamer.jsonassert.comparator.ArraySizeComparator;
import org.skyscreamer.jsonassert.comparator.CustomComparator;
import static org.assertj.core.api.Assertions.assertThat;
public class JsonAssertUnitTest {
@Test
public void givenLenientode_whenAssertEqualsSameJsonString_thenPass() throws JSONException {
String actual = "{id:123,name:\"John\"}";
JSONAssert.assertEquals("{id:123,name:\"John\"}", actual, JSONCompareMode.LENIENT);
actual = "{id:123,name:\"John\",zip:\"33025\"}";
JSONAssert.assertEquals("{id:123,name:\"John\"}", actual, JSONCompareMode.LENIENT);
}
@Test
public void givenStrictMode_whenAssertNotEqualsExtendedJsonString_thenPass() throws JSONException {
String actual = "{id:123,name:\"John\"}";
JSONAssert.assertNotEquals("{name:\"John\"}", actual, JSONCompareMode.STRICT);
}
@Test
public void whenUsingCompareModeOrBoolean_thenBothAreSame() throws JSONException {
String actual = "{id:123,name:\"John\",zip:\"33025\"}";
JSONAssert.assertEquals("{id:123,name:\"John\"}", actual, JSONCompareMode.LENIENT);
JSONAssert.assertEquals("{id:123,name:\"John\"}", actual, false);
actual = "{id:123,name:\"John\"}";
JSONAssert.assertNotEquals("{name:\"John\"}", actual, JSONCompareMode.STRICT);
JSONAssert.assertNotEquals("{name:\"John\"}", actual, true);
}
@Test
public void givenDifferentOrderForJsonObject_whenAssertEquals_thenPass() throws JSONException {
String result = "{id:1,name:\"John\"}";
JSONAssert.assertEquals("{name:\"John\",id:1}", result, JSONCompareMode.STRICT);
JSONAssert.assertEquals("{name:\"John\",id:1}", result, JSONCompareMode.LENIENT);
}
@Test
public void givenDifferentTypes_whenAssertEqualsSameValue_thenPass() throws JSONException {
JSONObject expected = new JSONObject();
JSONObject actual = new JSONObject();
expected.put("id", Integer.valueOf(12345));
actual.put("id", Double.valueOf(12345));
JSONAssert.assertEquals(expected, actual, false);
JSONAssert.assertEquals(expected, actual, JSONCompareMode.LENIENT);
}
@Test
public void givenNestedObjects_whenAssertEquals_thenPass() throws JSONException {
String result = "{id:1,name:\"Juergen\", address:{city:\"Hollywood\", " + "state:\"LA\", zip:91601}}";
JSONAssert.assertEquals("{id:1,name:\"Juergen\", address:{city:\"Hollywood\", " + "state:\"LA\", zip:91601}}", result, false);
}
@Test
public void whenMessageUsedInAssertion_thenDisplayMessageOnFailure() throws JSONException {
String actual = "{id:123,name:\"John\"}";
String failureMessage = "Only one field is expected: name";
try {
JSONAssert.assertEquals(failureMessage, "{name:\"John\"}", actual, JSONCompareMode.STRICT);
} catch (AssertionError ae) {
assertThat(ae.getMessage()).containsIgnoringCase(failureMessage);
}
}
@Test
public void givenArray_whenComparing_thenOrderMustMatchForStrict() throws JSONException {
String result = "[Alex, Barbera, Charlie, Xavier]";
JSONAssert.assertEquals("[Charlie, Alex, Xavier, Barbera]", result, JSONCompareMode.LENIENT);
JSONAssert.assertEquals("[Alex, Barbera, Charlie, Xavier]", result, JSONCompareMode.STRICT);
JSONAssert.assertNotEquals("[Charlie, Alex, Xavier, Barbera]", result, JSONCompareMode.STRICT);
}
@Test
public void givenArray_whenComparingExtended_thenNotEqual() throws JSONException {
String result = "[1,2,3,4,5]";
JSONAssert.assertEquals("[1,2,3,4,5]", result, JSONCompareMode.LENIENT);
JSONAssert.assertNotEquals("[1,2,3]", result, JSONCompareMode.LENIENT);
JSONAssert.assertNotEquals("[1,2,3,4,5,6]", result, JSONCompareMode.LENIENT);
}
@Test
public void whenComparingSizeOfArray_thenPass() throws JSONException {
String names = "{names:[Alex, Barbera, Charlie, Xavier]}";
JSONAssert.assertEquals("{names:[4]}", names, new ArraySizeComparator(JSONCompareMode.LENIENT));
}
@Test
public void whenComparingContentsOfArray_thenPass() throws JSONException {
String ratings = "{ratings:[3.2,3.5,4.1,5,1]}";
JSONAssert.assertEquals("{ratings:[1,5]}", ratings, new ArraySizeComparator(JSONCompareMode.LENIENT));
}
@Test
public void givenValueMatcher_whenComparingUsingRegex_thenPass() throws IllegalArgumentException, JSONException {
JSONAssert.assertEquals("{entry:{id:x}}", "{entry:{id:1, id:2}}", new CustomComparator(JSONCompareMode.STRICT, new Customization("entry.id", new RegularExpressionValueMatcher<Object>("\\d"))));
JSONAssert.assertNotEquals("{entry:{id:x}}", "{entry:{id:1, id:as}}", new CustomComparator(JSONCompareMode.STRICT, new Customization("entry.id", new RegularExpressionValueMatcher<Object>("\\d"))));
}
}
@@ -0,0 +1,7 @@
package com.baeldung.serenity;
import net.serenitybdd.jbehave.SerenityStory;
public class GithubUserProfilePayloadIntegrationTest extends SerenityStory {
}
@@ -0,0 +1,33 @@
package com.baeldung.serenity;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.thucydides.core.annotations.Managed;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertThat;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
@RunWith(SerenityRunner.class)
public class GoogleSearchLiveTest {
@Managed(driver = "chrome")
private WebDriver browser;
@Test
public void whenGoogleBaeldungThenShouldSeeEugen() {
browser.get("https://www.google.com/ncr");
browser.findElement(By.name("q")).sendKeys("baeldung", Keys.ENTER);
new WebDriverWait(browser, 5).until(visibilityOfElementLocated(By.cssSelector("._ksh")));
assertThat(browser.findElement(By.cssSelector("._ksh")).getText(), containsString("Eugen (Baeldung)"));
}
}
@@ -0,0 +1,27 @@
package com.baeldung.serenity;
import com.baeldung.serenity.pageobjects.GoogleSearchPageObject;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.thucydides.core.annotations.Managed;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
@RunWith(SerenityRunner.class)
public class GoogleSearchPageObjectLiveTest {
@Managed(driver = "chrome")
private WebDriver browser;
private GoogleSearchPageObject googleSearch;
@Test
public void whenGoogleBaeldungThenShouldSeeEugen() {
googleSearch.open();
googleSearch.searchFor("baeldung");
googleSearch.resultMatches("Eugen (Baeldung)");
}
}
@@ -0,0 +1,44 @@
package com.baeldung.serenity;
import com.baeldung.serenity.screenplay.GoogleSearchResults;
import com.baeldung.serenity.screenplay.SearchForKeyword;
import com.baeldung.serenity.screenplay.StartWith;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.abilities.BrowseTheWeb;
import net.thucydides.core.annotations.Managed;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import static net.serenitybdd.screenplay.GivenWhenThen.givenThat;
import static net.serenitybdd.screenplay.GivenWhenThen.seeThat;
import static net.serenitybdd.screenplay.GivenWhenThen.then;
import static net.serenitybdd.screenplay.GivenWhenThen.when;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.hasItem;
@RunWith(SerenityRunner.class)
public class GoogleSearchScreenplayLiveTest {
@Managed(driver = "chrome")
private WebDriver browser;
private Actor kitty = Actor.named("kitty");
@Before
public void setup() {
kitty.can(BrowseTheWeb.with(browser));
}
@Test
public void whenGoogleBaeldungThenShouldSeeEugen() {
givenThat(kitty).wasAbleTo(StartWith.googleSearchPage());
when(kitty).attemptsTo(SearchForKeyword.of("baeldung"));
then(kitty).should(seeThat(GoogleSearchResults.displayed(), hasItem(containsString("Eugen (Baeldung)"))));
}
}
@@ -0,0 +1,73 @@
package com.baeldung.serenity;
import com.baeldung.serenity.membership.MemberStatusSteps;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.thucydides.core.annotations.Steps;
import net.thucydides.core.annotations.Title;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import static com.baeldung.serenity.membership.Commodity.MacBookPro;
import static com.baeldung.serenity.membership.MemberGrade.Bronze;
import static com.baeldung.serenity.membership.MemberGrade.Gold;
import static com.baeldung.serenity.membership.MemberGrade.Silver;
@RunWith(SerenityRunner.class)
public class MemberStatusIntegrationTest {
@Steps
private MemberStatusSteps memberSteps;
@Test
public void membersShouldStartWithBronzeStatus() {
memberSteps.aClientJoinsTheMemberProgram();
memberSteps.theMemberShouldHaveAStatusOf(Bronze);
}
@Test
@Title("Members earn Silver grade after 1000 points ($10,000)")
public void earnsSilverAfterSpends$10000() {
memberSteps.aClientJoinsTheMemberProgram();
memberSteps.theMemberSpends(10_000);
memberSteps.theMemberShouldHaveAStatusOf(Silver);
}
@Test
@Title("Members with 2,000 points should earn Gold grade when added 3,000 points ($30,000)")
public void memberWith2000PointsEarnsGoldAfterSpends$30000() {
memberSteps.aMemberHasPointsOf(2000);
memberSteps.theMemberSpends(30_000);
memberSteps.theMemberShouldHaveAStatusOf(Gold);
}
@Test
@Title("Members with 50,000 points can exchange a MacBook Pro")
public void memberWith50000PointsCanExchangeAMacbookpro() {
memberSteps.aMemberHasPointsOf(50_000);
memberSteps.aMemberExchangeA(MacBookPro);
memberSteps.memberShouldHavePointsLeft();
}
/**
* This test should fail, comment out <code>@Ignore</code> to see how failed test can be reflected in Serenity report. <br/>
*/
@Test
@Ignore
@Title("Members with 500 points should have a Gold status when added 4,000 points ($40,000)")
public void memberWith500PointsEarnsGoldAfterSpends$40000() {
memberSteps.aMemberHasPointsOf(500);
memberSteps.theMemberSpends(40_000);
memberSteps.theMemberShouldHaveAStatusOf(Gold);
}
@Test
@Ignore
@Title("Members with 100 points would have a Gold status when added 10,000 points ($100,000)")
public void memberWith100EarnsGoldAfterSpends$100000() {
memberSteps.aMemberHasPointsOf(100);
memberSteps.theMemberSpends(100_000);
memberSteps.theMemberShouldHaveAStatusOf(Gold);
}
}
@@ -0,0 +1,30 @@
package com.baeldung.serenity.github;
import net.thucydides.core.annotations.Step;
import org.hamcrest.Matchers;
import java.io.IOException;
import static net.serenitybdd.rest.SerenityRest.rest;
import static net.serenitybdd.rest.SerenityRest.then;
class GithubRestAssuredUserAPISteps {
private String api;
@Step("Given the github REST API for user profile")
void withUserProfileAPIEndpoint() {
api = "https://api.github.com/users/{username}";
}
@Step("When looking for {0} via the api")
void getProfileOfUser(String username) throws IOException {
rest().get(api, username);
}
@Step("Then there should be a login field with value {0} in payload of user {0}")
void profilePayloadShouldContainLoginValue(String username) {
then().body("login", Matchers.equalTo(username));
}
}
@@ -0,0 +1,48 @@
package com.baeldung.serenity.github;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.thucydides.core.annotations.Step;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.hamcrest.Matchers;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
public class GithubRestUserAPISteps {
private String api;
private GitHubUser resource;
@Step("Given the github REST API for user profile")
public void withUserProfileAPIEndpoint() {
api = "https://api.github.com/users/%s";
}
@Step("When looking for {0} via the api")
public void getProfileOfUser(String username) throws IOException {
HttpResponse httpResponse = getGithubUserProfile(api, username);
resource = retrieveResourceFromResponse(httpResponse, GitHubUser.class);
}
@Step("Then there should be a login field with value {0} in payload of user {0}")
public void profilePayloadShouldContainLoginValue(String username) {
assertThat(username, Matchers.is(resource.getLogin()));
}
private static <T> T retrieveResourceFromResponse(final HttpResponse response, final Class<T> clazz) throws IOException {
final String jsonFromResponse = EntityUtils.toString(response.getEntity());
final ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return mapper.readValue(jsonFromResponse, clazz);
}
private static HttpResponse getGithubUserProfile(String api, String username) throws IOException {
HttpUriRequest request = new HttpGet(String.format(api, username));
return HttpClientBuilder.create().build().execute(request);
}
}
@@ -0,0 +1,30 @@
package com.baeldung.serenity.github;
import net.thucydides.core.annotations.Steps;
import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;
import java.io.IOException;
public class GithubUserProfilePayloadStepDefinitions {
@Steps
private GithubRestAssuredUserAPISteps userAPISteps;
@Given("github user profile api")
public void givenGithubUserProfileApi() {
userAPISteps.withUserProfileAPIEndpoint();
}
@When("looking for $user via the api")
public void whenLookingForProfileOf(String user) throws IOException {
userAPISteps.getProfileOfUser(user);
}
@Then("github's response contains a 'login' payload same as $user")
public void thenGithubsResponseContainsAloginPayloadSameAs(String user) {
userAPISteps.profilePayloadShouldContainLoginValue(user);
}
}
@@ -0,0 +1,44 @@
package com.baeldung.serenity.membership;
import net.thucydides.core.annotations.Pending;
import net.thucydides.core.annotations.Step;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
public class MemberStatusSteps {
private Member member;
@Step("Given a member has {0} points")
public void aMemberHasPointsOf(int points) {
member = Member.withInitialPoints(points);
}
@Step("Then the member grade should be {0}")
public void theMemberShouldHaveAStatusOf(MemberGrade grade) {
assertThat(member.getGrade(), equalTo(grade));
}
@Step("When the member spends ${0} ")
public void theMemberSpends(int moneySpent) {
member.spend(moneySpent);
}
@Step("Given client joins membership program")
public void aClientJoinsTheMemberProgram() {
member = Member.withInitialPoints(0);
}
@Pending
@Step("When the member exchange {}")
public void aMemberExchangeA(Commodity commodity) {
// TODO
}
@Pending
@Step("Then the member should have points left")
public void memberShouldHavePointsLeft() {
}
}
@@ -0,0 +1,31 @@
package com.baeldung.serenity.pageobjects;
import net.thucydides.core.annotations.DefaultUrl;
import net.thucydides.core.pages.PageObject;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
@DefaultUrl("https://www.google.com/ncr")
public class GoogleSearchPageObject extends PageObject {
@FindBy(name = "q")
private WebElement search;
@FindBy(css = "._ksh")
private WebElement result;
public void searchFor(String keyword) {
search.sendKeys(keyword, Keys.ENTER);
}
public void resultMatches(String expected) {
withTimeoutOf(5, SECONDS).waitFor(result).waitUntilVisible();
assertThat(result.getText(), containsString(expected));
}
}
@@ -0,0 +1,17 @@
package com.baeldung.serenity.screenplay;
import net.serenitybdd.core.pages.PageObject;
import net.serenitybdd.screenplay.targets.Target;
import net.thucydides.core.annotations.DefaultUrl;
/**
* @author baoqiang
*/
@DefaultUrl("https://www.google.com/ncr")
class GoogleSearchPage extends PageObject {
static final Target SEARCH_RESULT_TITLES = Target.the("search results").locatedBy("._ksh");
static final Target SEARCH_INPUT_BOX = Target.the("search input box").locatedBy("#lst-ib");
}
@@ -0,0 +1,18 @@
package com.baeldung.serenity.screenplay;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Question;
import net.serenitybdd.screenplay.questions.Text;
import java.util.List;
public class GoogleSearchResults implements Question<List<String>> {
public static Question<List<String>> displayed() {
return new GoogleSearchResults();
}
public List<String> answeredBy(Actor actor) {
return Text.of(GoogleSearchPage.SEARCH_RESULT_TITLES).viewedBy(actor).asList();
}
}
@@ -0,0 +1,27 @@
package com.baeldung.serenity.screenplay;
import net.serenitybdd.core.steps.Instrumented;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Task;
import net.serenitybdd.screenplay.actions.Enter;
import net.thucydides.core.annotations.Step;
import org.openqa.selenium.Keys;
public class SearchForKeyword implements Task {
@Step("{0} searches for '#keyword'")
public <T extends Actor> void performAs(T actor) {
actor.attemptsTo(Enter.theValue(keyword).into(GoogleSearchPage.SEARCH_INPUT_BOX).thenHit(Keys.RETURN));
}
private String keyword;
public SearchForKeyword(String keyword) {
this.keyword = keyword;
}
public static Task of(String keyword) {
return Instrumented.instanceOf(SearchForKeyword.class).withProperties(keyword);
}
}
@@ -0,0 +1,23 @@
package com.baeldung.serenity.screenplay;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Task;
import net.serenitybdd.screenplay.actions.Open;
import net.thucydides.core.annotations.Step;
import static net.serenitybdd.screenplay.Tasks.instrumented;
public class StartWith implements Task {
public static StartWith googleSearchPage() {
return instrumented(StartWith.class);
}
private GoogleSearchPage googleSearchPage;
@Step("{0} starts a google search")
public <T extends Actor> void performAs(T t) {
t.attemptsTo(Open.browserOn().the(googleSearchPage));
}
}
@@ -0,0 +1,72 @@
package com.baeldung.serenity.spring;
import com.baeldung.serenity.spring.steps.AdderServiceSteps;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.serenitybdd.junit.spring.integration.SpringIntegrationClassRule;
import net.thucydides.core.annotations.Steps;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import static com.baeldung.serenity.spring.RandomNumberUtil.randomInt;
import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_CLASS;
@RunWith(Suite.class)
@Suite.SuiteClasses({ AdderClassDirtiesContextIntegrationTest.DirtiesContextIntegrationTest.class, AdderClassDirtiesContextIntegrationTest.AnotherDirtiesContextIntegrationTest.class })
public class AdderClassDirtiesContextIntegrationTest {
@RunWith(SerenityRunner.class)
@ContextConfiguration(classes = AdderService.class)
public static abstract class Base {
@Steps
AdderServiceSteps adderServiceSteps;
@ClassRule
public static SpringIntegrationClassRule springIntegrationClassRule = new SpringIntegrationClassRule();
void whenAccumulate_thenSummedUp() {
adderServiceSteps.whenAccumulate();
adderServiceSteps.summedUp();
}
void whenAdd_thenSumWrong() {
adderServiceSteps.whenAdd();
adderServiceSteps.sumWrong();
}
void whenAdd_thenSummedUp() {
adderServiceSteps.whenAdd();
adderServiceSteps.summedUp();
}
}
@DirtiesContext(classMode = AFTER_CLASS)
public static class AnotherDirtiesContextIntegrationTest extends Base {
@Test
public void givenNumber_whenAdd_thenSumWrong() {
super.whenAdd_thenSummedUp(); // expecting zero
adderServiceSteps.givenBaseAndAdder(randomInt(), randomInt());
super.whenAccumulate_thenSummedUp();
super.whenAdd_thenSumWrong();
}
}
@DirtiesContext(classMode = AFTER_CLASS)
public static class DirtiesContextIntegrationTest extends Base {
@Test
public void givenNumber_whenAdd_thenSumWrong() {
super.whenAdd_thenSummedUp(); // expecting zero
adderServiceSteps.givenBaseAndAdder(randomInt(), randomInt());
super.whenAccumulate_thenSummedUp();
super.whenAdd_thenSumWrong();
}
}
}
@@ -0,0 +1,20 @@
package com.baeldung.serenity.spring;
import io.restassured.module.mockmvc.RestAssuredMockMvc;
import net.serenitybdd.jbehave.SerenityStory;
import org.jbehave.core.annotations.BeforeStory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
@ContextConfiguration(classes = { AdderController.class, AdderService.class })
public class AdderIntegrationTest extends SerenityStory {
@Autowired
private AdderService adderService;
@BeforeStory
public void init() {
RestAssuredMockMvc.standaloneSetup(new AdderController(adderService));
}
}
@@ -0,0 +1,56 @@
package com.baeldung.serenity.spring;
import com.baeldung.serenity.spring.steps.AdderConstructorDependencySteps;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.serenitybdd.junit.spring.integration.SpringIntegrationMethodRule;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import static com.baeldung.serenity.spring.RandomNumberUtil.randomInt;
/**
* @author aiet
*/
@RunWith(SerenityRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@ContextConfiguration(classes = AdderService.class)
public class AdderMethodDirtiesContextDependencyWorkaroundIntegrationTest {
private AdderConstructorDependencySteps adderSteps;
@Autowired
private AdderService adderService;
@Before
public void init() {
adderSteps = new AdderConstructorDependencySteps(adderService);
}
@Test
public void _1_givenNumber_whenAdd_thenSumWrong() {
adderSteps.whenAdd();
adderSteps.summedUp();
}
@Rule
public SpringIntegrationMethodRule springIntegration = new SpringIntegrationMethodRule();
@DirtiesContext
@Test
public void _0_givenNumber_whenAddAndAccumulate_thenSummedUp() {
adderSteps.givenBaseAndAdder(randomInt(), randomInt());
adderSteps.whenAccumulate();
adderSteps.summedUp();
adderSteps.whenAdd();
adderSteps.sumWrong();
}
}
@@ -0,0 +1,53 @@
package com.baeldung.serenity.spring;
import com.baeldung.serenity.spring.steps.AdderServiceSteps;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.serenitybdd.junit.spring.integration.SpringIntegrationMethodRule;
import net.thucydides.core.annotations.Steps;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import static com.baeldung.serenity.spring.RandomNumberUtil.randomInt;
/**
* @author aiet
*/
@RunWith(SerenityRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@ContextConfiguration(classes = AdderService.class)
public class AdderMethodDirtiesContextInitWorkaroundIntegrationTest {
@Steps
private AdderServiceSteps adderServiceSteps;
@Before
public void init() {
adderServiceSteps.givenBaseAndAdder(randomInt(), randomInt());
}
@Test
public void _1_givenNumber_whenAdd_thenSumWrong() {
adderServiceSteps.whenAdd();
adderServiceSteps.summedUp();
}
@Rule
public SpringIntegrationMethodRule springIntegration = new SpringIntegrationMethodRule();
@DirtiesContext
@Test
public void _0_givenNumber_whenAddAndAccumulate_thenSummedUp() {
adderServiceSteps.whenAccumulate();
adderServiceSteps.summedUp();
adderServiceSteps.whenAdd();
adderServiceSteps.sumWrong();
}
}
@@ -0,0 +1,48 @@
package com.baeldung.serenity.spring;
import com.baeldung.serenity.spring.steps.AdderServiceSteps;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.serenitybdd.junit.spring.integration.SpringIntegrationMethodRule;
import net.thucydides.core.annotations.Steps;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import static com.baeldung.serenity.spring.RandomNumberUtil.randomInt;
/**
* @author aiet
*/
@RunWith(SerenityRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@ContextConfiguration(classes = AdderService.class)
public class AdderMethodDirtiesContextIntegrationTest {
@Steps
private AdderServiceSteps adderServiceSteps;
@Test
public void _1_givenNumber_whenAdd_thenSumWrong() {
adderServiceSteps.whenAdd();
adderServiceSteps.summedUp();
}
@Rule
public SpringIntegrationMethodRule springIntegration = new SpringIntegrationMethodRule();
@DirtiesContext
@Test
public void _0_givenNumber_whenAddAndAccumulate_thenSummedUp() {
adderServiceSteps.givenBaseAndAdder(randomInt(), randomInt());
adderServiceSteps.whenAccumulate();
adderServiceSteps.summedUp();
adderServiceSteps.whenAdd();
adderServiceSteps.sumWrong();
}
}
@@ -0,0 +1,62 @@
package com.baeldung.serenity.spring;
import com.baeldung.serenity.spring.steps.AdderSteps;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.serenitybdd.junit.spring.integration.SpringIntegrationMethodRule;
import net.thucydides.core.annotations.Steps;
import org.junit.*;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.test.context.ContextConfiguration;
/**
* Unit test for simple App.
*/
@RunWith(SerenityRunner.class)
@ContextConfiguration(locations = "classpath:adder-beans.xml")
public class AdderMethodRuleIntegrationTest {
private static Logger LOG = LoggerFactory.getLogger(AdderMethodRuleIntegrationTest.class);
@BeforeClass
public static void initClass() {
LOG.info("static adder before test class: {}", staticAdder);
}
@AfterClass
public static void destroyClass() {
LOG.info("static adder after test class: {}", staticAdder);
}
@Before
public void init() {
LOG.info("adder before test: {}", adder);
staticAdder = adder;
}
@After
public void destroy() {
LOG.info("adder after test: {}", adder);
}
@Rule
public SpringIntegrationMethodRule springMethodIntegration = new SpringIntegrationMethodRule();
@Steps
private AdderSteps adderSteps;
@Value("#{props['adder']}")
private int adder;
private static int staticAdder;
@Test
public void givenNumber_whenAdd_thenSummedUp() {
adderSteps.givenNumber();
adderSteps.whenAdd(adder);
adderSteps.thenSummedUp();
}
}
@@ -0,0 +1,34 @@
package com.baeldung.serenity.spring;
import com.baeldung.serenity.spring.steps.AdderRestSteps;
import io.restassured.module.mockmvc.RestAssuredMockMvc;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.thucydides.core.annotations.Steps;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static com.baeldung.serenity.spring.RandomNumberUtil.randomInt;
/**
* @author aiet
*/
@RunWith(SerenityRunner.class)
public class AdderMockMvcIntegrationTest {
@Before
public void init() {
RestAssuredMockMvc.standaloneSetup(new PlainAdderController());
}
@Steps
AdderRestSteps steps;
@Test
public void givenNumber_whenAdd_thenSummedUp() throws Exception {
steps.givenCurrentNumber();
steps.whenAddNumber(randomInt());
steps.thenSummedUp();
}
}
@@ -0,0 +1,27 @@
package com.baeldung.serenity.spring;
import com.baeldung.serenity.spring.steps.AdderServiceSteps;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.thucydides.core.annotations.Steps;
import org.junit.Test;
import org.junit.runner.RunWith;
import static com.baeldung.serenity.spring.RandomNumberUtil.randomInt;
/**
* @author aiet
*/
@RunWith(SerenityRunner.class)
public class AdderServiceIntegrationTest {
@Steps
private AdderServiceSteps adderServiceSteps;
@Test
public void givenNumber_whenAdd_thenSummedUp() {
adderServiceSteps.givenBaseAndAdder(randomInt(), randomInt());
adderServiceSteps.whenAdd();
adderServiceSteps.summedUp();
}
}
@@ -0,0 +1,31 @@
package com.baeldung.serenity.spring;
import com.baeldung.serenity.spring.steps.AdderSteps;
import net.serenitybdd.junit.spring.integration.SpringIntegrationSerenityRunner;
import net.thucydides.core.annotations.Steps;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.test.context.ContextConfiguration;
/**
* Unit test for simple App.
*/
@RunWith(SpringIntegrationSerenityRunner.class)
@ContextConfiguration(locations = "classpath:adder-beans.xml")
public class AdderSpringSerenityRunnerIntegrationTest {
@Steps
private AdderSteps adderSteps;
@Value("#{props['adder']}")
private int adder;
@Test
public void givenNumber_whenAdd_thenSummedUp() {
adderSteps.givenNumber();
adderSteps.whenAdd(adder);
adderSteps.thenSummedUp();
}
}
@@ -0,0 +1,13 @@
package com.baeldung.serenity.spring;
import org.apache.commons.lang3.RandomUtils;
/**
* @author aiet
*/
public class RandomNumberUtil {
public static int randomInt() {
return RandomUtils.nextInt(1, 10);
}
}
@@ -0,0 +1,44 @@
package com.baeldung.serenity.spring.steps;
import com.baeldung.serenity.spring.AdderService;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
/**
* @author aiet
*/
public class AdderConstructorDependencySteps {
private AdderService adderService;
public AdderConstructorDependencySteps(AdderService adderService) {
this.adderService = adderService;
}
private int givenNumber;
private int base;
private int sum;
public void givenBaseAndAdder(int base, int adder) {
this.base = base;
adderService.baseNum(base);
this.givenNumber = adder;
}
public void whenAdd() {
sum = adderService.add(givenNumber);
}
public void summedUp() {
assertEquals(base + givenNumber, sum);
}
public void sumWrong() {
assertNotEquals(base + givenNumber, sum);
}
public void whenAccumulate() {
sum = adderService.accumulate(givenNumber);
}
}
@@ -0,0 +1,35 @@
package com.baeldung.serenity.spring.steps;
import io.restassured.module.mockmvc.response.MockMvcResponse;
import net.thucydides.core.annotations.Step;
import java.io.UnsupportedEncodingException;
import static io.restassured.module.mockmvc.RestAssuredMockMvc.given;
import static org.hamcrest.core.IsEqual.equalTo;
/**
* @author aiet
*/
public class AdderRestSteps {
private MockMvcResponse mockMvcResponse;
private int currentNum;
@Step("get the current number")
public void givenCurrentNumber() throws UnsupportedEncodingException {
currentNum = Integer.valueOf(given().when().get("/adder/current").mvcResult().getResponse().getContentAsString());
}
@Step("adding {0}")
public void whenAddNumber(int num) {
mockMvcResponse = given().queryParam("num", num).when().post("/adder");
currentNum += num;
}
@Step("got the sum")
public void thenSummedUp() {
mockMvcResponse.then().statusCode(200).body(equalTo(currentNum + ""));
}
}
@@ -0,0 +1,45 @@
package com.baeldung.serenity.spring.steps;
import com.baeldung.serenity.spring.AdderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
/**
* @author aiet
*/
@ContextConfiguration(classes = AdderService.class)
public class AdderServiceSteps {
@Autowired
private AdderService adderService;
private int givenNumber;
private int base;
private int sum;
public void givenBaseAndAdder(int base, int adder) {
this.base = base;
adderService.baseNum(base);
this.givenNumber = adder;
}
public void whenAdd() {
sum = adderService.add(givenNumber);
}
public void summedUp() {
assertEquals(base + givenNumber, sum);
}
public void sumWrong() {
assertNotEquals(base + givenNumber, sum);
}
public void whenAccumulate() {
sum = adderService.accumulate(givenNumber);
}
}
@@ -0,0 +1,29 @@
package com.baeldung.serenity.spring.steps;
import net.thucydides.core.annotations.Step;
import static com.baeldung.serenity.spring.RandomNumberUtil.randomInt;
/**
* @author aiet
*/
public class AdderSteps {
int currentNumber;
int sum;
@Step("given current number")
public void givenNumber() {
currentNumber = randomInt();
}
@Step("add up {0}")
public void whenAdd(int adder) {
sum = currentNumber + adder;
}
@Step("summed up")
public void thenSummedUp() {
}
}
@@ -0,0 +1,32 @@
package com.baeldung.serenity.spring.stories;
import com.baeldung.serenity.spring.steps.AdderRestSteps;
import net.thucydides.core.annotations.Steps;
import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;
/**
* @author aiet
*/
public class AdderStory {
@Steps
AdderRestSteps restSteps;
@Given("a number")
public void givenANumber() throws Exception {
restSteps.givenCurrentNumber();
}
@When("I submit another number $num to adder")
public void whenISubmitToAdderWithNumber(int num) {
restSteps.whenAddNumber(num);
}
@Then("I get a sum of the numbers")
public void thenIGetTheSum() {
restSteps.thenSummedUp();
}
}
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<util:properties id="props">
<prop key="adder">
4
</prop>
</util:properties>
</beans>