2.11 Delegateを使用してExpectationでresultをカスタマイズする

767 ワード

使用シーン:Expectationではreplay時のパラメータ値に基づいて戻り値を決定する必要があります.原理:JMockitは呼び出しをブロックし、Delegate処理に渡す.
@Test
public void delegatingInvocationsToACustomDelegate(@Mocked final DependencyAbc anyAbc){
   new Expectations() {{
      anyAbc.intReturningMethod(anyInt, null);
      result = new Delegate() {
         int aDelegateMethod(int i, String s)
         {
            return i == 1 ? i : s.length();
         }
      };
   }};

   // Calls to "intReturningMethod(int, String)" will execute the delegate method above.
   new UnitUnderTest().doSomething();
}
  • delegateメソッドのパラメータは、元のメソッドと一致する必要があります.戻り値は互換性が必要か、または異常です.
  • delegateコンストラクタは、戻り値が空に設定されている場合に使用できます.
  • delegateパラメータには、Invocationオブジェクトがあり、呼び出し元の参照
  • を得ることができる.