Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java mock database connection [closed]

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?

like image 321
nyanev Avatar asked Nov 26 '11 15:11

nyanev


People also ask

What is stubbing Java?

Mocks and stubs are fake Java classes that replace these external dependencies. These fake classes are then instructed before the test starts to behave as you expect. More specifically: A stub is a fake class that comes with preprogrammed return values.

How do you mock in Dbconnection?

You should adhere to Interface Segregation and Dependency Inversion principle by using Inversion of Control with the help of Dependency Injection. This way, you can create a MockDB2Connection, which you inject into the constructor, in your unit tests, while in your real code, you pass a proper DB2Connection.

What is@ mock in Java?

Mockito is a mocking framework, JAVA-based library that is used for effective unit testing of JAVA applications. Mockito is used to mock interfaces so that a dummy functionality can be added to a mock interface that can be used in unit testing.


1 Answers

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
like image 95
Tomasz Nurkiewicz Avatar answered Sep 28 '22 03:09

Tomasz Nurkiewicz