JUnit5 execution condition that checks whether a connection to public Internet is available.
First, you add this to your pom.xml:
<dependency>
<groupId>com.yegor256</groupId>
<artifactId>jping</artifactId>
<version>0.1.0</version>
<scope>test</scope>
</dependency>Then, you use it like this:
import com.yegor256.WeAreOnline;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ExtendWith(WeAreOnline.class)
final class MyTest {
@Test
void canDownloadViaHttp() throws Exception {
new URL("https://www.google.com").openStream();
}
}Or if need to override default settings:
import com.yegor256.OnlineMeans;
import com.yegor256.Request;
import com.yegor256.RequestStrategy;
import com.yegor256.WeAreOnline;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ExtendWith(WeAreOnline.class)
final class MyTest {
@Test
@OnlineMeans(
url = "https://www.amazon.com",
connectTimeout = 500,
readTimeout = 1500
)
void canDownloadViaHttp() throws Exception {
new URL("https://www.amazon.com").openStream();
}
}It is also possible to configure a few requests:
import com.yegor256.OnlineMeans;
import com.yegor256.Request;
import com.yegor256.RequestStrategy;
import com.yegor256.WeAreOnline;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ExtendWith(WeAreOnline.class)
final class MyTest {
@Test
@OnlineMeans(
requests = {
@Request(url = "https://www.google.com"),
@Request(
url = "http://127.0.0.1:1",
strategy = RequestStrategy.OPTIONAL
)
}
)
void canDownloadViaHttp() throws Exception {
new URL("https://www.google.com").openStream();
}
}When requests are used, each request is checked in parallel.
MANDATORY requests must succeed, while OPTIONAL ones may fail.
The old url attribute is still supported for backward compatibility.
We don't want this unit test to be executed when no Internet connection
is available. The WeAreOnline execution condition will prevent JUnit5 from
executing the test when you are offline.
Fork repository, make changes, send us a pull request.
We will review your changes and apply them to the master branch shortly,
provided they don't violate our quality standards. To avoid frustration,
before sending us your pull request please run full Maven build:
mvn clean install -PquliceYou will need Maven 3.3+ and Java 8+.