I am trying to Mock constructor with no args in ResourceConfig.class. It happens that ResourceConfig has two constructors: (among other ones):
public ResourceConfig()
public ResourceConfig(Class... class)
PowerMock (1.7.3) fails to get the right constructor. I would consider this as a bug; but perhaps there is a solutoin to it(?)
Code:
import org.glassfish.jersey.server.ResourceConfig;
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.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.whenNew;
@RunWith(PowerMockRunner.class)
@PrepareForTest( ResourceConfig.class )
public class StackOverflowTest {
@Test
public void toStackOvflow2() throws Exception {
ResourceConfig resConf = mock(ResourceConfig.class);
whenNew(ResourceConfig.class).withNoArguments().thenReturn(resConf);
//WHATEVER...
}
}
This produces:
org.powermock.reflect.exceptions.TooManyConstructorsFoundException: Several matching constructors found, please specify the argument parameter types so that PowerMock can determine which method you're referring to. Matching constructors in class org.glassfish.jersey.server.ResourceConfig were:
org.glassfish.jersey.server.ResourceConfig( )
org.glassfish.jersey.server.ResourceConfig( [Ljava.lang.Class;.class )at org.powermock.reflect.internal.ConstructorFinder.throwExceptionWhenMultipleConstructorMatchesFound(ConstructorFinder.java:89) ...
Any ideas?
You can suppress the multiple constructors, for example:
@Test
public void toStackOvflow2() throws Exception {
ResourceConfig resConf = mock(ResourceConfig.class);
// suppress TooManyConstructorsFoundException
MemberModifier.suppress(MemberMatcher.constructorsDeclaredIn(ResourceConfig.class));
whenNew(ResourceConfig.class).withNoArguments().thenReturn(resConf);
// verifying that the expected ResourceConfig instance is returned when using the default ctor ...
assertSame(resConf, new ResourceConfig());
}
This test passes with:
Example for File
class that can receive a String
or an Uri
:
whenNew(File.class).withParameterTypes(String.class).withArguments(any(String.class)).thenReturn(mockFile);
Best approach(if you know the String value in this case):
whenNew(File.class).withArguments(eq("SOME STRING")).thenReturn(mockFile);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.