Rahul Sharma
Rahul Sharma

Reputation: 5995

Mock Multiple Static Methods

I have a class like which makes two different static function calls one of which is some Util function while the other is local to the class, like this:

public class A {
    .
    .
    public static myfunc1() {
        obj1 = myfunc(param);
        .
        .
        Obj obj = Util.getObj(param);
        .
        .
    }

    static obj1 myfunc(param) {
        ..
    }
}

I want to write unit test for this class which looks something like this:

public class Atest {
    .
    .
    public void testMyfunc1() {
        .
        .
        A a = new A();
        A spyA = spy(a);
        PowerMockito.doReturn(mockObj).when(spyA).myfunc(mockParam);
        .
        .
    }
    .
    .
}

But it is giving me UnfinishedStubbingException.

I also tried doing like this:

PowerMockito.when(spyA.myfunc(mockParam)).thenReturn(mockObj);

But it does not override the function.

And secondly, I need to know that how can I override the Util.getObj() function.

Upvotes: 0

Views: 3744

Answers (2)

Rahul Sharma
Rahul Sharma

Reputation: 5995

After some research, I came to know that PowerMock provides a module called easymock wherein there is method called mockStaticPartial which mocks specific static functions in a class. As for Utils.getObj() method, similar thing can be done. So, my test class now looks like something like this:

@RunWith(PowerMockRunner.class)
@PrepareForTest({A.class, Utils.class})
public class Atest {
    .
    .
    @Before
    public void setup() {
        .
        .
        mockStaticPartial(A.class, "myfunc");
        mockStatic(Utils.class);
        .
        .
    }

    public void testMyfunc1() {
        .
        .
        PowerMockito.when(A.mufync()).thenReturn(mockObj1);
        PowerMockito.when(Utils.getObj(mockParam)).thenReturn(mockObj);
        .
        .
        //More testing logic goes here
    }
    .
    .
}

Upvotes: 1

kan
kan

Reputation: 28951

Spies are for mocking class instances, but static methods are class level. You should use PowerMockito.mockStatic or PowerMockito.spy.

However, the best approach - refactor the code and get rid of statics.

Upvotes: 0

Related Questions