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

おそらくあなたの質問には遅すぎます。私は今日それに会い、次のURLで解決策を見つけました。基本的には、のように引数の型を指定する必要があります。

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 を受け取る 1 つのコンストラクターと、引数として anString を受け取る別のコンストラクターを 持つ、呼び出されたクラスがあり int、コンストラクターのみを抑制したいとしますStringsuppress(constructor(ClassWithSeveralConstructors.class, String.class)); メソッドを使用してこれを行うことができます 。

http://code.google.com/p/powermock/wiki/SuppressUnwantedBehaviorにあります

それはあなたが欲しかったものではありませんか?

編集:わかりました、あなたはすでに抑制を試みました。しかし、サプレッション コールが正しく行われたと確信していますか? の最初の引数はconstructor()、コンストラクターを抑制したいクラスではありませんか?

于 2011-02-10T21:11:26.290 に答える