How do I write unit test (JUnit) to check Database connection using DAO class?

6.7k views Asked by At

I have a DAO class called PersonDAO and I am using it to get info about People from Database. I want to write unit test to check the database connection. This is what I have so far

@Test( expected= SQLException.class)
public void testDatabaseConnection()
    throws Exception {



}

Also, how do I write unit test for findAll() method? This is what I have if I am storing people info in a map. But, I would like to know what changes if I have a database instead of a map

@Test
public void testFindAll()
    throws Exception {

    Map< Integer, PersonDTO > people = new LinkedHashMap<>();
    people = PersonDAO.findAll();

    assertEquals( PersonDTO.getTotalDept(), people.size() );
}
2

There are 2 answers

6
Branislav Lazic On

Basically, you are talking about integration tests if you want to test your DAO on "live" database.

PersonDTO personDto;
Connection connection;

@Before
public void setUp() {
    personDto = new PersonDTO();
    connection = ConnectionUtil.someMethodThatReturnsConnection();
}

@Test
public void testIfConnectionNotNull() {
    assertNotNull(connection);
}

@Test
public void testIfDAONotNull() {
    assertNotNull(personDto);
}

@Test
public void testFindAll() {
    // Let's presume you have 4 records
    assertEquals(4, personDto.findAll().size());
}

In case you want to stay on JUnit, Mockito, EasyMock... are an answer.

0
Rash On

Take a look at this question to answer your first question - how to create a database connection. JUNIT test case for connection with database

To answer your second question, on how to test "findAll", you need to ask yourself what does this method does. E.g. it brings all user records, then first check how many users are there in your table and store that in a variable. Then insert another user and again make a call to findAll and count how many rows are returned. Then test if you have previousCount + 1 == currentCount