简体   繁体   English

PowerMockito模拟通用构造函数

[英]PowerMockito mock a generic constructor

I have a class that is declared like this: 我有一个这样声明的类:

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

I am writing a unit test for a class, call it SomeBar which creates and makes use of instances of GenericFoo . 我写一个单元测试的一类,称之为SomeBar创建并利用的实例GenericFoo For this test I need the constructor to always return a specific spy of 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 */
                }
            });

To ensure that testFoo is returned when SomeBar creates an instance of GenericFoo<MyWebServiceResponse> , I've tried this: 为了确保在SomeBar创建SomeBar GenericFoo<MyWebServiceResponse>的实例时返回testFoo ,我尝试了以下操作:

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

This causes PowerMock to produce the error: 这将导致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)

Is there any way to get a generic constructor to return a specific object in this sort of situation? 在这种情况下,有什么方法可以让泛型构造函数返回特定对象?

The root cause of your error is that the parameter type for the constructor is just Class at runtime (and Class<T> at compile time, never MyWebServiceResponse ). 该错误的根本原因是,构造函数的参数类型在运行时只是Class (在编译时是Class<T> ,而不是MyWebServiceResponse )。

So using 所以用

.withParameterTypes(Class.class)

should work. 应该管用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM