Java 使用Easymock时无法识别数据源
在父类BaseDAO.java中,我有一个方法: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
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包装器