You do not want to connect to a real server in the unit test. If you want to actually connect to a real server, this is technically an integration test.
Since you are testing client code, you should use unit test, so you do not need to connect to a real server. Instead, you can use layouts to simulate a server connection. This is really great because you can simulate conditions that would be difficult to achieve if you were using a real server (for example, the connection was not in the middle of the session, etc.).
Testing modules with mocks will also make tests run faster, since you donβt need to connect to anything so that there is no I / O delay.
Since you contacted another question, I will use this sample code (resold here for clarity). I created a class called MyClass with the foo() method, which connects to the URL and returns true or false if the connection is successful, Since the related question is:
public class MyClass { private String url = "http://example.com"; public boolean foo(){ try { HttpURLConnection.setFollowRedirects(false); HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(); con.setRequestMethod("HEAD"); con.setConnectTimeout(5000);
I will use Mockito to create mock objects, as this is one of the most popular object mock libraries. In addition, since the code creates a new URL object in the foo method (which is not a better design), I will use the PowerMock library, which can intercept calls to new . In real production code, I recommend using dependency injection or at least the extraction method to create a URL object for the factory method so that you can redefine it to make testing easier. But since I am following your example, I will not change anything.
Here is the test code using Mockito and Powermock to check for timeouts:
import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net.URL; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.junit.Assert.*; @RunWith(PowerMockRunner.class)
This test passes in less than a second, which is much faster than actually waiting more than 5 seconds for a real timeout!