Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用Easymock时无法识别数据源_Java_Datasource_Easymock - Fatal编程技术网

Java 使用Easymock时无法识别数据源

Java 使用Easymock时无法识别数据源,java,datasource,easymock,Java,Datasource,Easymock,在父类BaseDAO.java中,我有一个方法: public DBWrapper getDBWrapper() { //Obtains the DBwrapper with the data source details } public int getBookRefCode(int bookId) { //I am calling getDBWrapper.executeQuery() to execute query on my database } //在ChildD

在父类BaseDAO.java中,我有一个方法:

public DBWrapper getDBWrapper() {
    //Obtains the DBwrapper with the data source details
}
public int getBookRefCode(int bookId) {
    //I am calling getDBWrapper.executeQuery() to execute query on my database
}
//在ChildDAO子类中,我有一个方法:

public DBWrapper getDBWrapper() {
    //Obtains the DBwrapper with the data source details
}
public int getBookRefCode(int bookId) {
    //I am calling getDBWrapper.executeQuery() to execute query on my database
}
在JUnit测试类中: 我已经创建了子类和基类的实例

BaseDAO dao = new BaseDAO();
ChildDAO cdao = new ChildDAO;

dao = createMock(BaseDAO.class);
@Test
int res = cdao.getBookRefCode(id);// This does not return any result and says data source is not recognized
但是,当getDBWrapper实现直接在子类中时,我会这样做

cdao = createMock(ChildDAO.class); //it works
有什么建议吗?

在下面的代码中

dao = createMock(BaseDAO.class);
您正在为类/接口
BaseDAO
创建的是
Proxy
,它返回默认值(您可以更改mocking/stubing方法调用)

现在,当你

@Test
int res = cdao.getBookRefCode(id);// This does not return any result and says data source is not recognized
实际上,您正在调用引用上的方法,该方法指向
ChildDAO
类,该类将调用真实的数据源,但当您模拟子类时,它将返回模拟值,这就是为什么这样做的原因

cdao = createMock(ChildDAO.class); //it work
您可以模拟基类或子类,具体取决于您正在尝试的内容。。我的意思是,如果您将这个模拟类传递给其他需要基类或子类的方法/类

更新: 必须模拟
DBWrapper
实例并将其注入父/子类,或者可以模拟返回模拟实例的
getDBWrapper
方法

obj = mock(YourClass.class)
 when(obj).getdbwrapper().return(mockDbWrapper)

对不起,我在打电话,pl execuse syntax

谢谢您的回复!既然我的DB包装器实现在父类中,而子类方法只是访问它来获取查询结果,那么如何进行模拟呢?我的意思是模拟子类也不起作用(它只在包装器实现在子类中时起作用)请看我更新的答案,在这种情况下,您必须模拟db包装器