问题
My method looks like this:
public class Decompile extends JdbcDaoSupport
public void getRunner(){
String val = this.getJdbcTemplate().queryForObject(sql,String.class, new Object[]{1001});
}
}
Please suggest how I would mock this.
回答1:
an EasyMock-3.0 example
String sql = "select * from t1";
Object[] params = new Object[] { 1001 };
JdbcTemplate t = EasyMock.createMock(JdbcTemplate.class);
EasyMock.expect(
t.queryForObject(sql, String.class, params)).andReturn("res");
EasyMock.replay(t);
回答2:
@Mock
JdbcTemplate jdbctemplate;
@Test
public void testRun(){
when(jdbctemplate.queryForObject(anyString(),eq(String.class),anyObject()).thenReturn("data");
}
回答3:
Use JMockit, the code will be like this:
@Mocked
JdbcTemplate jdbcTemplate
new Expectations() {
jdbcTemplate.queryForObject(sql,String.class, new Object[]{1001});
result = "result you want";
}
More information about JMockit is here.
回答4:
Using Mockito, you can also mock the queryForObject(..) method as follows :
@Mock
JdbcTemplate jdbctemplate;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void testRun(){
when(jdbctemplate.queryForObject(eq("input string"), refEq(new Object[]{1001}), eq(String.class))).thenReturn("data");
}
Some additional source of information - http://sourcesnippets.blogspot.com/2013/06/jdbc-dao-unit-test-using-mockito.html
来源:https://stackoverflow.com/questions/13818712/how-to-mock-jdbctemplate-queryforobject-method