0

PowerMock でテストしているクラスでは、クラスの次のインスタンス化があります

EmailMessage msg = new EmailMessage(getExchangeSession());

EmailMessagegetExchangeSession()継承された保護されたメソッドである間、私が嘲笑しているサードパーティのツールです。をモックする必要がありますEmailMessageが、への呼び出しは本当に気にしませんgetExchangeSession()

現時点では次のものがありますが、getExchangeSession()メソッドはまだ呼び出されています:

@RunWith(PowerMockRunner.class)
@PrepareForTest({EmailProvider.class, ExchangeService.class})
public class MyTest {

    @Test
    public void test() {
        EmailMessage emailMessage = createMock(EmailMessage.class);
        ExchangeService exchangeService = createMock(ExchangeService.class);
        expectNew(EmailMessage.class, exchangeService).andReturn(emailMessage);

        // test setup and call to the class under test
        Email email = new Email();
        new EmailProvider().send(email);
    }
}

public class EmailProvider() extends ClassWithProtectedAccess {
    public void send(Email email) {
        EmailMessage msg = new EmailMessage(getExchangeSession());

        // and here follows the code that I am actually testing
        // and which works on the msg (EmailMessage)
        // ...
    }
}

EmailProvider.send() の最初の行は、実行getExchangeSession()され、その後失敗することです。

どうやら への呼び出しをスキップできないようgetExchangeSession()で、おそらくこのメソッドもモックする必要があります。これは正しいです?もしそうなら、EasyMock で PowerMock を使用すると、この保護されたメソッドをどのようにモックできますか?

4

2 に答える 2

1

テストしているクラスに次の行がある場合:

EmailMessage msg = new EmailMessage(getExchangeSession());

getExchangeSession()次に、コンストラクターをパワーモックして呼び出しをスキップすることはできませんEmailMessage-コンストラクターが呼び出される前に呼び出され、戻り値が渡されますEmailMessage(それが本物かモックかに関係なく)。

したがって、 への呼び出しが機能するようにクラスを設定できない場合はgetExchangeSession、この質問の説明に従ってその呼び出しをモックする必要があります:プロテクト メソッドのモック。

于 2013-06-14T11:31:22.283 に答える
0

あなたの質問を正しく理解したので、あなたは EmailMessage クラスをモックすることを期待していますが、インスタンスを作成するときにコンストラクター呼び出しをスキップする必要があります。

    ... test setup and call to the class under test ...
    Email email = new Email();
    new EmailProvider().send(email);

問題は、テストの方法です。あなたの意図は、send メソッドでコードをテストすることです。その send() メソッドを呼び出してテストすることはできません。依存関係クラスをモックして send() メソッドのステートメントをテストするコードを記述し、クラス内の他のステートメントをテストする必要があります

public void testSend() throws Exception 
{
  // you need to suppress the constructor before you mock the class.
   PowerMockito.suppress(PowerMockito.constructor(EmailMessage.class));
   EmailMessage emailMessage = PowerMockito.mock(EmailMessage.class);
   Email email = new Email();
   emailMessage.setSubject(email.getSubject());
  // ...your other code here ...

}
于 2013-06-13T13:28:32.350 に答える