Avinash Jethy
Avinash Jethy

Reputation: 843

How to mock static method chain call using easymock-powermock?

I want to mock below method chain using easymock-powermock,

OtherClass oc = SampleClass.getInstance().getSampleMethod(new StringReader("ABC");

getInstance () is a singleton method. getSampleMethod() is a public method.

When I try to use expect/andReturn getting null.

Upvotes: 0

Views: 1447

Answers (1)

Sravya
Sravya

Reputation: 159

I am not sure if you are setting the expectations at once to the whole method chain but that is not how it works. You have to set the expectation for each and every method call separately.

In your case, as first method call is a static call you should use powermock and set the expectation and return the mocked instance for it. Then you should add the expectation for second method call. I have given the sample code below Please check if it works in your case.

@RunWith(PowerMockRunner.class)
@PrepareForTest({SampleClass.class})
public class SimpleClassTest{
    @Test
    public void test(){
        PowerMock.mockStatic(SampleClass.class);
        SampleClass sampleClassInstance = EasyMock.createMock(SampleClass);
        EasyMock.expect(SampleClass.getInstance).andReturn(sampleClassInstance);
        EasyMock.expect(sampleClassInstance.getSampleMethod(/*required parameter goes here*/).andReturn(/*Otherclass instance goes here*/);
        PowerMock.replayAll();
        EasyMock.replay(sampleClassInstance);
    }

}

Upvotes: 1

Related Questions