如何在同一个类中使用其他静态方法模拟静态方法调用?

时间:2018-02-15 20:25:20

标签: powermock powermockito

我有一个实用程序类,其中一个静态方法调用另一个。我想模拟被调用的方法而不是目标方法。有人有例子吗?

我有:

@RunWith(PowerMockRunner.class)
@PrepareForTest({SubjectUnderTest.class})
public class SubjectUnderTestTest {
...
    SubjectUnderTest testTarget = PowerMockito.mock(SubjectUnderTest.class, Mockito.CALLS_REAL_METHODS);

1 个答案:

答案 0 :(得分:0)

docs开始,通过一些小的调整,你可以模拟或监视静态方法,具体取决于你需要什么(间谍似乎不那么冗长,但语法不同)。您可以在下面找到两者的样本,基于PowerMockito 1.7.3& Mockito 1.10.19。

给出以下带有所需2个静态方法的简单类:

public class ClassWithStaticMethods {

    public static String doSomething() {
        throw new UnsupportedOperationException("Nope!");
    }

    public static String callDoSomething() {
        return doSomething();
    }

}

您可以执行以下操作:

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

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.powermock.api.mockito.PowerMockito.*;

// prep for the magic show
@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStaticMethods.class)
public class ClassWithStaticMethodsTest {

    @Test
    public void shouldMockStaticMethod() {
        // enable static mocking
        mockStatic(ClassWithStaticMethods.class);

        // mock the desired method
        when(ClassWithStaticMethods.doSomething()).thenReturn("Did something!");

        // can't use Mockito.CALLS_REAL_METHODS, so work around it
        when(ClassWithStaticMethods.callDoSomething()).thenCallRealMethod();

        // validate results
        assertThat(ClassWithStaticMethods.callDoSomething(), is("Did something!"));
    }

    @Test
    public void shouldSpyStaticMethod() throws Exception {
        // enable static spying
        spy(ClassWithStaticMethods.class);

        // mock the desired method - pay attention to the different syntax
        doReturn("Did something!").when(ClassWithStaticMethods.class, "doSomething");

        // validate
        assertThat(ClassWithStaticMethods.callDoSomething(), is("Did something!"));
    }

}