how to simulate lack of network connectivity in unit testing

前端 未结 2 2033
再見小時候
再見小時候 2021-01-18 18:45

The general question is how to simulate (as part of a JUnit suite of test cases) lack of network connectivity as this is an important consideration in some test

相关标签:
2条回答
  • 2021-01-18 19:20

    That's not what I would advise to do, but... you can try to use a security manager. By default JVM does not use a security manager, by setting -Djava.security.manager you will activate the default security manager. AFAIR, the default behaviour of the security manager is to block any connections (as long as the permission is not explicitly granted in security policy). But. You will get java.net.NetPermission Exception each time a connection will be blocked. You can also experience problems with local files access, reflection calls and so on.

    Another possibility is to set the network proxy to a non-existent address, like -DsocksProxyHost=127.0.0.1. Then any TCP socket will try to use the SOCKS server and fail.

    0 讨论(0)
  • 2021-01-18 19:23

    Sniffy allows you to block outgoing network connections in your JUnit tests - it will throw a ConnectException whenever you try to establish a new connection.

    @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);
        }
    }
    

    It also allows you to test how your application behaves with broken connectivity in runtime. Just add -javaagent:sniffy.jar=5559 to your JVM arguments and point your browser to localhost:5559 - it will open a web page with all discovered connections to downstream systems and controls to disable certain connections.

    Disclaimer: I'm the author of Sniffy

    0 讨论(0)
提交回复
热议问题