Skip to content

Commit

Permalink
☀️ Mock multiple requests! (#33)
Browse files Browse the repository at this point in the history
  • Loading branch information
Sérgio Martins authored Nov 14, 2020
1 parent 34793be commit 694910e
Show file tree
Hide file tree
Showing 5 changed files with 32 additions and 29 deletions.
8 changes: 4 additions & 4 deletions docs/documentation.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,10 @@ Then, use the [@Mock](../src/test/java/io/company/utils/mocks/Mock.java) annotat

##### Snippet
```java
@Target({ElementType.METHOD, ElementType.TYPE})
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Mock {
Class<? extends MockDefinition> clazz();
Class<? extends MockDefinition>[] clazz();
}
```

Expand All @@ -87,7 +87,7 @@ The annotation may be declared for methods or class types.
##### Example
````java
@Test
@Mock(clazz = ExampleMockModel.class)
@Mock(clazz = {ExampleMockModel.class, OtherExampleMockModel.class})
public void exampleMockedTest() { ... }
````

Expand Down Expand Up @@ -132,7 +132,7 @@ There is a [jenkinsfile](../Jenkinsfile) example available. Use it to get starte
podTemplate(label: "jenkins-slave-base-pod", serviceAccount: "jenkins", containers: [
containerTemplate(
name: "base",
image: "sergiomartins8/jenkins-slave-base:1.0",
image: "sergiomartins8/jenkins-slave-base:latest",
ttyEnabled: true,
command: "cat"
)
Expand Down
45 changes: 24 additions & 21 deletions src/test/java/io/company/utils/listeners/MockListener.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,39 +20,42 @@ public class MockListener implements ITestListener, Loggable {
* <b>TL;DR:</b>
* For this to work, we're using the selenide proxy implementation. Thus, allowing us to intercept and swap any http responses.
* <br>
* This piece of logic extracts the parameter class within the {@link Mock} annotation.
* Then, converts it into a {@link MockDefinition} object.
* This piece of logic extracts the clazz field within the {@link Mock} annotation, containing the array of model objects to be mocked.
* Then, for each model, instantiates it back into a {@link MockDefinition} object.
* <br>
* Having the object, we use it to add its fields to the http response - through a filter.
*
* @param result the current test result.
*/
@Override
public void onTestStart(ITestResult result) {
extractMockAnnotation(result).ifPresent(mock -> {
extractMockAnnotation(result).ifPresent(mockAnnotation -> {
try {
MockDefinition mockDefinition = mock
.clazz()
.getDeclaredConstructor()
.newInstance();
for (Class<? extends MockDefinition> mockedModel : mockAnnotation.clazz()) {
MockDefinition mockDefinition = mockedModel.getDeclaredConstructor().newInstance();

logger().info("Adding response filter for class name '{}'", mock.clazz().getSimpleName());
WebDriverRunner
.getSelenideProxy()
.addResponseFilter(mock.clazz().getSimpleName(), (response, contents, messageInfo) -> {
if (messageInfo.getOriginalRequest().method().equals(mockDefinition.methodName())
&& Pattern.compile(mockDefinition.url()).matcher(messageInfo.getOriginalUrl()).matches()) {
logger().info("Adding response filter from model '{}.class'", mockedModel.getSimpleName());
logger().info("Adding response filter '{}'", mockedModel.getSimpleName().toLowerCase());

logger().info("Mocking content body: {}", mockDefinition.contentBody());
contents.setTextContents(mockDefinition.contentBody());
WebDriverRunner
.getSelenideProxy()
.addResponseFilter(mockedModel.getSimpleName().toLowerCase(), (response, contents, messageInfo) -> {
if (messageInfo.getOriginalRequest().method().equals(mockDefinition.methodName())
&& Pattern.compile(mockDefinition.urlPattern()).matcher(messageInfo.getOriginalUrl()).matches()) {
logger().info("Original url request: {} {}", mockDefinition.methodName(), mockDefinition.urlPattern());
logger().info("Matching pattern: {}", mockDefinition.urlPattern());

logger().info("Mocking response status: {}", mockDefinition.responseStatus());
response.setStatus(mockDefinition.responseStatus());
logger().info("Mocking content body: {}", mockDefinition.contentBody());
contents.setTextContents(mockDefinition.contentBody());

logger().info("Mocking response headers: {}", mockDefinition.headers());
response.headers().add(mockDefinition.headers());
}
});
logger().info("Mocking response status: {}", mockDefinition.responseStatus());
response.setStatus(mockDefinition.responseStatus());

logger().info("Mocking response headers: {}", mockDefinition.headers());
response.headers().add(mockDefinition.headers());
}
});
}
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
logger().error(e.getMessage());
}
Expand Down
4 changes: 2 additions & 2 deletions src/test/java/io/company/utils/mocks/Mock.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@
* <br>
* Example: {@code @Mock({"path1", "path2", ...})}
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Mock {
/**
* Class that represents the mocked data.
*/
Class<? extends MockDefinition> clazz();
Class<? extends MockDefinition>[] clazz();
}
2 changes: 1 addition & 1 deletion src/test/java/io/company/utils/mocks/MockDefinition.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
* <br>
*/
public interface MockDefinition {
String url();
String urlPattern();

default HttpMethod methodName() {
return HttpMethod.GET;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
public class MockExampleModel implements MockDefinition {

@Override
public String url() {
public String urlPattern() {
return "https://www.google.pt/mock";
}

Expand Down

0 comments on commit 694910e

Please sign in to comment.