Skip to content

Commit

Permalink
Make MockWebServerExtension public and allow for server customization (
Browse files Browse the repository at this point in the history
…#532)

* Make MockWebServerExtension public. This is in preparation for
  most likely moving it to part of kiwi-test, i.e., in src/main
* Add ability to customize the MockWebServer by using a
  Consumer<MockWebServer>
* Add a builder. It currently only provides the ability to
  specify your own MockWebServer and the customization Consumer,
  but by using a builder instead of multiple constructors, it
  provides a nicer interface. The no-args constructor still
  exists for situations where no customization is needed.
  • Loading branch information
sleberknight authored Dec 13, 2024
1 parent bbffb45 commit d0f4433
Showing 1 changed file with 35 additions and 2 deletions.
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

0 comments on commit d0f4433

Please sign in to comment.