如何从同一个类中的另一个静态方法模拟静态方法调用?

问题描述 投票:0回答:1

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

我有:

@RunWith(PowerMockRunner.class)
@PrepareForTest({SubjectUnderTest.class})
public class SubjectUnderTestTest {
...
    SubjectUnderTest testTarget = PowerMockito.mock(SubjectUnderTest.class, Mockito.CALLS_REAL_METHODS);
powermock powermockito
1个回答
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!"));
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.