Support
Quality
Security
License
Reuse
kandi has reviewed wiremock and discovered the below as its top functions. This is intended to give you an instant insight into wiremock implemented functionality, and help decide if they suit your requirements.
HTTP response stubbing, matchable on URL, header and body content patterns
Request verification
Runs in unit tests, as a standalone process or as a WAR app
Configurable via a fluent Java API, JSON files and JSON over HTTP
Record/playback of stubs
Fault injection
Per-request conditional proxying
Browser proxying for request inspection and replacement
Stateful behaviour simulation
Configurable response delays
Building WireMock locally
./gradlew clean test
How to write response in wiremock as a template with list?
testImplementation 'com.github.jknack:handlebars-jackson2:4.3.0'
<!-- https://mvnrepository.com/artifact/com.github.jknack/handlebars-jackson2 -->
<dependency>
<groupId>com.github.jknack</groupId>
<artifactId>handlebars-jackson2</artifactId>
<version>4.3.0</version>
<scope>test</scope>
</dependency>
WireMockServer wireMockServer = new WireMockServer(wireMockConfig().dynamicPort()
.extensions(new ResponseTemplateTransformer(false, "json", Jackson2Helper.INSTANCE)))
{
"place": "{{parameters.place}}",
"users": {{json parameters.users}}
}
{
"place": "New York",
"users": [{"name":"John","age":24},{"name":"Merry","age":31}]
}
-----------------------
testImplementation 'com.github.jknack:handlebars-jackson2:4.3.0'
<!-- https://mvnrepository.com/artifact/com.github.jknack/handlebars-jackson2 -->
<dependency>
<groupId>com.github.jknack</groupId>
<artifactId>handlebars-jackson2</artifactId>
<version>4.3.0</version>
<scope>test</scope>
</dependency>
WireMockServer wireMockServer = new WireMockServer(wireMockConfig().dynamicPort()
.extensions(new ResponseTemplateTransformer(false, "json", Jackson2Helper.INSTANCE)))
{
"place": "{{parameters.place}}",
"users": {{json parameters.users}}
}
{
"place": "New York",
"users": [{"name":"John","age":24},{"name":"Merry","age":31}]
}
-----------------------
testImplementation 'com.github.jknack:handlebars-jackson2:4.3.0'
<!-- https://mvnrepository.com/artifact/com.github.jknack/handlebars-jackson2 -->
<dependency>
<groupId>com.github.jknack</groupId>
<artifactId>handlebars-jackson2</artifactId>
<version>4.3.0</version>
<scope>test</scope>
</dependency>
WireMockServer wireMockServer = new WireMockServer(wireMockConfig().dynamicPort()
.extensions(new ResponseTemplateTransformer(false, "json", Jackson2Helper.INSTANCE)))
{
"place": "{{parameters.place}}",
"users": {{json parameters.users}}
}
{
"place": "New York",
"users": [{"name":"John","age":24},{"name":"Merry","age":31}]
}
-----------------------
testImplementation 'com.github.jknack:handlebars-jackson2:4.3.0'
<!-- https://mvnrepository.com/artifact/com.github.jknack/handlebars-jackson2 -->
<dependency>
<groupId>com.github.jknack</groupId>
<artifactId>handlebars-jackson2</artifactId>
<version>4.3.0</version>
<scope>test</scope>
</dependency>
WireMockServer wireMockServer = new WireMockServer(wireMockConfig().dynamicPort()
.extensions(new ResponseTemplateTransformer(false, "json", Jackson2Helper.INSTANCE)))
{
"place": "{{parameters.place}}",
"users": {{json parameters.users}}
}
{
"place": "New York",
"users": [{"name":"John","age":24},{"name":"Merry","age":31}]
}
-----------------------
testImplementation 'com.github.jknack:handlebars-jackson2:4.3.0'
<!-- https://mvnrepository.com/artifact/com.github.jknack/handlebars-jackson2 -->
<dependency>
<groupId>com.github.jknack</groupId>
<artifactId>handlebars-jackson2</artifactId>
<version>4.3.0</version>
<scope>test</scope>
</dependency>
WireMockServer wireMockServer = new WireMockServer(wireMockConfig().dynamicPort()
.extensions(new ResponseTemplateTransformer(false, "json", Jackson2Helper.INSTANCE)))
{
"place": "{{parameters.place}}",
"users": {{json parameters.users}}
}
{
"place": "New York",
"users": [{"name":"John","age":24},{"name":"Merry","age":31}]
}
Docker Container with Wiremock could not find stub mappings
{
"mappings": [
{
"id": "679dd3ce-55e5-45ee-b270-01dcf1b371ca",
"request": {
"urlPattern": "^/hello",
"method": "GET"
},
"response": {
"status": 200,
"jsonBody": {
"status": "success",
"message": "Hello"
},
"headers": {
"Content-Type": "text/plain"
}
},
"uuid": "679dd3ce-55e5-45ee-b270-01dcf1b371ca"
},
{
"id": "679dd3ce-55e5-45ee-b270-01dcf1b371c2",
"request": {
"urlPattern": "^/hello-2",
"method": "GET"
},
"response": {
"status": 200,
"jsonBody": {
"status": "success",
"message": "Hello-2"
},
"headers": {
"Content-Type": "text/plain"
}
},
"uuid": "679dd3ce-55e5-45ee-b270-01dcf1b371c2"
}
]
}
docker run -it --rm \
-p 8090:8080 \
-v $PWD/samples/hello/stubs:/home/wiremock \
wiremock/wiremock
-----------------------
{
"mappings": [
{
"id": "679dd3ce-55e5-45ee-b270-01dcf1b371ca",
"request": {
"urlPattern": "^/hello",
"method": "GET"
},
"response": {
"status": 200,
"jsonBody": {
"status": "success",
"message": "Hello"
},
"headers": {
"Content-Type": "text/plain"
}
},
"uuid": "679dd3ce-55e5-45ee-b270-01dcf1b371ca"
},
{
"id": "679dd3ce-55e5-45ee-b270-01dcf1b371c2",
"request": {
"urlPattern": "^/hello-2",
"method": "GET"
},
"response": {
"status": 200,
"jsonBody": {
"status": "success",
"message": "Hello-2"
},
"headers": {
"Content-Type": "text/plain"
}
},
"uuid": "679dd3ce-55e5-45ee-b270-01dcf1b371c2"
}
]
}
docker run -it --rm \
-p 8090:8080 \
-v $PWD/samples/hello/stubs:/home/wiremock \
wiremock/wiremock
Unable to run JUnit5 tests with Maven
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.8.2</version>
</dependency>
</dependencies>
</plugin>
Implement different response with WireMock when no request(s) match
try {
fileSource.getBinaryFileNamed(bodyFileName).readContents();
} catch (FileNotFoundException e) {
return WireMock.notFound().withBody("custom body");
}
// Otherwise return the unmodified response definition
-----------------------
{
"mappings": [
{
"name": "Retrieve Items - Success",
"priority": 1, // arbitrary number lower than the second priority
"request": {
"headers": {
"accept": {
"caseInsensitive": true,
"equalTo": "application/json"
}
},
"method": "GET",
"urlPathPattern": "/api/items/(UUID1|UUID2|UUID3|UUID4)"
},
"response": {
"bodyFileName": "items-api/responses/retrieve/{{ request.pathSegments.[2] }}.json",
"headers": {
"content-type": "application/json"
},
"status": 200
}
},
{
"name": "Retrieve Items - 404 Not Found",
"priority": 5, // arbitrary number that is higher than 1
"request": {
"headers": {
"accept": {
"caseInsensitive": true,
"equalTo": "application/json"
}
},
"method": "GET",
"urlPathPattern": "/api/items/[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}"
},
"response": {
"status": 404
}
}
]
}
Wiremock stubs for an API client that has hardcoded urls
JvmProxyConfigurer.configureFor(wireMockServer);
wireMockServer.stubFor(get("/stuff")
.withHost(equalTo("api.sandbox.braintreegateway.com"))
.willReturn(okJson("{ ... }")));
// Test something that uses the Braintree client lib
Matching JSON request body based on JSON Path with logical operators in WireMock
...
{
"matchesJsonPath": "$[?(@.amnt < 20000)]"
}
...
{
"amnt": 20000 // correct format
"amnt": "20000" // incorrect format
}
-----------------------
...
{
"matchesJsonPath": "$[?(@.amnt < 20000)]"
}
...
{
"amnt": 20000 // correct format
"amnt": "20000" // incorrect format
}
How to invoke JUnit5 test runner / Junit tag expressions using Maven Surefire plugin?
pom.xml
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<configuration>
<groups>Demo1Test,Demo2Test,Demo3Test,Demo4Test</groups>
</configuration>
</plugin>
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
@Tag("Demo1Test")
public class Demo1Test {
@Test
void name1(TestInfo info) {
System.out.println(info.getDisplayName());
}
}
-----------------------
pom.xml
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<configuration>
<groups>Demo1Test,Demo2Test,Demo3Test,Demo4Test</groups>
</configuration>
</plugin>
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
@Tag("Demo1Test")
public class Demo1Test {
@Test
void name1(TestInfo info) {
System.out.println(info.getDisplayName());
}
}
quarkus.oidc.auth-server-url for both testing and localhost development
src/test/resources/application.properties
Is there a way to block all external network access from a Java JUnit test?
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<configuration>
<systemPropertyVariables>
<socksProxyHost>localhost</socksProxyHost>
<socksProxyPort>1080</socksProxyPort>
[...]
</systemPropertyVariables>
</configuration>
</plugin>
-----------------------
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.time.Duration;
import java.time.Instant;
public class BlockNetworkByProperty {
public static void main(String[] args) throws Exception {
System.setProperty("sun.net.spi.nameservice.nameservers", "192.168.0.254"); // Pick any dead IP.
System.setProperty("sun.net.spi.nameservice.provider.1", "dns,sun");
Instant start = Instant.now();
System.out.println("Attempting connection.. ");
try {
URL oracle = new URL("https://www.cnet.com/");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
System.out.println("Should not have gotten here.");
} finally {
long secondsPassed = Duration.between(start, Instant.now()).getSeconds();
System.out.println(String.format("%s seconds have passed.", secondsPassed));
}
}
}
Attempting connection..
60 seconds have passed.
Exception in thread "main" java.net.UnknownHostException: www.cnet.com
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184)
...stack trace continues
-----------------------
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.time.Duration;
import java.time.Instant;
public class BlockNetworkByProperty {
public static void main(String[] args) throws Exception {
System.setProperty("sun.net.spi.nameservice.nameservers", "192.168.0.254"); // Pick any dead IP.
System.setProperty("sun.net.spi.nameservice.provider.1", "dns,sun");
Instant start = Instant.now();
System.out.println("Attempting connection.. ");
try {
URL oracle = new URL("https://www.cnet.com/");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
System.out.println("Should not have gotten here.");
} finally {
long secondsPassed = Duration.between(start, Instant.now()).getSeconds();
System.out.println(String.format("%s seconds have passed.", secondsPassed));
}
}
}
Attempting connection..
60 seconds have passed.
Exception in thread "main" java.net.UnknownHostException: www.cnet.com
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184)
...stack trace continues
-----------------------
docker run --network none
-----------------------
@Rule public SniffyRule sniffyRule = new SniffyRule();
@Test
@DisableSockets
public void testDisableSockets() throws IOException {
try {
new Socket("google.com", 443);
fail("Sniffy should have thrown ConnectException");
} catch (ConnectException e) {
assertNotNull(e);
}
}
-----------------------
public class DisableRemoteSocketsExtension implements BeforeAllCallback {
private static final AtomicBoolean APPLIED = new AtomicBoolean(false);
@Override
public void beforeAll(ExtensionContext context) throws Exception {
if (!APPLIED.get()) {
System.out.println("Globally disabling non-loopback sockets");
Socket.setSocketImplFactory(DisableRemoteSocketImpl::forSocket);
ServerSocket.setSocketFactory(DisableRemoteSocketImpl::forServerSocket);
APPLIED.set(true);
}
}
}
com.example.DisableRemoteSocketsExtension
junit.jupiter.extensions.autodetection.enabled=true
public class DisableRemoteSocketImpl extends SocketImpl {
private static final Pattern LOOPBACK_PATTERN =
Pattern.compile("^localhost$|^127(?:\\.[0-9]+){0,2}\\.[0-9]+$|^(?:0*:)*?:?0*1$");
private final SocketImpl delegate;
public DisableRemoteSocketImpl(SocketImpl delegate) {
this.delegate = delegate;
}
public static DisableRemoteSocketImpl forSocket() {
// Mimics implementation in Socket.setImpl()
SocketImpl delegate = newSocksSocketImpl(getDefaultSocketImpl());
return new DisableRemoteSocketImpl(delegate);
}
public static DisableRemoteSocketImpl forServerSocket() {
// Mimics implementation in ServerSocket.setImpl()
SocketImpl delegate = getDefaultSocketImpl();
return new DisableRemoteSocketImpl(delegate);
}
@Override
protected void create(boolean stream) throws IOException {
callDelegate("create", new Class<?>[]{boolean.class}, new Object[]{stream});
}
@Override
protected void connect(String host, int port) throws IOException {
requireLoopbackAddress(host);
callDelegate("connect", new Class<?>[]{String.class, int.class}, new Object[]{host, port});
}
@Override
protected void connect(InetAddress address, int port) throws IOException {
requireLoopbackAddress(address);
callDelegate("connect", new Class<?>[]{InetAddress.class, int.class}, new Object[]{address, port});
}
@Override
protected void connect(SocketAddress address, int timeout) throws IOException {
if (!(address instanceof InetSocketAddress)) {
throw new UnsupportedOperationException("Unsupported address type: " + address);
}
requireLoopbackAddress(((InetSocketAddress) address).getHostString());
callDelegate("connect", new Class<?>[]{SocketAddress.class, int.class}, new Object[]{address, timeout});
}
@Override
protected void bind(InetAddress host, int port) throws IOException {
requireLoopbackAddress(host);
callDelegate("bind", new Class<?>[]{InetAddress.class, int.class}, new Object[]{host, port});
}
@Override
protected void listen(int backlog) throws IOException {
callDelegate("listen", new Class<?>[]{int.class}, new Object[]{backlog});
}
@Override
protected void accept(SocketImpl s) throws IOException {
callDelegate("accept", new Class<?>[]{SocketImpl.class}, new Object[]{s});
}
@Override
protected InputStream getInputStream() throws IOException {
return callDelegate("getInputStream", new Class<?>[]{}, new Object[]{});
}
@Override
protected OutputStream getOutputStream() throws IOException {
return callDelegate("getOutputStream", new Class<?>[]{}, new Object[]{});
}
@Override
protected int available() throws IOException {
return callDelegate("available", new Class<?>[]{}, new Object[]{});
}
@Override
protected void close() throws IOException {
callDelegate("close", new Class<?>[]{}, new Object[]{});
}
@Override
protected void sendUrgentData(int data) throws IOException {
callDelegate("close", new Class<?>[]{int.class}, new Object[]{data});
}
@Override
public void setOption(int optID, Object value) throws SocketException {
delegate.setOption(optID, value);
}
@Override
public Object getOption(int optID) throws SocketException {
return delegate.getOption(optID);
}
private void requireLoopbackAddress(String host) {
if (!LOOPBACK_PATTERN.matcher(host).matches()) {
throw new UnsupportedOperationException("Attempted to connect to remote host: " + host);
}
}
private void requireLoopbackAddress(InetAddress address) {
if (!address.isLoopbackAddress()) {
throw new UnsupportedOperationException("Attempted to connect to remote host: " + address);
}
}
private static SocketImpl createDelegate() {
// Mimics implementation in Socket.setImpl()
return newSocksSocketImpl(getDefaultSocketImpl());
}
private static SocketImpl getDefaultSocketImpl() {
try {
Method factoryMethod = SocketImpl.class.getDeclaredMethod("createPlatformSocketImpl", Boolean.TYPE);
factoryMethod.setAccessible(true);
return (SocketImpl) factoryMethod.invoke(null, false);
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
private static SocketImpl newSocksSocketImpl(SocketImpl delegate) {
try {
Constructor<? extends SocketImpl> constructor = Class.forName("java.net.SocksSocketImpl")
.asSubclass(SocketImpl.class).getDeclaredConstructor(SocketImpl.class);
constructor.setAccessible(true);
return constructor.newInstance(delegate);
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("unchecked")
private <T> T callDelegate(String methodName, Class<?>[] parameterTypes, Object[] args) throws IOException {
try {
Method method = SocketImpl.class.getDeclaredMethod(methodName, parameterTypes);
method.setAccessible(true);
return (T) method.invoke(delegate, args);
} catch (InvocationTargetException invocationTargetException) {
Throwable e = invocationTargetException.getCause();
if (e instanceof IOException) {
throw (IOException) e;
} else if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else if (e instanceof Error) {
throw (Error) e;
} else {
throw new AssertionError(invocationTargetException);
}
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
}
-----------------------
public class DisableRemoteSocketsExtension implements BeforeAllCallback {
private static final AtomicBoolean APPLIED = new AtomicBoolean(false);
@Override
public void beforeAll(ExtensionContext context) throws Exception {
if (!APPLIED.get()) {
System.out.println("Globally disabling non-loopback sockets");
Socket.setSocketImplFactory(DisableRemoteSocketImpl::forSocket);
ServerSocket.setSocketFactory(DisableRemoteSocketImpl::forServerSocket);
APPLIED.set(true);
}
}
}
com.example.DisableRemoteSocketsExtension
junit.jupiter.extensions.autodetection.enabled=true
public class DisableRemoteSocketImpl extends SocketImpl {
private static final Pattern LOOPBACK_PATTERN =
Pattern.compile("^localhost$|^127(?:\\.[0-9]+){0,2}\\.[0-9]+$|^(?:0*:)*?:?0*1$");
private final SocketImpl delegate;
public DisableRemoteSocketImpl(SocketImpl delegate) {
this.delegate = delegate;
}
public static DisableRemoteSocketImpl forSocket() {
// Mimics implementation in Socket.setImpl()
SocketImpl delegate = newSocksSocketImpl(getDefaultSocketImpl());
return new DisableRemoteSocketImpl(delegate);
}
public static DisableRemoteSocketImpl forServerSocket() {
// Mimics implementation in ServerSocket.setImpl()
SocketImpl delegate = getDefaultSocketImpl();
return new DisableRemoteSocketImpl(delegate);
}
@Override
protected void create(boolean stream) throws IOException {
callDelegate("create", new Class<?>[]{boolean.class}, new Object[]{stream});
}
@Override
protected void connect(String host, int port) throws IOException {
requireLoopbackAddress(host);
callDelegate("connect", new Class<?>[]{String.class, int.class}, new Object[]{host, port});
}
@Override
protected void connect(InetAddress address, int port) throws IOException {
requireLoopbackAddress(address);
callDelegate("connect", new Class<?>[]{InetAddress.class, int.class}, new Object[]{address, port});
}
@Override
protected void connect(SocketAddress address, int timeout) throws IOException {
if (!(address instanceof InetSocketAddress)) {
throw new UnsupportedOperationException("Unsupported address type: " + address);
}
requireLoopbackAddress(((InetSocketAddress) address).getHostString());
callDelegate("connect", new Class<?>[]{SocketAddress.class, int.class}, new Object[]{address, timeout});
}
@Override
protected void bind(InetAddress host, int port) throws IOException {
requireLoopbackAddress(host);
callDelegate("bind", new Class<?>[]{InetAddress.class, int.class}, new Object[]{host, port});
}
@Override
protected void listen(int backlog) throws IOException {
callDelegate("listen", new Class<?>[]{int.class}, new Object[]{backlog});
}
@Override
protected void accept(SocketImpl s) throws IOException {
callDelegate("accept", new Class<?>[]{SocketImpl.class}, new Object[]{s});
}
@Override
protected InputStream getInputStream() throws IOException {
return callDelegate("getInputStream", new Class<?>[]{}, new Object[]{});
}
@Override
protected OutputStream getOutputStream() throws IOException {
return callDelegate("getOutputStream", new Class<?>[]{}, new Object[]{});
}
@Override
protected int available() throws IOException {
return callDelegate("available", new Class<?>[]{}, new Object[]{});
}
@Override
protected void close() throws IOException {
callDelegate("close", new Class<?>[]{}, new Object[]{});
}
@Override
protected void sendUrgentData(int data) throws IOException {
callDelegate("close", new Class<?>[]{int.class}, new Object[]{data});
}
@Override
public void setOption(int optID, Object value) throws SocketException {
delegate.setOption(optID, value);
}
@Override
public Object getOption(int optID) throws SocketException {
return delegate.getOption(optID);
}
private void requireLoopbackAddress(String host) {
if (!LOOPBACK_PATTERN.matcher(host).matches()) {
throw new UnsupportedOperationException("Attempted to connect to remote host: " + host);
}
}
private void requireLoopbackAddress(InetAddress address) {
if (!address.isLoopbackAddress()) {
throw new UnsupportedOperationException("Attempted to connect to remote host: " + address);
}
}
private static SocketImpl createDelegate() {
// Mimics implementation in Socket.setImpl()
return newSocksSocketImpl(getDefaultSocketImpl());
}
private static SocketImpl getDefaultSocketImpl() {
try {
Method factoryMethod = SocketImpl.class.getDeclaredMethod("createPlatformSocketImpl", Boolean.TYPE);
factoryMethod.setAccessible(true);
return (SocketImpl) factoryMethod.invoke(null, false);
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
private static SocketImpl newSocksSocketImpl(SocketImpl delegate) {
try {
Constructor<? extends SocketImpl> constructor = Class.forName("java.net.SocksSocketImpl")
.asSubclass(SocketImpl.class).getDeclaredConstructor(SocketImpl.class);
constructor.setAccessible(true);
return constructor.newInstance(delegate);
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("unchecked")
private <T> T callDelegate(String methodName, Class<?>[] parameterTypes, Object[] args) throws IOException {
try {
Method method = SocketImpl.class.getDeclaredMethod(methodName, parameterTypes);
method.setAccessible(true);
return (T) method.invoke(delegate, args);
} catch (InvocationTargetException invocationTargetException) {
Throwable e = invocationTargetException.getCause();
if (e instanceof IOException) {
throw (IOException) e;
} else if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else if (e instanceof Error) {
throw (Error) e;
} else {
throw new AssertionError(invocationTargetException);
}
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
}
-----------------------
public class DisableRemoteSocketsExtension implements BeforeAllCallback {
private static final AtomicBoolean APPLIED = new AtomicBoolean(false);
@Override
public void beforeAll(ExtensionContext context) throws Exception {
if (!APPLIED.get()) {
System.out.println("Globally disabling non-loopback sockets");
Socket.setSocketImplFactory(DisableRemoteSocketImpl::forSocket);
ServerSocket.setSocketFactory(DisableRemoteSocketImpl::forServerSocket);
APPLIED.set(true);
}
}
}
com.example.DisableRemoteSocketsExtension
junit.jupiter.extensions.autodetection.enabled=true
public class DisableRemoteSocketImpl extends SocketImpl {
private static final Pattern LOOPBACK_PATTERN =
Pattern.compile("^localhost$|^127(?:\\.[0-9]+){0,2}\\.[0-9]+$|^(?:0*:)*?:?0*1$");
private final SocketImpl delegate;
public DisableRemoteSocketImpl(SocketImpl delegate) {
this.delegate = delegate;
}
public static DisableRemoteSocketImpl forSocket() {
// Mimics implementation in Socket.setImpl()
SocketImpl delegate = newSocksSocketImpl(getDefaultSocketImpl());
return new DisableRemoteSocketImpl(delegate);
}
public static DisableRemoteSocketImpl forServerSocket() {
// Mimics implementation in ServerSocket.setImpl()
SocketImpl delegate = getDefaultSocketImpl();
return new DisableRemoteSocketImpl(delegate);
}
@Override
protected void create(boolean stream) throws IOException {
callDelegate("create", new Class<?>[]{boolean.class}, new Object[]{stream});
}
@Override
protected void connect(String host, int port) throws IOException {
requireLoopbackAddress(host);
callDelegate("connect", new Class<?>[]{String.class, int.class}, new Object[]{host, port});
}
@Override
protected void connect(InetAddress address, int port) throws IOException {
requireLoopbackAddress(address);
callDelegate("connect", new Class<?>[]{InetAddress.class, int.class}, new Object[]{address, port});
}
@Override
protected void connect(SocketAddress address, int timeout) throws IOException {
if (!(address instanceof InetSocketAddress)) {
throw new UnsupportedOperationException("Unsupported address type: " + address);
}
requireLoopbackAddress(((InetSocketAddress) address).getHostString());
callDelegate("connect", new Class<?>[]{SocketAddress.class, int.class}, new Object[]{address, timeout});
}
@Override
protected void bind(InetAddress host, int port) throws IOException {
requireLoopbackAddress(host);
callDelegate("bind", new Class<?>[]{InetAddress.class, int.class}, new Object[]{host, port});
}
@Override
protected void listen(int backlog) throws IOException {
callDelegate("listen", new Class<?>[]{int.class}, new Object[]{backlog});
}
@Override
protected void accept(SocketImpl s) throws IOException {
callDelegate("accept", new Class<?>[]{SocketImpl.class}, new Object[]{s});
}
@Override
protected InputStream getInputStream() throws IOException {
return callDelegate("getInputStream", new Class<?>[]{}, new Object[]{});
}
@Override
protected OutputStream getOutputStream() throws IOException {
return callDelegate("getOutputStream", new Class<?>[]{}, new Object[]{});
}
@Override
protected int available() throws IOException {
return callDelegate("available", new Class<?>[]{}, new Object[]{});
}
@Override
protected void close() throws IOException {
callDelegate("close", new Class<?>[]{}, new Object[]{});
}
@Override
protected void sendUrgentData(int data) throws IOException {
callDelegate("close", new Class<?>[]{int.class}, new Object[]{data});
}
@Override
public void setOption(int optID, Object value) throws SocketException {
delegate.setOption(optID, value);
}
@Override
public Object getOption(int optID) throws SocketException {
return delegate.getOption(optID);
}
private void requireLoopbackAddress(String host) {
if (!LOOPBACK_PATTERN.matcher(host).matches()) {
throw new UnsupportedOperationException("Attempted to connect to remote host: " + host);
}
}
private void requireLoopbackAddress(InetAddress address) {
if (!address.isLoopbackAddress()) {
throw new UnsupportedOperationException("Attempted to connect to remote host: " + address);
}
}
private static SocketImpl createDelegate() {
// Mimics implementation in Socket.setImpl()
return newSocksSocketImpl(getDefaultSocketImpl());
}
private static SocketImpl getDefaultSocketImpl() {
try {
Method factoryMethod = SocketImpl.class.getDeclaredMethod("createPlatformSocketImpl", Boolean.TYPE);
factoryMethod.setAccessible(true);
return (SocketImpl) factoryMethod.invoke(null, false);
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
private static SocketImpl newSocksSocketImpl(SocketImpl delegate) {
try {
Constructor<? extends SocketImpl> constructor = Class.forName("java.net.SocksSocketImpl")
.asSubclass(SocketImpl.class).getDeclaredConstructor(SocketImpl.class);
constructor.setAccessible(true);
return constructor.newInstance(delegate);
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("unchecked")
private <T> T callDelegate(String methodName, Class<?>[] parameterTypes, Object[] args) throws IOException {
try {
Method method = SocketImpl.class.getDeclaredMethod(methodName, parameterTypes);
method.setAccessible(true);
return (T) method.invoke(delegate, args);
} catch (InvocationTargetException invocationTargetException) {
Throwable e = invocationTargetException.getCause();
if (e instanceof IOException) {
throw (IOException) e;
} else if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else if (e instanceof Error) {
throw (Error) e;
} else {
throw new AssertionError(invocationTargetException);
}
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
}
-----------------------
public class DisableRemoteSocketsExtension implements BeforeAllCallback {
private static final AtomicBoolean APPLIED = new AtomicBoolean(false);
@Override
public void beforeAll(ExtensionContext context) throws Exception {
if (!APPLIED.get()) {
System.out.println("Globally disabling non-loopback sockets");
Socket.setSocketImplFactory(DisableRemoteSocketImpl::forSocket);
ServerSocket.setSocketFactory(DisableRemoteSocketImpl::forServerSocket);
APPLIED.set(true);
}
}
}
com.example.DisableRemoteSocketsExtension
junit.jupiter.extensions.autodetection.enabled=true
public class DisableRemoteSocketImpl extends SocketImpl {
private static final Pattern LOOPBACK_PATTERN =
Pattern.compile("^localhost$|^127(?:\\.[0-9]+){0,2}\\.[0-9]+$|^(?:0*:)*?:?0*1$");
private final SocketImpl delegate;
public DisableRemoteSocketImpl(SocketImpl delegate) {
this.delegate = delegate;
}
public static DisableRemoteSocketImpl forSocket() {
// Mimics implementation in Socket.setImpl()
SocketImpl delegate = newSocksSocketImpl(getDefaultSocketImpl());
return new DisableRemoteSocketImpl(delegate);
}
public static DisableRemoteSocketImpl forServerSocket() {
// Mimics implementation in ServerSocket.setImpl()
SocketImpl delegate = getDefaultSocketImpl();
return new DisableRemoteSocketImpl(delegate);
}
@Override
protected void create(boolean stream) throws IOException {
callDelegate("create", new Class<?>[]{boolean.class}, new Object[]{stream});
}
@Override
protected void connect(String host, int port) throws IOException {
requireLoopbackAddress(host);
callDelegate("connect", new Class<?>[]{String.class, int.class}, new Object[]{host, port});
}
@Override
protected void connect(InetAddress address, int port) throws IOException {
requireLoopbackAddress(address);
callDelegate("connect", new Class<?>[]{InetAddress.class, int.class}, new Object[]{address, port});
}
@Override
protected void connect(SocketAddress address, int timeout) throws IOException {
if (!(address instanceof InetSocketAddress)) {
throw new UnsupportedOperationException("Unsupported address type: " + address);
}
requireLoopbackAddress(((InetSocketAddress) address).getHostString());
callDelegate("connect", new Class<?>[]{SocketAddress.class, int.class}, new Object[]{address, timeout});
}
@Override
protected void bind(InetAddress host, int port) throws IOException {
requireLoopbackAddress(host);
callDelegate("bind", new Class<?>[]{InetAddress.class, int.class}, new Object[]{host, port});
}
@Override
protected void listen(int backlog) throws IOException {
callDelegate("listen", new Class<?>[]{int.class}, new Object[]{backlog});
}
@Override
protected void accept(SocketImpl s) throws IOException {
callDelegate("accept", new Class<?>[]{SocketImpl.class}, new Object[]{s});
}
@Override
protected InputStream getInputStream() throws IOException {
return callDelegate("getInputStream", new Class<?>[]{}, new Object[]{});
}
@Override
protected OutputStream getOutputStream() throws IOException {
return callDelegate("getOutputStream", new Class<?>[]{}, new Object[]{});
}
@Override
protected int available() throws IOException {
return callDelegate("available", new Class<?>[]{}, new Object[]{});
}
@Override
protected void close() throws IOException {
callDelegate("close", new Class<?>[]{}, new Object[]{});
}
@Override
protected void sendUrgentData(int data) throws IOException {
callDelegate("close", new Class<?>[]{int.class}, new Object[]{data});
}
@Override
public void setOption(int optID, Object value) throws SocketException {
delegate.setOption(optID, value);
}
@Override
public Object getOption(int optID) throws SocketException {
return delegate.getOption(optID);
}
private void requireLoopbackAddress(String host) {
if (!LOOPBACK_PATTERN.matcher(host).matches()) {
throw new UnsupportedOperationException("Attempted to connect to remote host: " + host);
}
}
private void requireLoopbackAddress(InetAddress address) {
if (!address.isLoopbackAddress()) {
throw new UnsupportedOperationException("Attempted to connect to remote host: " + address);
}
}
private static SocketImpl createDelegate() {
// Mimics implementation in Socket.setImpl()
return newSocksSocketImpl(getDefaultSocketImpl());
}
private static SocketImpl getDefaultSocketImpl() {
try {
Method factoryMethod = SocketImpl.class.getDeclaredMethod("createPlatformSocketImpl", Boolean.TYPE);
factoryMethod.setAccessible(true);
return (SocketImpl) factoryMethod.invoke(null, false);
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
private static SocketImpl newSocksSocketImpl(SocketImpl delegate) {
try {
Constructor<? extends SocketImpl> constructor = Class.forName("java.net.SocksSocketImpl")
.asSubclass(SocketImpl.class).getDeclaredConstructor(SocketImpl.class);
constructor.setAccessible(true);
return constructor.newInstance(delegate);
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("unchecked")
private <T> T callDelegate(String methodName, Class<?>[] parameterTypes, Object[] args) throws IOException {
try {
Method method = SocketImpl.class.getDeclaredMethod(methodName, parameterTypes);
method.setAccessible(true);
return (T) method.invoke(delegate, args);
} catch (InvocationTargetException invocationTargetException) {
Throwable e = invocationTargetException.getCause();
if (e instanceof IOException) {
throw (IOException) e;
} else if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else if (e instanceof Error) {
throw (Error) e;
} else {
throw new AssertionError(invocationTargetException);
}
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
}
Can I create a spring bean as part of my cucumber step definitions?
@Profile("cucumber")
@TestConfiguration
public class ClockConfiguration {
@Bean
public Clock clock() {
return Clock.fixed(Instant.parse(TestScope.getDateValue()), ZoneId.systemDefault());
}
}
@Given("now is {string})
public void setDateTime(String dateTime) {
TestScope.setDateValue(dateTime);
}
-----------------------
@Profile("cucumber")
@TestConfiguration
public class ClockConfiguration {
@Bean
public Clock clock() {
return Clock.fixed(Instant.parse(TestScope.getDateValue()), ZoneId.systemDefault());
}
}
@Given("now is {string})
public void setDateTime(String dateTime) {
TestScope.setDateValue(dateTime);
}
-----------------------
public void setClock(String dateTime) {
this.clock = Clock.fixed(Instant.parse(dateTime), ZoneId.systemDefault());
}
@Given("now is {string})
public void setDateTime(String dateTime) {
applicationContext.getBean(MyWrapperClock.class).setClock(dateTime);
}
@Bean
public Clock clock() {
return Mockito.mock(Clock.class);
}
@Given("now is {string})
public void setDateTime(String dateTime) {
when(this.clock.instant()).thenReturn(Instant.parse(dateTime));
when(this.clock.getZone()).thenReturn(ZoneId.systemDefault());
}
-----------------------
public void setClock(String dateTime) {
this.clock = Clock.fixed(Instant.parse(dateTime), ZoneId.systemDefault());
}
@Given("now is {string})
public void setDateTime(String dateTime) {
applicationContext.getBean(MyWrapperClock.class).setClock(dateTime);
}
@Bean
public Clock clock() {
return Mockito.mock(Clock.class);
}
@Given("now is {string})
public void setDateTime(String dateTime) {
when(this.clock.instant()).thenReturn(Instant.parse(dateTime));
when(this.clock.getZone()).thenReturn(ZoneId.systemDefault());
}
-----------------------
public void setClock(String dateTime) {
this.clock = Clock.fixed(Instant.parse(dateTime), ZoneId.systemDefault());
}
@Given("now is {string})
public void setDateTime(String dateTime) {
applicationContext.getBean(MyWrapperClock.class).setClock(dateTime);
}
@Bean
public Clock clock() {
return Mockito.mock(Clock.class);
}
@Given("now is {string})
public void setDateTime(String dateTime) {
when(this.clock.instant()).thenReturn(Instant.parse(dateTime));
when(this.clock.getZone()).thenReturn(ZoneId.systemDefault());
}
-----------------------
public void setClock(String dateTime) {
this.clock = Clock.fixed(Instant.parse(dateTime), ZoneId.systemDefault());
}
@Given("now is {string})
public void setDateTime(String dateTime) {
applicationContext.getBean(MyWrapperClock.class).setClock(dateTime);
}
@Bean
public Clock clock() {
return Mockito.mock(Clock.class);
}
@Given("now is {string})
public void setDateTime(String dateTime) {
when(this.clock.instant()).thenReturn(Instant.parse(dateTime));
when(this.clock.getZone()).thenReturn(ZoneId.systemDefault());
}
QUESTION
How to write response in wiremock as a template with list?
Asked 2022-Mar-18 at 20:10I want to use template response in wiremock and set list as a parameter. How to do that?
I set up wiremock in Java:
wireMockServer.stubFor(get(urlPathEqualTo("/somePath"))
.withQueryParam("place.id", equalTo(buildingId))
.willReturn(aResponse()
.withHeader("Content-Type", "application/json")
.withBodyFile("wiremock/response-template.json") //how to set up this file
.withTransformerParameters(Map.of(
"place", "New York",
"users", List.of(new User("John", 24), new User("Merry", 31)) //list to insert
))
.withTransformers("response-template")));
How to write file: response-template.json to have result like this:
{
"place": "New York",
"users": [
{
"name": "John",
"age": 24
},
{
"name": "Marry",
"age": 31
}
]
}
I know that it should start like this:
{
"place": "{{parameters.place}}",
"users": [
???
]
}
I
ANSWER
Answered 2022-Mar-18 at 20:10The easiest solution would be to use Jackson2 Helper or any other helper that can serialize to jsons.
testImplementation 'com.github.jknack:handlebars-jackson2:4.3.0'
<!-- https://mvnrepository.com/artifact/com.github.jknack/handlebars-jackson2 -->
<dependency>
<groupId>com.github.jknack</groupId>
<artifactId>handlebars-jackson2</artifactId>
<version>4.3.0</version>
<scope>test</scope>
</dependency>
WireMockServer wireMockServer = new WireMockServer(wireMockConfig().dynamicPort()
.extensions(new ResponseTemplateTransformer(false, "json", Jackson2Helper.INSTANCE)))
The name of the helper will be json
and that is how you will refer to it from your template.
{
"place": "{{parameters.place}}",
"users": {{json parameters.users}}
}
{
"place": "New York",
"users": [{"name":"John","age":24},{"name":"Merry","age":31}]
}
Of course you can customize Jackson2Helper
and create your own instance with own ObjectMapper
instance - this is useful if you are using Spring
and want to use same serialization options everywhere.
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
No vulnerabilities reported
Save this library and start creating your kit
Save this library and start creating your kit