Qiang Yao
Qiang Yao

Reputation: 185

How to skip invoking another method to create a mock object?

I have a class of methods, if I want to test one method, but the objects created in this method depend on other methods in the class. I don't want to actually call the other methods, I just want to create mock objects to test. How should I do it?

@Test
public void testLoadException(String id) {

    WorkflowExecution mockWorkflowExection = getWorkflowExecution(id);

}

I tried to just do so

WorkflowExecution mockExecution = EasyMock.create(WorkflowExecution.class);
Easy.expect(this.test.getWorkflowExecution(EasyMock.anyString())).andReturn(mockExecution);

But this does not work, the test gives me Nullpointer exception. So can I skip the calling of getWorkflowExecution(id), Thanks!

Upvotes: 0

Views: 124

Answers (1)

Henri
Henri

Reputation: 5711

You need a partial mock. Your example doesn't make much sense. So here is what you seem to want.

public class WorkflowExecution {
    public void theRealMethodIWantToCall() {
        theMethodIWantToMock();
    }

    void theMethodIWantToMock() {

    }
}

@Test
public void testLoadException() {
    WorkflowExecution execution = partialMockBuilder(WorkflowExecution.class)
            .addMockedMethod("theMethodIWantToMock")
            .mock();
    execution.theMethodIWantToMock();
    replay(execution);

    execution.theRealMethodIWantToCall();

    verify(execution);
}

Upvotes: 1

Related Questions