0

I am trying to make a unit test on a method from a DAO class. Dao class is using JDBC. I am trying to unit test it but without using test data base. I must test it using some data structure for storing all the information.

public class UserProfilesDao extends JdbcDaoSupport {

    @Autowired
    private MessageSourceAccessor msa;

        public long getUserServiceId(long userId, int serviceId) {
            String sql = msa.getMessage("sql.select.service_user_id");
            Object[] params = new Object[] { userId, serviceId };
            int[] types = new int[] { Types.INTEGER, Types.INTEGER };
            return getJdbcTemplate().queryForLong(sql, params, types);
        }
}
4
  • 1
    So what is the question? Commented Jan 10, 2016 at 16:51
  • Did you heard of mock or doubles/stub? Commented Jan 10, 2016 at 16:52
  • @SMA yes know about Mocking but till now i was writing tests without using data base. That is why i ask here for some example. Commented Jan 10, 2016 at 16:55
  • @Raja Anbazhagan the question is that i am asking form some help how to make this unit test because after this i have bigger methods to test and i want to have some example, Commented Jan 10, 2016 at 16:57

2 Answers 2

1

getJdbcTemplate() appears to be a method that you want to mock out.

In your unit test, declare a UserProfilesDao member as follows:

@Spy
private UserProfilesDao classToTest;

the @Spy is a mockito annotation.

in your unit test declare a setup method as follows:

@Before
public void preTestSetup()
{
    MockitoAnnotations.initMocks(this);

    doReturn(what ever you want).when(classToTest).queryForLong(
        any(xxx.class),
        any(yyy.class),
        any(zzz.class));
}

where xxx, yyy, and zzz are the queryForLong parameter types.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you :) In doReturn(...) what i have to write. Is is correct to return an user by id ?
Is there a reason for spying the DAO instead of mocking it?
you spy because it is the class you are actually testing. Why would you mock the class you are attempting to test? That seems counterproductive
in the doReturn, return the value that you want to be returned.
0

You can store data in DTO Objects and maintain DTOs in a Map with proper keys. For test, retrieve data from map using key according to your need!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.