如何使用PowerMockito模拟静态方法?

les*_*onz 4 junit mockito powermock

我在用:

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.10</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-api-mockito</artifactId>
        <version>${powermock.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-module-junit4</artifactId>
        <version>${powermock.version}</version>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
Run Code Online (Sandbox Code Playgroud)

我试图通过以下调用来测试一段代码:

final KeyPairGenerator kpg = KeyPairGenerator.getInstance(KEY_PAIR_ALGORITHM, DEFAULT_PROVIDER);
Run Code Online (Sandbox Code Playgroud)

这两个常量是String类型,所以我调用:

java.security.KeyPairGenerator.getInstance(String algorithm, String provider)
Run Code Online (Sandbox Code Playgroud)

我试过了:

import static org.mockito.Mockito.when;

import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

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

@RunWith(PowerMockRunner.class)
@PrepareForTest(KeyPairGenerator.class)
public class TestClass {

    private static final String DEFAULT_PROVIDER = "BC";
    private static final String KEY_PAIR_ALGORITHM = "RSA";

    @Test
    public void test() throws NoSuchAlgorithmException, NoSuchProviderException {
        final KeyPairGenerator kpg = Mockito.mock(KeyPairGenerator.class);
        PowerMockito.mockStatic(KeyPairGenerator.class);
        when(KeyPairGenerator.getInstance(KEY_PAIR_ALGORITHM, DEFAULT_PROVIDER)).thenReturn(kpg);
    }
}
Run Code Online (Sandbox Code Playgroud)

我试着更换when(KeyPairGenerator.getInstance(KEY_PAIR_ALGORITHM, DEFAULT_PROVIDER)).thenReturn(kpg);用PowerMockito.doReturn(kpg).when(KeyPairGenerator.class);但也似乎让我在哪里,我想,因为我仍然得到NoSuchProviderException.任何见解将不胜感激.

cbe*_*din 6

您可能需要尝试更改行@PrepareForTest语句.

从:

@PrepareForTest(KeyPairGenerator.class)
Run Code Online (Sandbox Code Playgroud)

至:

@PrepareForTest(ClassThatCallsTheStaticMethod.class)
Run Code Online (Sandbox Code Playgroud)