Last active
April 28, 2017 03:44
-
-
Save kuoshenghsu/4e3c45bff0519c9acb57518467af2a30 to your computer and use it in GitHub Desktop.
[junit] 測試網路連結
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
for junit 用,測試網路連線置放於 Test Method 中,若網路連線不通則該 Test Case 會略過,也可以擺放於 @before中,每項測試執行時檢查