Java 使用PowerMock easymock模拟db对象
我有一个界面ShoppingListDAO,如下所示Java 使用PowerMock easymock模拟db对象,java,unit-testing,mocking,Java,Unit Testing,Mocking,我有一个界面ShoppingListDAO,如下所示 public interface ShoppingListDAO extends GenericDAO<Object, String> { public List<ShoppingList> getShoppingList(Department department) throws ShoppingListDAOException; } 公共接口ShoppingListDAO扩展了Generic
public interface ShoppingListDAO extends GenericDAO<Object, String> {
public List<ShoppingList> getShoppingList(Department department) throws ShoppingListDAOException;
}
公共接口ShoppingListDAO扩展了GenericDAO{
公共列表getShoppingList(部门)抛出ShoppingListDAOException;
}
它的实现DAO类类似于下面的一个
public class ShoppingListDAOImpl extends GenericCustomDAO<Object, String> implements ShoppingListDAO {
//.......
public List<ShoppingList> getShoppingList(Department department) throws ShoppingListDAOException {
try {
ds = getDataSource();
connection = ds.getConnection();
callableStatment = connection.prepareCall(SHOPPING_LIST_QRY1);
callableStatment.setString(1, department.getDistributorNumber());
//......
callableStatment.registerOutParameter(4, OracleTypes.CURSOR);
callableStatment.execute();
resultSet= (ResultSet) callableStatment.getObject(4);
while(resultSet.next()) {
//.......
}
} catch (SQLException e) {
e.printStackTrace();
throw new ShoppingListDAOException(e);
} catch (Exception e) {
e.printStackTrace();
throw new ShoppingListDAOException(e);
}finally{
//......
}
}
return shoppingList;
}
公共类ShoppingListDAOImpl扩展了GenericCustomDAO实现ShoppingListDAO{
//.......
公共列表getShoppingList(部门)抛出ShoppingListDAOException{
试试{
ds=getDataSource();
connection=ds.getConnection();
CallableStation=connection.prepareCall(购物清单);
callableStatment.setString(1,department.getDistributorNumber());
//......
registerOutParameter(4,OracleTypes.CURSOR);
callablestation.execute();
resultSet=(resultSet)callablestation.getObject(4);
while(resultSet.next()){
//.......
}
}捕获(SQLE){
e、 printStackTrace();
抛出新的ShoppingListDAOException(e);
}捕获(例外e){
e、 printStackTrace();
抛出新的ShoppingListDAOException(e);
}最后{
//......
}
}
退货清单;
}
现在我需要使用Mock db对象测试我实现的DAO类
方法提供提供DAO接口的虚拟实现类的me对象
ShoppingListDAOImpl
类中提供的后续代码
因为我必须使用这种模拟来实现代码覆盖callableStatement.execute()
返回虚拟数据或异常(使用我们的物理数据库访问),以便我可以签入它
我的JUnit测试用例我对mocking框架很陌生,所以我的要求可能不现实。任何信息都会很有帮助。使用EasyMock、Powermock或Mockito等模拟框架,您可以模拟一切。但我不建议模拟
连接
在您的情况下,我将使用内存中的数据库来测试DAO,而不是使用在内存中运行的数据库。这样,您的测试不依赖于任何外部资源,并且可以轻松地在任何环境中运行
通过对数据库测试代码,您不再严格地进行单元测试。虽然我认为这是一个可以接受的折衷办法。Thx对于这个建议,我会尝试学习并使用内存数据库。但是我可以使用模拟吗。。。我的意思是,如果我先是连接,然后是CallableStatement,然后是resultset,有可能吗???这样我就可以从“execute”方法中得到我想要的任何输出???????