How to mock JdbcTemplate.queryForObject() method

坚强是说给别人听的谎言 提交于 2019-12-21 17:36:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!