問題描述
我想用 make db connection 來測試類.我要測試的類在構造函數 Connection
類中接受為參數.我想將模擬對象傳遞給構造函數.你能告訴我一個好的框架,例如如何模擬數據庫連接嗎?
I want to test class with make db connection. Class that I want to test accept as param in constructor Connection
class. I want to pass mock object to the constructor. Can you tell me good framework with example how to mock db connection?
推薦答案
可以使用MockRunner,支持對于 JDBC.像 Mockito 這樣的通用模擬框架也可以工作,但是 JDBC 是一組相互返回的接口,所以手動模擬會很困難.親自查看:如何存根/模擬 JDBC ResultSet 以同時使用 Java 5 和 6?
You can use MockRunner, which has support for JDBC. General mocking frameworks like Mockito will also work, but JDBC is a set of interfaces returning each other so hand-mocking will be hard. See for yourself: How to stub/mock JDBC ResultSet to work both with Java 5 and 6?
然而,模擬 JDBC 是如此脆弱和冗長(無論您使用哪種工具),我建議在一些薄的 DAO 層中抽象 JDBC 訪問(請參閱 @duffymo 答案)或者去 in-內存數據庫,例如 H2.
However mocking JDBC is so brittle and verbose (no matter which tools you use) that I would either suggest abstracting JDBC access within some thin DAO layer (see @duffymo answer) or go for in-memory database like H2.
另見:
- 模擬 JDBC 驅動程序不值得
這篇關于Java 模擬數據庫連接的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!