wood burning stoves*
The moose likes Other Application Frameworks and the fly likes easy mock Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Frameworks » Other Application Frameworks
Bookmark "easy mock" Watch "easy mock" New topic
Author

easy mock

sreenivas vemula
Ranch Hand

Joined: Jan 21, 2012
Posts: 44
Hi,
we are using easymock framework for mocking the java objects to reduce dependency. We got stuck at a certain point. Following is the issue we are facing.
we have two classes say classA,classB. classA has a method say methodA(). and classB has a method say methodB(). And now I want to unit test all the methods in the classA(methodA() in our example). For unit testing we are using JUNIT5. To start with the unit testing we have created a test class for the classA named TestClassA and a testmethod named testMethodA() which will return List . And methodA() in the classA will be calling methodB() of classB.

classA{
public List methodA(){
//here there will be a call to methodB of classB
}
}
class {
public List methodB(){
//here there will a code to connect to data base
}
}

As we are doing unit testing and using easy mock to reduce the dependency and hence instead of connecting to the data base (which is done by calling methodB() of classB) we are trying to mock this method call with the statement.

expect(classB.methodB()).andReturn(list);

where is list is some list object.

the code snippet is as follows:
class TestClass{
public final void testMethodA() {
List list= null;

try {
expect(classB.methodB()).andReturn(list)
list= TestClassA .methodA(); //here methodA() will be calling methodB of classB
} catch (ServiceException e) {
e.printStackTrace();
}
assertNotNull(list);

}
}
so with the first statement in try block as and when there is a call for methodB of classB , it will be replaced by some list object and there by no need to data base connectivity. But the problem is that we are mocknig the classB object in the TestClassA and call is happening in the classA. so obviously when we make a call to testmethodA() in the TestClassA , the flow will be as follows:
TestclassA().testmethodA() --> classA.methodA() --> classB.methodB() and final call classB.methodB() is going to data base. The intension is it should not go to the database ,instead it should be behaving as per the mocked object. But problem how to make the mocked object available in classA.

Please help...........

Thanks in Advance
Mohamed Sanaulla
Saloon Keeper

Joined: Sep 08, 2007
Posts: 3056
    
  33

Please CarefullyChooseOneForum and dont post across multiple forum.


Mohamed Sanaulla | My Blog
sreenivas vemula
Ranch Hand

Joined: Jan 21, 2012
Posts: 44
Any solution to the problem described above??
Jayesh A Lalwani
Bartender

Joined: Jan 17, 2008
Posts: 2054
    
  22

How does class A get an object of type B. For mocking to work, you have to make sure A calls the mocked object that is created from your unit test
sreenivas vemula
Ranch Hand

Joined: Jan 21, 2012
Posts: 44
if you see the pseudo code there will be a statment for creating an object of classB in the methodA of classA.
Jayesh A Lalwani
Bartender

Joined: Jan 17, 2008
Posts: 2054
    
  22

Well, that's exactly your problem. AFAIK, EasyMock works on code that uses some sort of Dependency Injection or Factory pattern. If you are using DI, you create the mocks yourself and then inject them into the classes you want to test. If you are using Factory pattern, you create a MockFactory that creates the mock objects. If you are instantiating classes right inside your test class, you wouldn't be able to mock it.
sreenivas vemula
Ranch Hand

Joined: Jan 21, 2012
Posts: 44
Hi I writing test cases for the application and I am using jmock to mock the objects, but I am not able to do so . Please help:

Here is the Restful webservice implementation. Now I would like to write junit test case. In the following class "BusinessClass" I want to mock the part " partnerService.validatePartner(QuoteRQ.partnerid, transactionId)" and for that I have written mock class called " PartnerServiceMock" which will be injected at runtime.
The problem that I am facing is while running the junit test case, instead of mock object, actual code is getting executed, i.e., mock object is not getting injected at runtime. Please help.

Following is the code snippet

public interface BaseMockInjector {

public void injectMock(List<Class> clist);

public void injectMock(Class c);
}




public abstract class BusinessServiceBaseMockInjector implements BaseMockInjector {

AbstractMock abs = null;
PartnerService partnerService = new PartnerService();
try {
abs = (AbstractMock) Class.forName("test.chartis.tguard.stdoff.service." + c.getSimpleName() + "Mock").newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
abs.mock(context, mockSingleton);

public void injectMock(List<Class> clist) {
Mockery context = new JUnit4Mockery() {

{
setImposteriser(ClassImposteriser.INSTANCE);
}
};
try{
Class c = BusinessClass.class;
Field[] fields = c.getFields();
for(Field field : fields){
Class cls = field.getClass();
Object mock = context.mock(cls);
this.mock(context, mock, c);
if(field.getName().equalsIgnoreCase("partnerService"))
System.out.println("partnerService");
else if(field.getName().equalsIgnoreCase("isoCountryService"))
System.out.println("isoCountryService");
else if(field.getName().equalsIgnoreCase("uwCountryService"))
System.out.println("uwCountryService");
else if(field.getName().equalsIgnoreCase("agencyService"))
System.out.println("agencyService");
else if(field.getName().equalsIgnoreCase("productDTOService"))
System.out.println("productDTOService");
}

}catch(Exception e){

}

}


}



Test Class:
===========

public class TestBusinessClass extends BusinessServiceBaseMockInjector {

List<Class> classes = null;

@Before
public void test() throws Exception {
List<Class> classes = new ArrayList<Class>();
classes.add(PartnerService.class);
injectMock(classes);
}


@Test
public final void testExecuteRule() {
BusinessClass business = new BusinessClass();
QuoteRQ quoteRQ = new QuoteRQ();

quoteRQ.setTimestamp(today);
quoteRQ.setTransactionID("Scenario2Cycle206282012");

business .executeRule(quoteRQ);
}

}



Class under Test:
===================

@Path("/rule")
@Singleton
public class BusinessClass{
public PartnerService partnerService = new PartnerService();

@POST
@Path("/executeRule")
@Produces("application/xml")
@Consumes("application/xml")
public Response executeRule(QuoteRQ quoteRQ) {

// some code here
//now the following line will have a call to a web service
if (isPartnerNotNull) {
try {
isPartnerValid = partnerService.validatePartner(QuoteRQ.partnerid, transactionId);
} catch (ServiceException e1) {
logger.info("[" + transactionId + "ServiceException while validating partner Id");
}
}


}

}


Mock class for PartnerService:
==============================

public class PartnerServiceMock extends AbstractMock {

@Override
public void mock(Mockery context, Object obj) {
final PartnerService partnerService = (PartnerService) obj;
try {
final boolean isPartnerValid = true;
context.checking(new Expectations() {

{
atLeast(1).of(partnerService).validatePartner("QABHIAIR", "Scenario2Cycle206282012");
will(returnValue(isPartnerValid));
}
});
} catch (ServiceException serviceException) {
serviceException.printStackTrace();
}
}
}
 
 
subject: easy mock
 
Similar Threads
EASY MOCK
Scope and classes/methods
invoking super constructors.
NullPointer exception
concept of method overriding