3

次のクラスがあるとします。

public class TestBase
{
  public bool runMethod1 { get; set; }

  public void BaseMethod() 
  {
    if (runMethod1)
      ChildMethod1();
    else 
      ChildMethod2();
  }

  protected abstract void ChildMethod1();
  protected abstract void ChildMethod2();
}

クラスもあります

public class ChildTest : TestBase
{
  protected override void ChildMethod1()
  {
    //do something
  } 

  protected override void ChildMethod2()
  {
    //do something completely different
  }

}

私は Moq を使用しており、BaseMethod() を呼び出して runMethod1 が true のときに ChildMethod1() が呼び出されていることを確認するテストを書きたいと思います。Moq を使用して TestBase の実装を作成し、BaseMethod() を呼び出して、Moq 実装で ChildMethod が呼び出されたことを確認することは可能ですか?

[Test]
public BaseMethod_should_call_correct_child_method()
{
  TestBase testBase;

  //todo: get a mock of TestBase into testBase variable

  testBase.runMethod1 = true;

  testBase.BaseMethod();

  //todo: verify that ChildMethod1() was called

}
4

4 に答える 4

5

また、expectation/setup を Verifiable として設定し、厳密なモックなしで実行することもできます。

  //expect that ChildMethod1() will be called once. (it's protected)
  testBaseMock.Protected().Expect("ChildMethod1")
    .AtMostOnce()
    .Verifiable();

  ...

  //make sure the method was called
  testBase.Verify();

編集 この構文は、現在のバージョンの Moq では機能しません。少なくとも4.0.10827の時点でそれを行う方法については、この質問を参照してください

于 2009-02-03T03:52:29.487 に答える
4

これを行う方法を理解しました。保護されたメソッドを Moq でモックでき、厳密なモックを作成することで、それらが呼び出されたことを確認できます。これで、サブクラスを作成しなくても基本クラスをテストできます。

[Test]
public BaseMethod_should_call_correct_child_method()
{
  //strict mocks will make sure all expectations are met
  var testBaseMock = new Mock<TestBase>(MockBehavior.Strict);

  //expect that ChildMethod1() will be called once. (it's protected)
  testBaseMock.Protected().Expect("ChildMethod1")
    .AtMostOnce();

  var testBase = testBaseMock.Object;

  testBase.runMethod1 = true;
  testBase.BaseMethod();

  //make sure the method was called
  testBase.VerifyAll();
}
于 2008-12-24T18:48:00.883 に答える
1

少しハックですが、ChildMethod1 と ChildMethod を public にする TestBase のサブクラスを作成し、それを Moqing するのはどうですか?

于 2008-12-24T03:51:45.997 に答える
0

パブリック インターフェイスではなく動作をテストしているようです。これが意図されている場合は、おそらくプライベート メンバーをテストするためのアドバイスを参照できます。

「Moq を使用して TestBase の実装を作成し、BaseMethod() を呼び出して、Moq 実装で ChildMethod が呼び出されたことを確認することは可能ですか?」

一応可能です。しかし、実際のオブジェクトではなく、モック オブジェクトをテストすることになります。

あなたを正しい方向に導くかもしれない2つの質問:

  1. 子孫クラスは基本クラスとは異なる値を返しますか? もしそうなら、それをテストして、実装の詳細を無視することができます (リファクタリングも簡単になります)。

  2. 子孫クラスは異なるメソッドまたは異なる依存関係を呼び出しますか? その場合は、依存関係を確認できます。

于 2008-12-24T02:47:34.707 に答える