I'm doing my project using Tomcat 7
, JSP
, Servlets
, Log4j
and MySQL
.
I've googled this question for hours with no proper answer.
How can I test my DAO's using DataSource
and JUnit
?
I found this article recently, but don't know how to configure it for my purposes and don't sure if it's a good way of doing it.
I'm having the following DAO hierarchy:
And I'm obtaining the DataSource
in AbstractRepository
in the following way:
...
protected final DataSource ds;
...
public AbstractRepository() {
DataSource dataSource = null;
try {
Context initContext = new InitialContext();
dataSource = (DataSource) initContext
.lookup("java:/comp/env/jdbc/mydb");
} catch (NamingException ex) {
LOG.error("Cannot obtain a connection from the pool", ex);
}
ds = dataSource;
}
...
Would you produce some code sample of the way to solve this problem for example for Entrant Repository Test
?
The code you have in AbstractRepository
is pretty hard to test. The reason is the "smart constructor", that knows where he gets the datasource from. But you still have a number of options. You can either change your code (my choice) so that the constructor receives DataSource
as a parameter, like
public AbstractRepository(DataSource dataSource){
this.ds = dataSource;
}
so you will be able to initialize your repositories in Test environment with some test datasource (a mock?).
Or you can use some mocking Framework, e.g. EasyMock, to create a partial mock of the Repository you want to test. EasyMock creates partial mocks of classes without calling any constructor by default. Then you could either mock the getDataSource()
method (I hope you have one, that is used everywhere you need to access the datasource?) to return the test datasource, or you can set the final ds
field using Reflections (the worse choice, I suppose).