views:

118

answers:

3

I've the following class. It has the code to connect to SAP in its constructor. There is an abstract method(the subclasses define the implementation) which I want to mock.

public abstract class BapiExecutor {
        ...
        public BapiExecutor(final SapConnectionInfo connectionInfo)
      throws java.lang.Exception {
     if (!validConnectorData()) {
      throw new IllegalArgumentException(
        "Does not have valid data to connect to SAP");
     }
     initializeState(connectionInfo);
    }

    public abstract Object execute() throws Exception ;
        ....

}

The unit I want to test is : I want to mock the call to execute() method.

private String invokeBapiToAddAssociation(Map associationMap,
      SapConnectionInfo connectionInfo) {
     EidCcBapiExecutor executor = null;
     String bapiExecutionResult = null;
     try {
      executor = new EidCcBapiExecutor(connectionInfo, associationMap);
      bapiExecutionResult = (String) executor.execute();
     } catch (Exception e) {
      e.printStackTrace();
      throw new CcGenericException(
        "Exception occurred while invoking the EID-CC Association BAPI executor!",
        e);
     }
     return bapiExecutionResult;
    }

Any frameworks in Java that supports the mocking of parametrized constructors?

i just want to avoid connecting to SAP in the constructor.

+3  A: 

JMock with the ClassImposteriser can do that, as can most good mocking frameworks.

The ClassImposteriser creates mock instances without calling the constructor of the mocked class. So classes with constructors that have arguments or call overideable methods of the object can be safely mocked.

skaffman
Looked into the code. Sounds cool. Never used JMock before. +1
Adeel Ansari
It takes a bit of getting used to (the generics can get a bit hairy), but it's very useful.
skaffman
A: 

You can simply create the mock class, subclassing the abstract BapiExecutor class, and implementing the behavior you want in execute() (or any other method). You don't need to revert to a framework here.

Could you please elaborate about what the blocking point is ?

philippe
A: 

I expect that the EidCcBapiExecutor extends from BapiExecutor.

public class EidCcBapiExecutor extends BapiExecutor {
...
}

Than you could create the Mockup class for testing a specific method like:

public class EidCcBapiExecutorMockup extends EidCcBapiExecutor{

   public EidCcBapiExecutorMockup (final SapConnectionInfo connectionInfo){
     super(connectionInfo);
   }

   public Object execute() throws Exception {
      // You mockup code
   }
}

If you want to test the constructor you can create the class like:

public class EidCcBapiExecutorMockup extends EidCcBapiExecutor{

       public EidCcBapiExecutorMockup (){
         super(new SapConnectionInfo());
       }

    }

The object you place in the Constructor could be created in the setUp method of you JUnit test!

Markus Lausberg