This commit is contained in:
Jonathan Cook
2019-10-23 15:01:44 +02:00
parent db85c8f275
commit 684ec0d2e3
20486 changed files with 1642483 additions and 0 deletions
@@ -0,0 +1,10 @@
package com.baeldung.rest.cucumber;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
@RunWith(Cucumber.class)
@CucumberOptions(features = "classpath:Feature")
public class CucumberIntegrationTest {
}
@@ -0,0 +1,104 @@
package com.baeldung.rest.cucumber;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
import static com.github.tomakehurst.wiremock.client.WireMock.containing;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.verify;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import com.github.tomakehurst.wiremock.WireMockServer;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class StepDefinition {
private static final String CREATE_PATH = "/create";
private static final String APPLICATION_JSON = "application/json";
private final InputStream jsonInputStream = this.getClass().getClassLoader().getResourceAsStream("cucumber.json");
private final String jsonString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z").next();
private final WireMockServer wireMockServer = new WireMockServer(options().dynamicPort());
private final CloseableHttpClient httpClient = HttpClients.createDefault();
@When("^users upload data on a project$")
public void usersUploadDataOnAProject() throws IOException {
wireMockServer.start();
configureFor("localhost", wireMockServer.port());
stubFor(post(urlEqualTo(CREATE_PATH))
.withHeader("content-type", equalTo(APPLICATION_JSON))
.withRequestBody(containing("testing-framework"))
.willReturn(aResponse().withStatus(200)));
HttpPost request = new HttpPost("http://localhost:" + wireMockServer.port() + "/create");
StringEntity entity = new StringEntity(jsonString);
request.addHeader("content-type", APPLICATION_JSON);
request.setEntity(entity);
HttpResponse response = httpClient.execute(request);
assertEquals(200, response.getStatusLine().getStatusCode());
verify(postRequestedFor(urlEqualTo(CREATE_PATH))
.withHeader("content-type", equalTo(APPLICATION_JSON)));
wireMockServer.stop();
}
@When("^users want to get information on the (.+) project$")
public void usersGetInformationOnAProject(String projectName) throws IOException {
wireMockServer.start();
configureFor("localhost", wireMockServer.port());
stubFor(get(urlEqualTo("/projects/cucumber")).withHeader("accept", equalTo(APPLICATION_JSON))
.willReturn(aResponse().withBody(jsonString)));
HttpGet request = new HttpGet("http://localhost:" + wireMockServer.port() + "/projects/" + projectName.toLowerCase());
request.addHeader("accept", APPLICATION_JSON);
HttpResponse httpResponse = httpClient.execute(request);
String responseString = convertResponseToString(httpResponse);
assertThat(responseString, containsString("\"testing-framework\": \"cucumber\""));
assertThat(responseString, containsString("\"website\": \"cucumber.io\""));
verify(getRequestedFor(urlEqualTo("/projects/cucumber")).withHeader("accept", equalTo(APPLICATION_JSON)));
wireMockServer.stop();
}
@Then("^the server should handle it and return a success status$")
public void theServerShouldReturnASuccessStatus() {
}
@Then("^the requested data is returned$")
public void theRequestedDataIsReturned() {
}
private String convertResponseToString(HttpResponse response) throws IOException {
InputStream responseStream = response.getEntity().getContent();
Scanner scanner = new Scanner(responseStream, "UTF-8");
String responseString = scanner.useDelimiter("\\Z").next();
scanner.close();
return responseString;
}
}
@@ -0,0 +1,45 @@
package com.baeldung.rest.jbehave;
import org.jbehave.core.configuration.Configuration;
import org.jbehave.core.configuration.MostUsefulConfiguration;
import org.jbehave.core.io.LoadFromClasspath;
import org.jbehave.core.junit.JUnitStories;
import org.jbehave.core.reporters.StoryReporterBuilder;
import org.jbehave.core.steps.InjectableStepsFactory;
import org.jbehave.core.steps.InstanceStepsFactory;
import java.util.Arrays;
import java.util.List;
import static org.jbehave.core.io.CodeLocations.codeLocationFromClass;
import static org.jbehave.core.reporters.Format.CONSOLE;
/**
* @author aiet
*/
public abstract class AbstractStory extends JUnitStories {
abstract String storyName();
@Override
public Configuration configuration() {
return new MostUsefulConfiguration()
.useStoryLoader(new LoadFromClasspath(this.getClass()))
.useStoryReporterBuilder(new StoryReporterBuilder()
.withCodeLocation(codeLocationFromClass(this.getClass()))
.withFormats(CONSOLE));
}
abstract Object stepInstance();
@Override
public InjectableStepsFactory stepsFactory() {
return new InstanceStepsFactory(configuration(), stepInstance());
}
@Override
protected List<String> storyPaths() {
return Arrays.asList(storyName());
}
}
@@ -0,0 +1,59 @@
package com.baeldung.rest.jbehave;
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.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;
import java.io.IOException;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.apache.http.HttpStatus.SC_NOT_FOUND;
import static org.junit.Assert.assertTrue;
public class GithubUserNotFoundSteps {
private String api;
private String nonExistentUser;
private int githubResponseCode;
@Given("github user profile api")
public void givenGithubUserProfileApi() {
api = "https://api.github.com/users/%s";
}
@Given("a random non-existent username")
public void givenANonexistentUsername() {
nonExistentUser = randomAlphabetic(8);
}
@When("I look for the random user via the api")
public void whenILookForTheUserViaTheApi() throws IOException {
githubResponseCode = getGithubUserProfile(api, nonExistentUser)
.getStatusLine()
.getStatusCode();
}
@When("I look for $user via the api")
public void whenILookForSomeNonExistentUserViaTheApi(String user) throws IOException {
githubResponseCode = getGithubUserProfile(api, user)
.getStatusLine()
.getStatusCode();
}
static HttpResponse getGithubUserProfile(String api, String username) throws IOException {
HttpUriRequest request = new HttpGet(String.format(api, username));
return HttpClientBuilder
.create()
.build()
.execute(request);
}
@Then("github respond: 404 not found")
public void thenGithubRespond404NotFound() {
assertTrue(SC_NOT_FOUND == githubResponseCode);
}
}
@@ -0,0 +1,18 @@
package com.baeldung.rest.jbehave;
/**
* @author aiet
*/
public class GithubUserNotFoundStoryLiveTest extends AbstractStory {
@Override
String storyName() {
return "github_user_not_found.story";
}
@Override
Object stepInstance() {
return new GithubUserNotFoundSteps();
}
}
@@ -0,0 +1,40 @@
package com.baeldung.rest.jbehave;
import org.apache.http.entity.ContentType;
import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;
import java.io.IOException;
import static com.baeldung.rest.jbehave.GithubUserNotFoundSteps.getGithubUserProfile;
import static org.junit.Assert.assertEquals;
public class GithubUserResponseMediaTypeSteps {
private String api;
private String validUser;
private String mediaType;
@Given("github user profile api")
public void givenGithubUserProfileApi() {
api = "https://api.github.com/users/%s";
}
@Given("a valid username")
public void givenAValidUsername() {
validUser = "eugenp";
}
@When("I look for the user via the api")
public void whenILookForTheUserViaTheApi() throws IOException {
mediaType = ContentType
.getOrDefault(getGithubUserProfile(api, validUser).getEntity())
.getMimeType();
}
@Then("github respond data of type json")
public void thenGithubRespondDataOfTypeJson() {
assertEquals("application/json", mediaType);
}
}
@@ -0,0 +1,18 @@
package com.baeldung.rest.jbehave;
/**
* @author aiet
*/
public class GithubUserResponseMediaTypeStoryLiveTest extends AbstractStory {
@Override
String storyName() {
return "github_user_response_mediatype.story";
}
@Override
Object stepInstance() {
return new GithubUserResponseMediaTypeSteps();
}
}
@@ -0,0 +1,40 @@
package com.baeldung.rest.jbehave;
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.baeldung.rest.GitHubUser;
import org.baeldung.rest.RetrieveUtil;
import org.hamcrest.Matchers;
import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;
import java.io.IOException;
import static com.baeldung.rest.jbehave.GithubUserNotFoundSteps.getGithubUserProfile;
import static org.hamcrest.MatcherAssert.assertThat;
public class GithubUserResponsePayloadSteps {
private String api;
private GitHubUser resource;
@Given("github user profile api")
public void givenGithubUserProfileApi() {
api = "https://api.github.com/users/%s";
}
@When("I look for $user via the api")
public void whenILookForEugenpViaTheApi(String user) throws IOException {
HttpResponse httpResponse = getGithubUserProfile(api, user);
resource = RetrieveUtil.retrieveResourceFromResponse(httpResponse, GitHubUser.class);
}
@Then("github's response contains a 'login' payload same as $username")
public void thenGithubsResponseContainsAloginPayloadSameAsEugenp(String username) {
assertThat(username, Matchers.is(resource.getLogin()));
}
}
@@ -0,0 +1,18 @@
package com.baeldung.rest.jbehave;
/**
* @author aiet
*/
public class GithubUserResponsePayloadStoryLiveTest extends AbstractStory {
@Override
String storyName() {
return "github_user_response_payload.story";
}
@Override
Object stepInstance() {
return new GithubUserResponsePayloadSteps();
}
}
@@ -0,0 +1,34 @@
package com.baeldung.rest.jbehave;
import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;
import java.util.Random;
import static org.junit.Assert.assertTrue;
public class IncreaseSteps {
private int counter;
private int previousValue;
@Given("a counter")
public void aCounter() {
}
@Given("the counter has any integral value")
public void counterHasAnyIntegralValue() {
counter = new Random().nextInt();
previousValue = counter;
}
@When("the user increases the counter")
public void increasesTheCounter() {
counter++;
}
@Then("the value of the counter must be 1 greater than previous value")
public void theValueOfTheCounterMustBe1Greater() {
assertTrue(1 == counter - previousValue);
}
}
@@ -0,0 +1,38 @@
package com.baeldung.rest.jbehave;
import org.jbehave.core.configuration.Configuration;
import org.jbehave.core.configuration.MostUsefulConfiguration;
import org.jbehave.core.io.LoadFromClasspath;
import org.jbehave.core.junit.JUnitStories;
import org.jbehave.core.reporters.StoryReporterBuilder;
import org.jbehave.core.steps.InjectableStepsFactory;
import org.jbehave.core.steps.InstanceStepsFactory;
import java.util.Arrays;
import java.util.List;
import static org.jbehave.core.io.CodeLocations.codeLocationFromClass;
import static org.jbehave.core.reporters.Format.CONSOLE;
public class IncreaseStoryLiveTest extends JUnitStories {
@Override
public Configuration configuration() {
return new MostUsefulConfiguration()
.useStoryLoader(new LoadFromClasspath(this.getClass()))
.useStoryReporterBuilder(new StoryReporterBuilder()
.withCodeLocation(codeLocationFromClass(this.getClass()))
.withFormats(CONSOLE));
}
@Override
public InjectableStepsFactory stepsFactory() {
return new InstanceStepsFactory(configuration(), new IncreaseSteps());
}
@Override
protected List<String> storyPaths() {
return Arrays.asList("increase.story");
}
}
@@ -0,0 +1,44 @@
package com.baeldung.rest.karate;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.intuit.karate.junit4.Karate;
import cucumber.api.CucumberOptions;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
@RunWith(Karate.class)
@CucumberOptions(features = "classpath:karate")
public class KarateIntegrationTest {
private static final WireMockServer wireMockServer = new WireMockServer();
@BeforeClass
public static void setUp() throws Exception {
wireMockServer.start();
configureFor("localhost", 8080);
stubFor(get(urlEqualTo("/user/get"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{ \"id\": \"1234\", name: \"John Smith\" }")));
stubFor(post(urlEqualTo("/user/create"))
.withHeader("content-type", equalTo("application/json"))
.withRequestBody(containing("id"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{ \"id\": \"1234\", name: \"John Smith\" }")));
}
@AfterClass
public static void tearDown() throws Exception {
wireMockServer.stop();
}
}
@@ -0,0 +1,160 @@
package com.baeldung.rest.wiremock.introduction;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.containing;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.matching;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching;
import static com.github.tomakehurst.wiremock.client.WireMock.verify;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.util.Scanner;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.junit.Rule;
import org.junit.Test;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
public class JUnitManagedIntegrationTest {
private static final String BAELDUNG_WIREMOCK_PATH = "/baeldung/wiremock";
private static final String APPLICATION_JSON = "application/json";
static int port;
static {
try {
// Get a free port
ServerSocket s = new ServerSocket(0);
port = s.getLocalPort();
s.close();
} catch (IOException e) {
// No OPS
}
}
@Rule
public WireMockRule wireMockRule = new WireMockRule(port);
@Test
public void givenJUnitManagedServer_whenMatchingURL_thenCorrect() throws IOException {
stubFor(get(urlPathMatching("/baeldung/.*"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", APPLICATION_JSON)
.withBody("\"testing-library\": \"WireMock\"")));
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet request = new HttpGet(String.format("http://localhost:%s/baeldung/wiremock", port));
HttpResponse httpResponse = httpClient.execute(request);
String stringResponse = convertHttpResponseToString(httpResponse);
verify(getRequestedFor(urlEqualTo(BAELDUNG_WIREMOCK_PATH)));
assertEquals(200, httpResponse.getStatusLine().getStatusCode());
assertEquals(APPLICATION_JSON, httpResponse.getFirstHeader("Content-Type").getValue());
assertEquals("\"testing-library\": \"WireMock\"", stringResponse);
}
@Test
public void givenJUnitManagedServer_whenMatchingHeaders_thenCorrect() throws IOException {
stubFor(get(urlPathEqualTo(BAELDUNG_WIREMOCK_PATH))
.withHeader("Accept", matching("text/.*"))
.willReturn(aResponse()
.withStatus(503)
.withHeader("Content-Type", "text/html")
.withBody("!!! Service Unavailable !!!")));
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet request = new HttpGet(String.format("http://localhost:%s/baeldung/wiremock", port));
request.addHeader("Accept", "text/html");
HttpResponse httpResponse = httpClient.execute(request);
String stringResponse = convertHttpResponseToString(httpResponse);
verify(getRequestedFor(urlEqualTo(BAELDUNG_WIREMOCK_PATH)));
assertEquals(503, httpResponse.getStatusLine().getStatusCode());
assertEquals("text/html", httpResponse.getFirstHeader("Content-Type").getValue());
assertEquals("!!! Service Unavailable !!!", stringResponse);
}
@Test
public void givenJUnitManagedServer_whenMatchingBody_thenCorrect() throws IOException {
stubFor(post(urlEqualTo(BAELDUNG_WIREMOCK_PATH))
.withHeader("Content-Type", equalTo(APPLICATION_JSON))
.withRequestBody(containing("\"testing-library\": \"WireMock\""))
.withRequestBody(containing("\"creator\": \"Tom Akehurst\""))
.withRequestBody(containing("\"website\": \"wiremock.org\""))
.willReturn(aResponse().withStatus(200)));
InputStream jsonInputStream = this.getClass().getClassLoader().getResourceAsStream("wiremock_intro.json");
String jsonString = convertInputStreamToString(jsonInputStream);
StringEntity entity = new StringEntity(jsonString);
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost request = new HttpPost(String.format("http://localhost:%s/baeldung/wiremock", port));
request.addHeader("Content-Type", APPLICATION_JSON);
request.setEntity(entity);
HttpResponse response = httpClient.execute(request);
verify(postRequestedFor(urlEqualTo(BAELDUNG_WIREMOCK_PATH))
.withHeader("Content-Type", equalTo(APPLICATION_JSON)));
assertEquals(200, response.getStatusLine().getStatusCode());
}
@Test
public void givenJUnitManagedServer_whenNotUsingPriority_thenCorrect() throws IOException {
stubFor(get(urlPathMatching("/baeldung/.*")).willReturn(aResponse().withStatus(200)));
stubFor(get(urlPathEqualTo(BAELDUNG_WIREMOCK_PATH)).withHeader("Accept", matching("text/.*")).willReturn(aResponse().withStatus(503)));
HttpResponse httpResponse = generateClientAndReceiveResponseForPriorityTests();
verify(getRequestedFor(urlEqualTo(BAELDUNG_WIREMOCK_PATH)));
assertEquals(503, httpResponse.getStatusLine().getStatusCode());
}
@Test
public void givenJUnitManagedServer_whenUsingPriority_thenCorrect() throws IOException {
stubFor(get(urlPathMatching("/baeldung/.*")).atPriority(1).willReturn(aResponse().withStatus(200)));
stubFor(get(urlPathEqualTo(BAELDUNG_WIREMOCK_PATH)).atPriority(2).withHeader("Accept", matching("text/.*")).willReturn(aResponse().withStatus(503)));
HttpResponse httpResponse = generateClientAndReceiveResponseForPriorityTests();
verify(getRequestedFor(urlEqualTo(BAELDUNG_WIREMOCK_PATH)));
assertEquals(200, httpResponse.getStatusLine().getStatusCode());
}
private static String convertHttpResponseToString(HttpResponse httpResponse) throws IOException {
InputStream inputStream = httpResponse.getEntity().getContent();
return convertInputStreamToString(inputStream);
}
private static String convertInputStreamToString(InputStream inputStream) {
Scanner scanner = new Scanner(inputStream, "UTF-8");
String string = scanner.useDelimiter("\\Z").next();
scanner.close();
return string;
}
private HttpResponse generateClientAndReceiveResponseForPriorityTests() throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet request = new HttpGet(String.format("http://localhost:%s/baeldung/wiremock", port));
request.addHeader("Accept", "text/xml");
return httpClient.execute(request);
}
}
@@ -0,0 +1,54 @@
package com.baeldung.rest.wiremock.introduction;
import com.github.tomakehurst.wiremock.WireMockServer;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.verify;
import static org.junit.Assert.assertEquals;
public class ProgrammaticallyManagedLiveTest {
private static final String BAELDUNG_PATH = "/baeldung";
private WireMockServer wireMockServer = new WireMockServer();
private CloseableHttpClient httpClient = HttpClients.createDefault();
@Test
public void givenProgrammaticallyManagedServer_whenUsingSimpleStubbing_thenCorrect() throws IOException {
wireMockServer.start();
configureFor("localhost", 8080);
stubFor(get(urlEqualTo(BAELDUNG_PATH)).willReturn(aResponse().withBody("Welcome to Baeldung!")));
HttpGet request = new HttpGet("http://localhost:8080/baeldung");
HttpResponse httpResponse = httpClient.execute(request);
String stringResponse = convertResponseToString(httpResponse);
verify(getRequestedFor(urlEqualTo(BAELDUNG_PATH)));
assertEquals("Welcome to Baeldung!", stringResponse);
wireMockServer.stop();
}
private static String convertResponseToString(HttpResponse response) throws IOException {
InputStream responseStream = response.getEntity().getContent();
Scanner scanner = new Scanner(responseStream, "UTF-8");
String stringResponse = scanner.useDelimiter("\\Z").next();
scanner.close();
return stringResponse;
}
}
@@ -0,0 +1,75 @@
package com.baeldung.rest.wiremock.scenario;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.junit.Assert.assertEquals;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.junit.Rule;
import org.junit.Test;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.github.tomakehurst.wiremock.stubbing.Scenario;
public class WireMockScenarioExampleIntegrationTest {
private static final String THIRD_STATE = "third";
private static final String SECOND_STATE = "second";
private static final String TIP_01 = "finally block is not called when System.exit() is called in the try block";
private static final String TIP_02 = "keep your code clean";
private static final String TIP_03 = "use composition rather than inheritance";
private static final String TEXT_PLAIN = "text/plain";
static int port = 9999;
@Rule
public WireMockRule wireMockRule = new WireMockRule(port);
@Test
public void changeStateOnEachCallTest() throws IOException {
createWireMockStub(Scenario.STARTED, SECOND_STATE, TIP_01);
createWireMockStub(SECOND_STATE, THIRD_STATE, TIP_02);
createWireMockStub(THIRD_STATE, Scenario.STARTED, TIP_03);
assertEquals(TIP_01, nextTip());
assertEquals(TIP_02, nextTip());
assertEquals(TIP_03, nextTip());
assertEquals(TIP_01, nextTip());
}
private void createWireMockStub(String currentState, String nextState, String responseBody) {
stubFor(get(urlEqualTo("/java-tip"))
.inScenario("java tips")
.whenScenarioStateIs(currentState)
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", TEXT_PLAIN)
.withBody(responseBody))
.willSetStateTo(nextState)
);
}
private String nextTip() throws ClientProtocolException, IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet request = new HttpGet(String.format("http://localhost:%s/java-tip", port));
HttpResponse httpResponse = httpClient.execute(request);
return firstLineOfResponse(httpResponse);
}
private static String firstLineOfResponse(HttpResponse httpResponse) throws IOException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()))) {
return reader.readLine();
}
}
}
@@ -0,0 +1,21 @@
package org.baeldung.rest;
public class GitHubUser {
private String login;
public GitHubUser() {
super();
}
// API
public String getLogin() {
return login;
}
public void setLogin(final String login) {
this.login = login;
}
}
@@ -0,0 +1,21 @@
package org.baeldung.rest;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
public class RetrieveUtil {
// API
public 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);
}
}
@@ -0,0 +1,10 @@
Feature: Testing a REST API
Users should be able to submit GET and POST requests to a web service, represented by WireMock
Scenario: Data Upload to a web service
When users upload data on a project
Then the server should handle it and return a success status
Scenario: Data retrieval from a web service
When users want to get information on the Cucumber project
Then the requested data is returned
@@ -0,0 +1,19 @@
Meta:
Narrative:
As a user
I want to look up a non-existent user's profile on github
So that I can be sure that the username can not be found on github
Scenario: when a user checks a non-existent user on github, github would respond 'not found'
Given github user profile api
And a random non-existent username
When I look for the random user via the api
Then github respond: 404 not found
When I look for eugenp1 via the api
Then github respond: 404 not found
When I look for eugenp2 via the api
Then github respond: 404 not found
@@ -0,0 +1,13 @@
Meta:
Narrative:
As a user
I want to look up a valid user's profile on github
So that I can know that github responds data of type json
Scenario: when a user checks a valid user's profile on github, github would respond json data
Given github user profile api
And a valid username
When I look for the user via the api
Then github respond data of type json
@@ -0,0 +1,12 @@
Meta:
Narrative:
As a user
I want to look up a valid user's profile on github
So that I can know the login payload should be the same as username
Scenario: when a user checks a valid user's profile on github, github's response json should include a login payload with the same username
Given github user profile api
When I look for eugenp via the api
Then github's response contains a 'login' payload same as eugenp
@@ -0,0 +1,15 @@
JBehave Story - An increase test
Meta:
Narrative:
As a user
I want to increase a counter
So that I can have the counter's value increase by 1
Scenario: when a user increases a counter, its value is increased by 1
Given a counter
And the counter has any integral value
When the user increases the counter
Then the value of the counter must be 1 greater than previous value
@@ -0,0 +1,42 @@
Feature: Testing a REST API with Karate
Scenario: Testing valid GET endpoint
Given url 'http://localhost:8080/user/get'
When method GET
Then status 200
Scenario: Testing an invalid GET endpoint - 404
Given url 'http://localhost:8080/user/wrong'
When method GET
Then status 404
Scenario: Testing the exact response of a GET endpoint
Given url 'http://localhost:8080/user/get'
When method GET
Then status 200
And match $ == {id:"1234",name:"John Smith"}
Scenario: Testing the exact response field value of a GET endpoint
Given url 'http://localhost:8080/user/get'
When method GET
Then status 200
And match $.id == "1234"
Scenario: Testing that GET response contains specific field
Given url 'http://localhost:8080/user/get'
When method GET
Then status 200
And match $ contains {id:"1234"}
Scenario: Test GET response using markers
Given url 'http://localhost:8080/user/get'
When method GET
Then status 200
And match $ == {id:"#notnull",name:"John Smith"}
Scenario: Testing a POST endpoint with request body
Given url 'http://localhost:8080/user/create'
And request { id: '1234' , name: 'John Smith'}
When method POST
Then status 200
And match $ contains {id:"#notnull"}