Skip to content

Instantly share code, notes, and snippets.

@kuoshenghsu
Last active April 28, 2017 03:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kuoshenghsu/4e3c45bff0519c9acb57518467af2a30 to your computer and use it in GitHub Desktop.
Save kuoshenghsu/4e3c45bff0519c9acb57518467af2a30 to your computer and use it in GitHub Desktop.
[junit] 測試網路連結
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.HttpClients;
import org.junit.Assume;
/**
* 測試網路連結
*/
public class TestUtils {
private static final String TEST_URL = "http://www.google.com";
private static final int SOCKET_TIMEOUT = 2000;
private static final int CONNECT_TIMEOUT = 2000;
public static void assumeInternetAlive() {
Assume.assumeTrue(isInternetAlive());
}
private static boolean isInternetAlive() {
try {
HttpResponse response = getHttpResponse(TEST_URL);
return response != null && 200 == response.getStatusLine().getStatusCode();
} catch (IOException ex) {
return false;
}
}
private static HttpResponse getHttpResponse(String url) throws IOException {
HttpClient client = HttpClients.createDefault();
HttpUriRequest request = RequestBuilder.get().setUri(url).setConfig(getRequestConfig()).build();
return client.execute(request);
}
private static RequestConfig getRequestConfig() {
return RequestConfig.custom().setSocketTimeout(SOCKET_TIMEOUT).setConnectTimeout(CONNECT_TIMEOUT).build();
}
}
@kuoshenghsu
Copy link
Author

for junit 用,測試網路連線置放於 Test Method 中,若網路連線不通則該 Test Case 會略過,也可以擺放於 @before中,每項測試執行時檢查

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment