Skip to content

Commit

Permalink
Merge pull request square#3139 from yschimke/junit5_compat
Browse files Browse the repository at this point in the history
junit 5 compatibility for MockWebServer
  • Loading branch information
swankjesse authored Jan 28, 2017
2 parents 4de39f2 + 5215762 commit f541304
Showing 1 changed file with 14 additions and 25 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,7 @@
import okio.Okio;
import okio.Sink;
import okio.Timeout;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.junit.rules.ExternalResource;

import static okhttp3.internal.Util.closeQuietly;
import static okhttp3.mockwebserver.SocketPolicy.DISCONNECT_AFTER_REQUEST;
Expand All @@ -98,7 +96,7 @@
* A scriptable web server. Callers supply canned responses and the server replays them upon request
* in sequence.
*/
public final class MockWebServer implements TestRule, Closeable {
public final class MockWebServer extends ExternalResource implements Closeable {
static {
Internal.initializeInstanceForTests();
}
Expand Down Expand Up @@ -142,7 +140,7 @@ public final class MockWebServer implements TestRule, Closeable {

private boolean started;

private synchronized void maybeStart() {
@Override protected synchronized void before() {
if (started) return;
try {
start();
Expand All @@ -151,35 +149,18 @@ private synchronized void maybeStart() {
}
}

@Override public Statement apply(final Statement base, Description description) {
return new Statement() {
@Override public void evaluate() throws Throwable {
maybeStart();
try {
base.evaluate();
} finally {
try {
shutdown();
} catch (IOException e) {
logger.log(Level.WARNING, "MockWebServer shutdown failed", e);
}
}
}
};
}

public int getPort() {
maybeStart();
before();
return port;
}

public String getHostName() {
maybeStart();
before();
return inetSocketAddress.getHostName();
}

public Proxy toProxyAddress() {
maybeStart();
before();
InetSocketAddress address = new InetSocketAddress(inetSocketAddress.getAddress(), getPort());
return new Proxy(Proxy.Type.HTTP, address);
}
Expand Down Expand Up @@ -398,6 +379,14 @@ public synchronized void shutdown() throws IOException {
}
}

@Override protected synchronized void after() {
try {
shutdown();
} catch (IOException e) {
logger.log(Level.WARNING, "MockWebServer shutdown failed", e);
}
}

private void serveConnection(final Socket raw) {
executor.execute(new NamedRunnable("MockWebServer %s", raw.getRemoteSocketAddress()) {
int sequenceNumber = 0;
Expand Down

0 comments on commit f541304

Please sign in to comment.