How to mock only one static method and test the other

I used a very simple method of writing a conditional answer like this:

    PowerMockito.mockStatic(<MyMockedClass>.class, invocation -> {
        if (invocation.getMethod().getName().equals("<methodToMockName>")) {
            return <mockedValue>;
        }
        return invocation.callRealMethod();
    });

You can use partial mocking:

@Test
public void testStatic() {
    new Expectations(Provider.class) {{ Provider.getStaticList(); result = 1; }};

    List<Integer> test = Provider.test();

    assertTrue(test.contains(1));
}

(With no "@Mocked Provider" field for the test above.)


The code below changes the behaviour of doSomething static method only, without affecting other static methods.

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;

import java.util.HashMap;
import java.util.Map;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({Foo.class})
public class Snipets {

    @Test
    public void hoge() throws Exception {
        PowerMockito.spy(Foo.class);
        PowerMockito.when(Foo.class, "doSomething").thenReturn("dummy");

        String actual = Foo.doSomething();
        assertEquals("dummy", actual);
    }

}

Foo.java

public class Foo {
    public static String doSomething() {
        return "foo";
    }
}

Source: https://gist.github.com/mid0111/8859159

Tags:

Java

Jmockit