模拟getJdbcTemplate方法

时间:2014-10-15 12:42:13

标签: java mockito junit4

我的方案如下:

我在 SampleDao 界面中有no setter methods,在 SampleDaoImpl

中有no direct field

参考:How to mock getJdbcTemplate().queryForObject()?

public interface SampleDao {
    // some methods
}

public class SampleDaoImpl extends JdbcDaoSupport implements SampleDao {
    // implementation of some methods
    public String someMethod(String param1, String param2){
        // .....//
        List<String> data = getJdbcTemplate().query(.....);  // -> getJdbcTemplate() is the method of JdbcDaoSupport to get JdbcTemplate
    }
}

我想模仿getJdbcTemplate().query(.....) getJdbcTemplate() JdbcDaoSupport类的SampleDaoImpl类的结果,SampleDao扩展@RunWith(Parameterized.class) public class MockSampleDao { String param1 = "", param2 = ""; @Mock SampleDao sampleDao = new SampleDaoImpl(); public MockSampleDao(String param1, String param2) { super(); this.param1 = param1; this.param2 = param2; } @Parameterized.Parameters public static Collection primeNumbers() { return Arrays.asList(new Object[][] { { "test1", "test1" }, { "test2", "test2" } }); } @Test public void testSomeMethod(){ try { // HOW TO MOCK THE RESULT FROM getJdbcTemplate().query() HERE sampleDao.someMethod(param1, param2); } catch (Exception e) { e.printStackTrace(); } } } ,{{1}}。

我的测试用例如下:

SampleDaoImpl 的创建对象并分配给 SampleDao

{{1}}

2 个答案:

答案 0 :(得分:3)

你在嘲笑错误的对象。您正在尝试测试SampleDaoImpl.someMethod(),因此您必须创建具体 SampleDaoImpl实例,而不是模拟实例。

一旦有了具体的实例,就可以调用setJdbcTemplate()并传入模拟的 JdbcTemplate对象。最后,您可以控制该模拟的行为,以便query()调用someMethod()时,将返回您的首选数据。

例如:

public class MockSampleDao {

    // parameterized stuff omitted for brevity

    @Test
    public void testSomeMethod() throws Exception {

      SampleDaoImpl impl = new SampleDaoImpl();
      JdbcTemplate template = mock(JdbcTemplate.class);
      List<String> someList = // populate this list
      when(template.query(....)).thenReturn(someList);

      impl.setJdbcTemplate(template);
      impl.someMethod(param1, param2);

      // further testing etc.
    }

}

答案 1 :(得分:-1)

它应该如下所示(根据您要覆盖的JdbcTemplate的查询API调整模拟):

@RunWith(Parameterized.class)
public class MockSampleDao extends SampleDaoImpl{
      JdbcTemplate jdbcTemplate = mock(JdbcTemplate.class);

     @Override
     protected JdbcTemplate getJdbcTemplate(){
        return jdbcTemplate;
     }

    @Test
    public void testSomeMethod(){
        try {
             when(jdbcTemplate.query(/* put here the api that you want to overload*/)).
             thenReturn(/* the mock output that you want */);

            sampleDao.someMethod(param1, param2);
        } catch (Exception e) {
            e.printStackTrace();
        }
}