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?
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.
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.
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With