I am trying to write a unit test for a DAO implemented using MyBatis using annotations. I would like to instantiate that DAO to unit test against my (in-memory) database. However, the only way I see to instantiate it is through a SqlSessionFactory and the only way I see to see instantiate one of those is by using a SqlSessionFactoryBuilder only of whose methods that a configuration file.
However, in my unit test I already have a connection to the in-memory database can I just use that to somehow instantiate the mapper? That would also allow me to mock or spy the Connection later if I needed to for a test.
The
SqlSessionFactoryclass has aopenSession(Connection connection)method. You can use it to retrieve aSqlSessionusing theConnectionyou have to your in memory db.You can build a
SqlSessionFactoryprogrammatically without using a configuration file with the following code:Then you can mock or stub the
DataSourceto return your desiredConnectioninstance.