First, the StudentInfoService class in your example is not amenable to testing, or at least not easy. This is for a very simple reason - there is no way to pass a database connection object to a class, at least not in the method you specify.
To make the class testable, you need to create your own class as follows:
public class StudentInfoService { private Connection conn; public StudentInfoService(Connection conn) { this.conn = conn; } public StudentInfo getStudentInfo(long studentId) {
The above code allows dependency injection through the constructor. You can use installer injection instead of constructor injection if it is more suitable, but usually this is not for DAO / Repository classes, since the class cannot be considered fully formed without a connection.
Dependency injection will allow your test cases to create a connection to the database (which is an employee of your tested class / system) instead of the class / system itself creating collaborator objects. In simpler words, you untie the database connection mechanism from your class. If your class previously looked at the JNDI data source and then created the connection, then it would be unstable if you hadn't deployed it to the container using Apache Cactus or a similar structure like Arquillian , or if you used the built-in container. Having identified the problem of creating a connection from a class, you can now create connections in your unit tests outside the class and provide them to the class as needed, which allows you to run tests inside the Java SE environment.
This will allow you to use a database-oriented database such as DbUnit , which will allow you to configure the database to a known state before each test, then it is passed in conjunction with the StudentInfoService class, and then assert the class state (as well as co-author, etc. e. database) after the test.
It should be emphasized that when you unit test your classes, your classes should be the only systems tested. Elements, such as connections and data sources, are simply employees who can and should be bullied. Some unit tests would use databases such as H2 , HSQL , or Derby for unit tests and use production equivalent database setups for integration and functional testing.