How can I make fun of a static method using PowerMockito?

I use:

<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> 

I am trying to check a piece of code with the following call:

 final KeyPairGenerator kpg = KeyPairGenerator.getInstance(KEY_PAIR_ALGORITHM, DEFAULT_PROVIDER); 

Two constants are of type String, so I call:

 java.security.KeyPairGenerator.getInstance(String algorithm, String provider) 

I tried:

 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); } } 

I tried replacing when(KeyPairGenerator.getInstance(KEY_PAIR_ALGORITHM, DEFAULT_PROVIDER)).thenReturn(kpg); at PowerMockito.doReturn(kpg).when(KeyPairGenerator.class); but it doesn't seem to me what I want, as I am still getting a NoSuchProviderException. Any insight would be appreciated.

+4
source share
1 answer

You might want to try changing your @PrepareForTest statement.

From:

 @PrepareForTest(KeyPairGenerator.class) 

in

 @PrepareForTest(ClassThatCallsTheStaticMethod.class) 
+6
source

All Articles