how to simulate lack of network connectivity in unit testing

前端 未结 2 2056
再見小時候
再見小時候 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: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

提交回复
热议问题