serverfaces
serverfaces

Reputation: 1175

Mocking static class in Mockito

I have something like the following:

    public class Foo {

    public static String getValue(String key) {
        return key + "_" + System.currentTimeMillis();
    }
}

Now I need to have a test case for it and here is how I attempted:

@Test
public void testFoo() {
   PowerMockito.mockStatic(Foo.class);
    PowerMockito.when(Foo.getValue("123")).thenReturn("abcd");
    PowerMockito.verifyStatic();

}

When I run the test case, I get this:

org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
   Those methods *cannot* be stubbed/verified.
   Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.

    at org.powermock.api.mockito.PowerMockito.when(PowerMockito.java:495)

Am I doing anything wrong?

Please advise.

Upvotes: 1

Views: 5281

Answers (1)

Jeff Bowman
Jeff Bowman

Reputation: 95704

Can you confirm that you've added a @PrepareForTest(Foo.class) annotation onto your test class as listed on the PowerMock site, and that you're using the PowerMockRunner JUnit4 runner?

Static methods are invoked with static dispatch, not dynamic dispatch using Java's normal polymorphism and method overrides. To replace the implementation, PowerMock needs to load a replacement class before the test starts running, and the runner and annotation make that happen.

Upvotes: 3

Related Questions