Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make MockWebServerExtension public and allow for server customization #532

Merged
merged 1 commit into from
Dec 13, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
package org.kiwiproject.test.okhttp3.mockwebserver;

import static java.util.Objects.isNull;
import static org.kiwiproject.base.KiwiPreconditions.requireNotNull;

import lombok.Builder;
import lombok.Getter;
import lombok.experimental.Accessors;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.kiwiproject.io.KiwiIO;
import org.kiwiproject.util.function.KiwiConsumers;

import java.io.IOException;
import java.util.function.Consumer;

/**
* A simple JUnit Jupiter extension that creates and starts a {@link MockWebServer}
Expand All @@ -18,11 +24,38 @@ public class MockWebServerExtension implements BeforeEachCallback, AfterEachCall

@Getter
@Accessors(fluent = true)
private MockWebServer server;
private final MockWebServer server;

private final Consumer<MockWebServer> serverCustomizer;

/**
* Create a new instance.
* <p>
* The extension will use a default {@link MockWebServer} instance.
* <p>
* If you want to customize the server or provide your own {@link MockWebServer},
* use the builder instead of this constructor.
*/
public MockWebServerExtension() {
this(new MockWebServer(), KiwiConsumers.noOp());
}

/**
* Create a new instance that will use the given {@link MockWebServer} and customizer.
*
* @param server the server
* @param serverCustomizer allows a test to configure the server, e.g., to customize the protocols
* it supports or to serve requests via HTTPS over TLS.
*/
@Builder
MockWebServerExtension(MockWebServer server, Consumer<MockWebServer> serverCustomizer) {
this.server = requireNotNull(server, "server must not be null");
this.serverCustomizer = isNull(serverCustomizer) ? KiwiConsumers.noOp() : serverCustomizer;
}

@Override
public void beforeEach(ExtensionContext context) throws IOException {
server = new MockWebServer();
serverCustomizer.accept(server);
server.start();
}

Expand Down
Loading