11

这是测试:

import static junit.framework.Assert.assertTrue;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.whenNew;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest( {ClassUnderTesting.class} )
public class ClassUnderTestingTest {

    @Test
    public void shouldInitializeMocks() throws Exception {
        CollaboratorToBeMocked mockedCollaborator = mock(CollaboratorToBeMocked.class);

            suppress(constructor(CollaboratorToBeMocked.class, InjectedIntoCollaborator.class));

        whenNew(CollaboratorToBeMocked.class)
            .withArguments(InjectedAsTypeIntoCollaborator.class)
            .thenReturn(mockedCollaborator);

        new ClassUnderTesting().methodUnderTesting();

        assertTrue(true);
    }
}

这些是类:

public class ClassUnderTesting {

    public void methodUnderTesting() {
        new CollaboratorToBeMocked(InjectedAsTypeIntoCollaborator.class);
    }

}

public class CollaboratorToBeMocked {

    public CollaboratorToBeMocked(Class<InjectedAsTypeIntoCollaborator> clazz) {
    }

    public CollaboratorToBeMocked(InjectedIntoCollaborator someCollaborator) {
    }

    public CollaboratorToBeMocked() {
    }

}

public class InjectedAsTypeIntoCollaborator {

}

public class InjectedIntoCollaborator {

}

这是错误:

org.powermock.reflect.exceptions.TooManyConstructorsFoundException: Several matching constructors found, please specify the argument parameter types so that PowerMock can determine which method you're refering to.
Matching constructors in class CollaboratorToBeMocked were:
CollaboratorToBeMocked( InjectedIntoCollaborator.class )
CollaboratorToBeMocked( java.lang.Class.class )

问题来了:我怎样才能让 PowerMock 找出要寻找的构造函数?

有问题的行suppress. 这就是错误的来源。

4

2 回答 2

17

也许你的问题为时已晚。我今天遇到了它,并在以下网址找到了解决方案。基本上,您需要指定您的参数类型,例如。

whenNew(MimeMessage.class).**withParameterTypes(MyParameterType.class)**.withArguments(isA(MyParameter.class)).thenReturn(mimeMessageMock); 

http://groups.google.com/group/powermock/msg/347f6ef1fb34d946?pli=1

希望它可以帮助你。:)

于 2011-11-07T06:13:32.930 回答
2

在您写下您的问题之前,我不知道 PowerMock,但做了一些阅读并在他们的文档中找到了这一点。我仍然不确定这是否对您有帮助:

如果超类有多个构造函数,则可以告诉 PowerMock 只抑制特定的构造函数。假设您有一个名为的类 ,该类ClassWithSeveralConstructors具有一个构造函数,该构造函数采用 a作为参数String ,另一个构造函数采用 a int作为参数,并且您只想抑制String构造函数。您可以使用该 suppress(constructor(ClassWithSeveralConstructors.class, String.class)); 方法执行此操作。

http://code.google.com/p/powermock/wiki/SuppressUnwantedBehavior找到

这不是你想要的吗?

编辑:现在我明白了,你已经尝试过压制。但是你确定你的压制电话是对的吗?第一个参数不是constructor()应该是你想压制构造函数的类吗?

于 2011-02-10T21:11:26.290 回答