Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock JdbcTemplate.queryForObject() method

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.

like image 387
buttowski Avatar asked Dec 11 '12 10:12

buttowski


4 Answers

@Mock
JdbcTemplate jdbctemplate;

@Test
public void testRun(){
when(jdbctemplate.queryForObject(anyString(),eq(String.class),anyObject()).thenReturn("data");
}
like image 194
buttowski Avatar answered Oct 02 '22 15:10

buttowski


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);
like image 45
Evgeniy Dorofeev Avatar answered Oct 02 '22 15:10

Evgeniy Dorofeev


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.

like image 43
Gavin Xiong Avatar answered Oct 02 '22 17:10

Gavin Xiong


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

like image 25
Suketu Bhuta Avatar answered Oct 02 '22 17:10

Suketu Bhuta