I am working on a Java web app with unit/integration tests. App gets deployed to Jetty and uses H2 db while running the integration test phase of maven. I’ve one oracle function which is called from dao layer which can not be migrated to H2 db, hence i want to mock/skip this part in code while running the test cases.
I thought of having a flag which can tell if i’m running application in test mode and put the condition in code for it, but doesn’t look like cleaner approach to me. Please suggest best approach to achieve this.
Extract the Oracle native call into a separate class (probably some DAO). Inject that DAO to class that uses it. Create a second implementation of that DAO, doing nothing in place of calling Oracle. During integration testing inject the latter implementation.
Avoid flags in your code. If you are using Spring, use build profiles that will selectively create one implementation or the other.
That’s how dependency injection helps you test your code: if you want to mock some part of the system, just inject mocked version.