How to simulate a lack of network connectivity in unit testing

The general question is how to simulate (as part of the test case JUnit) the lack of a network connection, as this is an important consideration in some test cases. Is there a way to do this using the Java API (or using the JVM option) so that certain test cases can run when the network is down? (imitated or real?).

A more specific case (if there is no universally applicable solution) is that I do a bunch of XML file processing (including XSD validation), and I need to make sure that nothing happens over the network, in particular, that the attribute values xsi:schemaLocation(hints) are not are used and that all XSDs are actually derived from the classpath. I use Validator with a custom LSResourceResolver which loads any XSD that may be required from the classpath.

I guess I could implement a method resolveResourcefor LSResourceResolver, never to return null(and, therefore, never to deviate from the default behavior of the opening of the usual URI-connection with the resource) but I'm not sure if it will be enough, and in any case, I would feel more confident if I could run tests JUnitin simulated mode on an island (without manually transferring interfaces on my machine).

UPDATE

The accepted answer, namely the approach -DsocksProxyHostprovided exactly the solution that I need, since the JUnit task can take VM parameters (if forkinstalled on true), and therefore I can have the following in the Ant file:

<junit printsummary="true" showoutput="true" fork="true" maxmemory="256m">
    <jvmarg value="-DsocksProxyHost=127.0.0.1"/>
    ...

... contrib:if, , JUnit .

+4
2

, , ... . JVM , -Djava.security.manager, . AFAIR, ( ). . java.net.NetPermission Exception , . , ..

- , -DsocksProxyHost=127.0.0.1. TCP- SOCKS .

+2

Sniffy JUnit - ConnectException , .

@Rule public SniffyRule sniffyRule = new SniffyRule();

@Test
@DisableSockets
public void testDisableSockets() throws IOException {
    try {
        new Socket("google.com", 22);
        fail("Sniffy should have thrown ConnectException");
    } catch (ConnectException e) {
        assertNotNull(e);
    }
}

, . -javaagent:sniffy.jar=5559 JVM localhost:5559 - - , .

Remote connection console

: Sniffy

0

All Articles