org.bbottema.javasocksproxyserver.junit.SockServerExtension Maven / Gradle / Ivy
/*
* Copyright © 2019 Benny Bottema ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.bbottema.javasocksproxyserver.junit;
import org.bbottema.javasocksproxyserver.SocksServer;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import javax.net.ServerSocketFactory;
/**
* Creates a {@link SocksServer} once, and starts and stops it before and after each test.
*
* Can be used both by JUnit's {@code Rule} and {@code ClassRule} (`the latter being the preferred usage).
*/
public class SockServerExtension implements BeforeAllCallback, AfterAllCallback {
private final SocksServer socksServer;
public SockServerExtension(@NotNull Integer port) {
this(port, ServerSocketFactory.getDefault());
}
public SockServerExtension(@NotNull Integer port, @NotNull ServerSocketFactory serverSocketFactory) {
this.socksServer = new SocksServer(port).setFactory(serverSocketFactory);
}
@Override
public void beforeAll(ExtensionContext context) {
this.socksServer.start();
}
@Override
public void afterAll(ExtensionContext context) {
this.socksServer.stop();
}
}