Skip to content

Instantly share code, notes, and snippets.

@anthavio
Created March 5, 2013 17:56
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • 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
}
}
}
@Fatimamostafa
Copy link

Can you help me with sample android application where you've implemented this?

@whatnext
Copy link

Hello :) I don't want to detract from this solution for testing timeouts. I hope it works for everyone! But for anyone looking for an alternative, we just put up a proxy specifically for request timeout testing purposes. You can find it here: https://virtual.blue/software/apps/delay-proxy - and there is usage information here https://virtual.blue/delay-proxy

(apologies - hope you don't think I'm spamming your page - but just to point out this is a non-commercial project and completely free to use...)

@rasher
Copy link

rasher commented Feb 1, 2018

Good practice to have a fail() after line 43, so your test doesn't pass in case the connection works for some reason.

@tmysik
Copy link

tmysik commented Jun 5, 2018

This is read timeout, not connection timeout.

@helpermethod
Copy link

Probably stupid question, but does one actually get a SocketTimeoutException in case of a connection timeout?

@corbym
Copy link

corbym commented Jul 25, 2019

This is read timeout, not connection timeout.

^^ this

@hnadra
Copy link

hnadra commented Mar 25, 2022

No, it is a connect timeout. Java throws the same exception for connect and read timeouts. The difference will be in the message. You can also see the difference in the stack trace.

Connect Timeout

java.net.SocketTimeoutException: connect timed out
	at java.net.PlainSocketImpl.socketConnect(Native Method)
	at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
	at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
	at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
	at java.net.Socket.connect(Socket.java:589)
	at sun.net.NetworkClient.doConnect(NetworkClient.java:175)
        .....

Read Timeout

java.net.SocketTimeoutException: Read timed out
	at java.net.SocketInputStream.socketRead0(Native Method)
	at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
	at java.net.SocketInputStream.read(SocketInputStream.java:171)
	at java.net.SocketInputStream.read(SocketInputStream.java:141)
	at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
	at java.io.BufferedInputStream.read1(BufferedInputStream.java:286)
	at java.io.BufferedInputStream.read(BufferedInputStream.java:345)
        .....

Thanks for sharing the code!

@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