Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking dataSource during Unit Testing

I would like to unit test my DB independent web layer controllers even if the database is down.

But the 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?

like image 727
user847964 Avatar asked Feb 25 '26 04:02

user847964


1 Answers

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.

like image 59
Ryan Stewart Avatar answered Feb 27 '26 18:02

Ryan Stewart