gpt4 book ai didi

java - 模拟 getJdbcTemplate 方法

转载 作者:行者123 更新时间:2023-11-30 03:43:07 24 4
gpt4 key购买 nike

我的场景如下:

我在 SampleDao 接口(interface)中没有 setter 方法,在 SampleDaoImpl 类中没有直接字段

引用: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 扩展。

我的测试用例如下:

创建了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();
}
}

}

最佳答案

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

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

例如:

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.
}

}

关于java - 模拟 getJdbcTemplate 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26382924/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com