简体   繁体   English

程序中间网络连接丢失的测试效果

[英]Testing Effect of Network Connection Drop in The Middle Of Program

I want to test effect of network connection drop exactly before the execution of specific line of a program. 我想在执行程序的特定行之前准确测试网络连接丢失的效果。 Such as consider this execution sequence: 比如考虑这个执行顺序:

1. Connect to database.
2. Get country list from database.
3. Get a random country from list.
4. Get city list of this country from database.

I want to test behavior of program if network connection drops just before statement 4. I'm able test it with debugger by putting a break point, closing database when it hits break point, and then continuing to run program. 如果网络连接在语句4之前丢失,我想测试程序的行为。我可以通过设置断点,在达到断点时关闭数据库,然后继续运行程序来使用调试器测试它。

I wonder how can I accomplish this in a more systematic and robust way. 我想知道如何以更系统和更强大的方式实现这一目标。

Let's make the assumption that the 4 lines of pseudo code are in MyService, and that MyService uses MyDAO to access the database, you would have the following: 让我们假设4行伪代码在MyService中,并且MyService使用MyDAO访问数据库,您将拥有以下内容:

public class MyService {

    private MyDAO myDAO;

    public MySErvice(MyDAO myDAO) {
        this.myDAO = myDAO;
    }

    public List<City> getRandomCityList() {
        List<Country> countries = myDAO.getCountries();
        Country c = pickRandom(countries);
        return myDAO.getCities(country);
    }
}

To test it, use a mocking framework like Mockito to mock MyDAO, and inject this mock into a MyService instance. 要测试它,使用像Mockito这样的模拟框架来模拟MyDAO,并将这个模拟注入MyService实例。 Make the mock throw the same exception as the one thrown by a real MyDAO when the network goes down when its getCities() method is thrown, and see is MyService does the right thing: 当网络因为抛出getCities()方法而关闭时,使模拟抛出与真实MyDAO抛出的异常相同的异常,并且看到MyService做正确的事情:

MyDAO mockDAO = mock(MyDAO.class);
List<Country> countries = Arrays.asList(new Country(...));
when(mockDAO.getCountries()).thenReturn(countries);
when(mockDAO.getCities((Country) any(Country.class))).thenThrow(new NetworkIsDownException());

MyService underTest = new MyService(mockDAO);
// TODO call underTest.getRandomCityList() and check that it does what it should do.

A non-portable solution could be to modify the firewall rules of the system your test is running on, eg on Linux using iptables, to drop the packages and thus simulate a network outage. 一个不可移植的解决方案可能是修改运行测试的系统的防火墙规则,例如在使用iptables的Linux上,丢弃软件包,从而模拟网络中断。

A more portable solution could be to wrap the URI your database is connecting to around some proxy that can simulate network outages, much like ActiveMQ's SocketProxy . 一个更便携的解决方案可能是将数据库连接的URI包装在可以模拟网络中断的代理周围,就像ActiveMQ的SocketProxy一样 This only works if your API connects to your database using an URI, though. 但这仅适用于您的API使用URI连接到数据库的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM