[BAEL-16005] moved articles from libraries to libraries-security and libraries testing. Renamed TinkUnitTest to TinkLiveTest failing due InvalidKeyException

This commit is contained in:
Sjmillington
2019-08-13 16:47:26 +01:00
parent 23cc42b0f1
commit 13f818cccf
53 changed files with 400 additions and 193 deletions

View File

@@ -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));
}
}

View File

@@ -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());
}
}

View File

@@ -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"))));
}
}

View File

@@ -0,0 +1,7 @@
package com.baeldung.serenity;
import net.serenitybdd.jbehave.SerenityStory;
public class GithubUserProfilePayloadIntegrationTest extends SerenityStory {
}

View File

@@ -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)"));
}
}

View File

@@ -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)");
}
}

View File

@@ -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)"))));
}
}

View File

@@ -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);
}
}

View File

@@ -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));
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -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() {
}
}

View File

@@ -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));
}
}

View File

@@ -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");
}

View File

@@ -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();
}
}

View File

@@ -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);
}
}

View File

@@ -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));
}
}

View File

@@ -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();
}
}
}

View File

@@ -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));
}
}

View File

@@ -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();
}
}

View File

@@ -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();
}
}

View File

@@ -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();
}
}

View File

@@ -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();
}
}

View File

@@ -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();
}
}

View File

@@ -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();
}
}

View File

@@ -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();
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -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 + ""));
}
}

View File

@@ -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);
}
}

View File

@@ -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() {
}
}

View File

@@ -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();
}
}