PowerMockito模拟一个通用的构造函数

时间:2014-08-11 19:29:10

标签: java generics junit mockito powermock

我有一个声明如下的类:

public class GenericFoo<T>
{
    private final Class<T> _c;
    public GenericFoo(Class<T> c)
    {
        this._c = c; 
    }
    /*
    ...
    rest is unimportant
    */
}

我正在为一个类编写一个单元测试,称之为SomeBar,它创建并使用GenericFoo的实例。对于此测试,我需要构造函数始终返回GenericFoo的特定间谍。

    MyWebServiceResponse webServiceResponseObject = setUpTestResponseObject(1,2,3);

    GenericFoo<MyWebServiceResponse> testFoo = PowerMockito.spy(new GenericFoo<MyWebServiceResponse>(MyWebServiceResponse.class));

    PowerMockito.when(testFoo.processResponseObject(webServiceResponseObject))
            .thenAnswer(new Answer<String>()
            {
                @Override
                public String answer(InvocationOnMock invocation) throws Throwable
                {
                    /* details unimportant */
                }
            });

为了确保在testFoo创建SomeBar的实例时返回GenericFoo<MyWebServiceResponse>,我尝试过这样做:

PowerMockito.whenNew(com.myCompany.GenericFoo.class)
                .withParameterTypes(MyWebServiceResponse.class)
                .withArguments(MyWebServiceResponse.class)
                .thenReturn(testFoo);

这会导致PowerMock产生错误:

org.powermock.reflect.exceptions.ConstructorNotFoundException: Failed to lookup constructor with parameter types [ com.myCompany.MyWebServiceResponse ] in class com.myCompany.GenericFoo.
...[stack trace snipped]
Caused by: java.lang.NoSuchMethodException: com.myCompany.GenericFoo.(com.myCompany.MyWebServiceResponse)

有没有办法让泛型构造函数在这种情况下返回特定对象?

1 个答案:

答案 0 :(得分:1)

错误的根本原因是构造函数的参数类型在运行时只是Class(在编译时为Class<T>,从不MyWebServiceResponse)。

所以使用

.withParameterTypes(Class.class)

应该有用。