Mockito : How to test my Dao with mocking?

Viewed 8301

I am newbie to junit and TDD. I am planning to use Mockito to test my dao.

Dao Interface:

package com.test.SpringApp.dao;

import java.util.List;

import com.test.SpringApp.bean.Account;
import com.test.SpringApp.bean.Person;

public interface TestDao {
    List<Account> getAccountDetails(int account_id);
    Person getPersonDetails(int person_id);
}

DaoImpl Class Code:

package com.test.SpringApp.dao;

import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.apache.log4j.Logger;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import com.test.SpringApp.bean.Account;
import com.test.SpringApp.bean.Person;

public class TestDaoImpl implements TestDao {
    private static final Logger logger = Logger.getLogger(TestDaoImpl.class);
    private JdbcTemplate jdbcTemplate;

    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Override
    public List<Account> getAccountDetails(int account_id) {
        try {
            String query = "select * from account where account_id=?";
            SqlRowSet rowset = jdbcTemplate.queryForRowSet(query,account_id);
            Account account = null;
            List<Account> accountDetails = new ArrayList<Account>();
            while (rowset.next()) {
                account = new Account();
                account.setAccountId(rowset.getInt("accountid"));
                account.setAccountType(rowset.getString("accounttype"));
                accountDetails.add(account);
            }
            return accountDetails;
        } catch (Exception e) {
            // TODO: handle exception
            logger.info("Error :" + e.getMessage());
            return null;
        }
    }

    private Person getPersonDetails(int person_id) {
        try {
            String query = "select * from Person where person_id=?";
            SqlRowSet rowset = jdbcTemplate.queryForRowSet(query,person_id);
            Person person = null;
            while (rowset.next()) {
                person = new Person();
                person.setName(rowset.getString("name"));
                stage.setNumber(rowset.getInt("number"));
            }
            return person;
        } catch (Exception e) {
            // TODO: handle exception
            logger.info("Error :" + e.getMessage());
            return null;
        }
    }
}

I am using above mentioned interface and class to get account and person details from database. Could someone please explain me how to write test cases for above mentioned dao interface and class using junit and Mockito.

Help would be appreciated :)

1 Answers
Related