I would like to unit test my DB independent web layer controllers even if the database is down.
But t开发者_开发技巧he transactionManager
bean instantiation fails because the connection cannot be achieved by the bean dataSource
with the given DB credentials.
Also, I have used @Transactional
, @AfterTransaction
and @BeforeTransaction
annotations which I do not want to remove.
Is there a way to define a dummy (or mock) dataSource
where I need not provide any database credentials but still get my transactionManager
bean to be instantiated?
What you're describing is more of an integration test than a unit test. For unit testing, don't start Spring or the transaction manager. Just instantiate your controller and unit test it. For integration tests, consider just using an H2 in-memory database. H2 is extremely fast (much faster than Derby) and excellent for testing when a database is needed.
This is covered in the Spring turtorials. You have to create an in InMemory version of your DAO's.
Look at 6.2 Fix the failing tests
Use dependency injection. You have two standard and well documented options to do this.
- Use a framework such as Google Guice. There will be some overhead for doing this, but it will help you write better, more testable code and has some cool features like scoping which is particularly helpful for web layers.
- Implement DI in your own code by adding a constructor which takes a datasource paramater or a datasource setter method. In production you will pass-in/set your production database but in unit testing you can use a mock datasource which simply logs your operations/transactions.
精彩评论