简体   繁体   中英

Data source not recognized while using using Easymock

Inside parent class BaseDAO.java, I have a method:

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

//Inside child class ChildDAO, I have a method:

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

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

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)

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

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

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

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

Sorry I'm on phone, pl execuse syntax

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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