我想在程序的特定行执行之前测试网络连接断开的效果。例如考虑这个执行顺序:
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.
如果网络连接在语句 4 之前断开,我想测试程序的行为。我可以使用调试器测试它,方法是放置一个断点,在遇到断点时关闭数据库,然后继续运行程序。
我想知道如何以更系统、更稳健的方式完成此任务。
最佳答案
假设这 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);
}
}
要对其进行测试,请使用 Mockito 等模拟框架模拟 MyDAO,并将此模拟注入(inject) MyService 实例。使模拟抛出与真正的 MyDAO 抛出的异常相同的异常,当它的 getCities()
方法被抛出时网络出现故障,看看 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.
关于java - 程序中途掉网测试效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13765519/