Skip to content

Instantly share code, notes, and snippets.

@anthavio
Created March 5, 2013 17:56
Show Gist options
  • Save anthavio/5092439 to your computer and use it in GitHub Desktop.
Save anthavio/5092439 to your computer and use it in GitHub Desktop.
How to simulate connect timeout error and test it
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
}
}
}
@stanio
Copy link

stanio commented Jun 1, 2023

At present, I'm getting:

java.net.ConnectException: Connection refused: connect

instead. I've found this answer that doesn't require a live service to test the client:

        // Connect to a non-routable IP address, such as 10.255.255.1
        URL url = new URL("http://10.255.255.1/");
        URLConnection client = url.openConnection();
        client.setConnectTimeout(100);
        SocketTimeoutException exception =
                assertThrows(SocketTimeoutException.class, () -> client.connect());
        assertEquals("exception message", exception.getMessage(), "connect timed out");

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