简体   繁体   English

使用Easymock时无法识别数据源

[英]Data source not recognized while using using Easymock

Inside parent class BaseDAO.java, I have a method: 在父类BaseDAO.java中,我有一个方法:

public DBWrapper getDBWrapper() {
    //Obtains the DBwrapper with the data source details
}

//Inside child class ChildDAO, I have a method: //在子类ChildDAO中,我有一个方法:

public int getBookRefCode(int bookId) {
    //I am calling getDBWrapper.executeQuery() to execute query on my database
}

In JUnit test class: I have created instance of both Child and Base class 在JUnit测试类中:我已经创建了Child和Base类的实例

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

But when, the getDBWrapper implementation is directly in child class and I do 但是,当getDBWrapper实现直接在子类中时,我会

cdao = createMock(ChildDAO.class); //it works

Any suggestions? 有什么建议么?

In below code, 在下面的代码中,

dao = createMock(BaseDAO.class);

what you are creating is Proxy for class/interface BaseDAO which returns default value (which you can change mocking/stubbing method call) 您正在创建的是类/接口BaseDAO Proxy ,该Proxy返回默认值(您可以更改BaseDAO /存根方法调用)

now, when you do 现在,当你做

@Test
int res = cdao.getBookRefCode(id);// This does not return any result and says data source is not recognized

you're actually calling method on reference which is pointing to ChildDAO class which will call to real datasource, but when you mock the child class it will return mocked value, thats why this works.. 您实际上是在引用指向ChildDAO类的引用上调用方法,该类将调用真实的数据源,但是当您对子类进行模拟时,它将返回模拟值,这就是工作原理。

cdao = createMock(ChildDAO.class); //it work

You can either mock base class OR child class depending upon what you're trying.. I mean if you are passing this Mock class to some other method/class which expects base class or child class... 您可以根据自己的尝试模拟基类或子类。.我的意思是,如果您将此Mock类传递给其他需要基类或子类的方法/类,则...

Update: You have to mock DBWrapper instance and inject it to your parent/child class OR you can mock getDBWrapper method which return mock instance 更新:您必须模拟DBWrapper实例并将其注入到您的父/子类中,或者您可以模拟getDBWrapper方法,该方法返回模拟实例

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

Sorry I'm on phone, pl execuse syntax 抱歉,我在打电话,请执行语法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM