how to simulate lack of network connectivity in unit testing

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

提交回复
热议问题