假设 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,并将此模拟注入 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.