问题
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?
回答1:
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?
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.
See also:
- Mock JDBC driver not worth it
回答2:
Connection is an interface. Any mocking framework will be able to mock it: EasyMock, Mockito, ...
Mocking it isn't different from mocking any other Java interface.
回答3:
I wouldn't create a mock connection - it proves nothing, in my opinion.
I can see why you'd mock the repository/DAO itself after you've tested it fully with a live connection. You'd give the mock repository/DAO to a service or other client because you've already tested it - no need to prove that it works until you do an integration test.
回答4:
You can either use a mocking framework such as the ones mentioned in the above answer (I personally use EasyMock) OR Create you own mock object:
class FakeConnection extends Connection{
// Overrive all method behavious you want to fake.
}
回答5:
you can try easymock. it is easy to use i think. you can find a tutorial for reference. easymock
回答6:
If you are going to reuse that mock on many test cases you can also consider implementing your own implementation of connection and to reuse that implementation everywhere.
回答7:
My Acolyte framework is useful for such purposes -> https://github.com/cchantep/acolyte .
With this lib you can create a connection instance for which you provide handler. Implementing handler, you are able to 'dispatch' query or update : producing resultsets or update count (or warning).
来源:https://stackoverflow.com/questions/8279547/java-mock-database-connection