【问题标题】:PowerMock multiple matching constructors; (variable length array constructor vs no-param constructor)PowerMock 多个匹配的构造函数; (可变长度数组构造函数与无参数构造函数)
【发布时间】:2017-11-10 11:16:47
【问题描述】:

我正在尝试在 ResourceConfig.class 中模拟没有参数的构造函数。 碰巧 ResourceConfig 有两个构造函数:(除其他外):

public ResourceConfig()
public ResourceConfig(Class... class)

PowerMock (1.7.3) 无法获得正确的构造函数。 我认为这是一个错误;但也许有一个解决方案(?)

代码:

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

}

这会产生:

org.powermock.reflect.exceptions.TooManyConstructorsFoundException: 找到几个匹配的构造函数,请指定参数 参数类型,以便 PowerMock 可以确定您使用的方法 指。匹配类中的构造函数 org.glassfish.jersey.server.ResourceConfig 是:
org.glassfish.jersey.server.ResourceConfig( )
org.glassfish.jersey.server.ResourceConfig( [Ljava.lang.Class;.class )

在 org.powermock.reflect.internal.ConstructorFinder.throwExceptionWhenMultipleConstructorMatchesFound(ConstructorFinder.java:89) ...

有什么想法吗?

【问题讨论】:

    标签: java unit-testing junit powermock


    【解决方案1】:

    你可以抑制多个构造函数,例如:

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

    此测试通过:

    • PowerMock 1.7.3
    • 球衣 2.26

    【讨论】:

      【解决方案2】:

      可以接收StringUriFile 类示例:

      whenNew(File.class).withParameterTypes(String.class).withArguments(any(String.class)).thenReturn(mockFile);
      

      最佳方法(如果您知道这种情况下的 String 值):

      whenNew(File.class).withArguments(eq("SOME STRING")).thenReturn(mockFile);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-05
        • 2016-09-02
        • 2016-01-02
        • 1970-01-01
        • 2012-06-30
        • 2011-03-15
        相关资源
        最近更新 更多