簡體   English   中英

使用PowerMock-easymock模擬數據庫對象

[英]Mocking of db objects using PowerMock-easymock

我有如下界面ShoppingListDAO。

public interface ShoppingListDAO extends GenericDAO<Object, String> {       
    public List<ShoppingList> getShoppingList(Department department) throws 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;
}

現在我需要使用Mock db Objects測試我實現的DAO類。我搜索了POWERMOCK / EASYMOCK文檔,但是我想大多數API方法都為我提供了一些對象,這些對象為我提供了DAO接口的虛擬實現類。

  1. 有什么方法可以創建CONNECTION的模擬對象(假設我沒有物理數據庫訪問權限)並可以運行ShoppingListDAOImpl類中提供的后續代碼,因為我必須將此模擬用於代碼覆蓋?

  2. 是否有任何方法可以使callableStatement.execute()返回虛擬數據或Exception(具有您的物理數據庫訪問權限),以便可以在JUnit測試用例中對其進行檢查?

我對模擬框架很陌生,所以可能我的要求不切實際。 任何信息都有幫助。

使用EasyMock,Powermock或Mockito等模擬框架,您可以模擬所有內容。 但是我不建議模擬Connection

在您的情況下,我將使用像HSQLDB這樣的內存數據庫來測試您的DAO是否針對實際的DB,而是針對在內存中運行的DB。 這樣,您的測試不依賴任何外部資源,並且可以輕松地在任何環境下運行。

通過針對數據庫測試代碼,您將不再嚴格進行單元測試。 盡管我認為這是可以接受的折衷方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM