-
-
Save marhan/d26c194e6ed98c7f2b96320018a86bf4 to your computer and use it in GitHub Desktop.
How to simulate connect timeout error and test it
This file contains hidden or 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.net.HttpURLConnection; | |
import java.net.ServerSocket; | |
import java.net.Socket; | |
import java.net.SocketTimeoutException; | |
import java.net.URL; | |
import org.testng.Assert; | |
import org.testng.annotations.AfterClass; | |
import org.testng.annotations.BeforeClass; | |
import org.testng.annotations.Test; | |
public class ConnectTimeoutTest { | |
private ServerSocket serverSocket; | |
private int port; | |
@BeforeClass | |
public void beforeClass() throws IOException { | |
//server socket with single element backlog queue (1) and dynamicaly allocated port (0) | |
serverSocket = new ServerSocket(0, 1); | |
//just get the allocated port | |
port = serverSocket.getLocalPort(); | |
//fill backlog queue by this request so consequent requests will be blocked | |
new Socket().connect(serverSocket.getLocalSocketAddress()); | |
} | |
@AfterClass | |
public void afterClass() throws IOException { | |
//some cleanup | |
if (serverSocket != null && !serverSocket.isClosed()) { | |
serverSocket.close(); | |
} | |
} | |
@Test | |
public void testConnect() throws IOException { | |
URL url = new URL("http://localhost:" + port); //use allocated port | |
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); | |
connection.setConnectTimeout(1000); | |
//connection.setReadTimeout(2000); //irelevant in this case | |
try { | |
connection.getInputStream(); | |
} catch (SocketTimeoutException stx) { | |
Assert.assertEquals(stx.getMessage(), "connect timed out"); //that's what are we waiting for | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment