Java mock database connection [closed]

不羁岁月 提交于 2019-11-30 11:44:47
Tomasz Nurkiewicz

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:

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.

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.

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.
}

you can try easymock. it is easy to use i think. you can find a tutorial for reference. easymock

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.

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!