override a void-method's content

114 views Asked by At

I'm using EasyMock 3+.

I'm testing a method e.g. processMessage(), which (would) meet my tests, but at the very end of the method this method also calls another method dispatchMessage(String msg) of the same class. That latter method takes on a @EJB injected object, which I really don't care about in this test. Of course - this object result in a NullPointerException.

How can I mock with Easymock this method to simply ignore it's code and return void. i.e.

void dispatchMessage(String msg){
     return;
}

thanks

4

There are 4 answers

1
feder On BEST ANSWER

There is no need to invoke replay or verify. I did it like this. Added the @BeforeClass annotation.

InboundMDB inboundMock;

@BeforeClass
public void beforeClass() {
    inboundMock = new InboundMDB();
}

Then created an EasyMock builder instance and added the method I'm NOT interested in. Now, thi

IMockBuilder<InboundMDB> iMockBuilder = EasyMock
                .createMockBuilder(InboundMDB.class);
        inboundMock = iMockBuilder.addMockedMethod("dispatch")
                .createMock();

Following by this code, which invokes the method under test (original objective)...

try {
        inboundMock.processMessage(aMessage);
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    }

Of course, if I omit the partial mock, it throws a null pointer exception as initially described. Now, it doesn't do so anymore. All good.

2
eee On

You can use the partial mock feature of EasyMock.

Let's assume the following class:

public class ClassUnderTest {

    @EJB
    private SomeEJB someEJB;

    public void processMessage() {
        dispatchMessage("some message");
    }

    public void dispatchMessage(String msg) {
        someEJB.dispatch(msg);        
    }
}

In order to test only the method processMessage you can mock dispatchMessage:

import org.easymock.EasyMockSupport;
import org.junit.Test;

public class ProcessMessageTest extends EasyMockSupport {

    @Test
    public void processMessage() throws Exception {
        ClassUnderTest classUnderTest = createMockBuilder(ClassUnderTest.class)
            .addMockedMethod("dispatchMessage")
            .createMock();  
        classUnderTest.dispatchMessage("some message");
        replayAll();

        classUnderTest.processMessage();

        verifyAll();
    }

}
0
Vihar On

for a mocking a void method, the expectLastCall() method is useful, and you do not need to return anything in this case as return type is void

essentially you need to do

mockObject.dispatchMessage(Easymock.anyObject(String.class));
Easymock.expectLastcall();

hope it helps!

good luck!

0
nutfox On

Another alternative is to use the PowerMock framework which works very nicely with EasyMock and has some additional features you might find interesting (like mocking new object creations or static method calls): https://code.google.com/p/powermock/wiki/MockPrivate