Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
494 views
in Technique[技术] by (71.8m points)

java - Mocking DataSource for JdbcTemplate with Mockito

I'm trying to test a class in a Spring project. I would like to make as many changes as possible in the test class vs. the dao class so that I don't have to retest all sorts things because of a change.

The class I'm working with has a JdbcTemplate template class variable that is instantiated by the following:

setJdbcTemplate(DataSource dataSource) {
    this.template = new JdbcTemplate(dataSource);
}

The method I would like to test makes a template.query(<code>) to run a defined SQL query and return the results to a list.

I created the following in my test case, but I'm not sure how to put it into use. Can I make the following code return a certain list of Strings using Mockito?

DataSource mockedDataSrc = Mockito.mock(DataSource.class);
customerClassDao.setJdbcTemplate(mockedDataSrc); 

Can I somehow use the when or another command to set what I want to be returned to the JdbcTemplate's .query call?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you're testing a DAO it makes no sense at all to mock the data source. What are you testing? You need to make a DAO that interacts with the database.

Once you have that working, you're free to mock the interface-based DAO when testing services that use it. You've already tested the DAO; there's no reason to redo it when testing the services.

I'd say you're off-track if you're mocking the data source when testing the DAO.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...