4

I am using EasyMock and EasyMock CE 3.0 to mock dependent layers and test my classes. Below is the scenario for which I am not able to find any solution

I have class to be tested, which calls a dependent class void method that takes an input param, and alters the same param. The method that I am testing is doing some operations based on the altered param, which I have to test now for various scenarios

Consider the below sample, where I have tried to put the same scenario

public boolean voidCalling(){
    boolean status = false;
    SampleMainBean mainBean = new SampleMainBean();
    dependentMain.voidCalled(mainBean);
    if(mainBean.getName() != null){
        status = true; 
    }else{
        status = false;
    }
    return status;
}

And the dependentMain class the below method

public void voidCalled(SampleMainBean mainBean){
    mainBean.setName("Sathiesh");
}

To have full coverage, I need to have 2 test cases to test both the scenarios where true and false are returned, but I always get false as I am not able to set the behaviour of the void method to alter this input bean. How can I get a true as result in this scenario using EasyMock

Thanks in advance for any help.

Sathiesh
  • 418
  • 4
  • 11

2 Answers2

7

Starting from the answer in this answer: EasyMock: Void Methods, you can use IAnswer.

// create the mock object
DependentMain dependentMain = EasyMock.createMock(DependentMain.class);

// register the expected method
dependentMain.voidCalled(mainBean);

// register the expectation settings: this will set the name 
// on the SampleMainBean instance passed to voidCalled
EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
    @Override
    public Object answer() throws Throwable {
        ((SampleMainBean) EasyMock.getCurrentArguments()[0])
                .setName("Sathiesh");
        return null; // required to be null for a void method
    }
});

// rest of test here
Community
  • 1
  • 1
DoctorRuss
  • 1,429
  • 10
  • 9
2

Thanks for your reply.. I got the problem resolved... :) Thanks for the sample code too.

Using the above code snippet, One change that I had to do is,

// register the expected method
dependentMain.voidCalled((SampleMainBean) EasyMock.anyObject());

With this am able to get the updated bean in the method to be tested.

Thanks again for your help.

Sathiesh
  • 418
  • 4
  • 11