1

以下の例のようなクラスをテストしようとしています。

public class Service : IService
{
    public string A(string input)
    {            
        int attemptCount = 5;
        while (attemptCount > 0)
        {
            try
            {
                return TryA(input);
            }
            catch (ArgumentOutOfRangeException)
            {
                attemptCount--;
                if (attemptCount == 0)
                {
                    throw;
                }
                // Attempt 5 more times
                Thread.Sleep(1000);                        
            }                    
        }
        throw new ArgumentOutOfRangeException();            
    }

    public string TryA(string input)
    {
    // try actions, if fail will throw ArgumentOutOfRangeException
    }
}

[TestMethod]
public void Makes_5_Attempts()
{
    //  Arrange
    var _service = MockRepository.GeneratePartialMock<Service>();
    _service.Expect(x=>x.TryA(Arg<string>.Is.Anything)).IgnoreArguments().Throw(new ArgumentOutOfRangeException());

    //  Act
    Action act = () => _service.A("");

    //  Assert
    //  Assert TryA is attempted to be called 5 times
    _service.AssertWasCalled(x => x.TryA(Arg<string>.Is.Anything), opt => opt.Repeat.Times(5));
    //  Assert the Exception is eventually thrown
    act.ShouldThrow<ArgumentOutOfRangeException>();
}

部分的なあざけりは私の期待を受け入れていないようです。テストを実行すると、入力に関するエラーが表示されます。デバッグすると、メソッドの実際の実装が期待どおりに実行されていないことがわかります。

私はこのテストを正しく行っていますか?ドキュメント(http://ayende.com/wiki/Rhino%20Mocks%20Partial%20Mocks.ashx)によると:「部分的なモックは、クラスで定義されたメソッドの期待値を定義しない限り、そのメソッドを呼び出します。期待値を定義しました。これには通常のルールが使用されます。」

4

1 に答える 1

2

Rhinomocks、Moq、NSubstituteなどのモックフレームワークは、メモリ内にモックの派生クラスを動的に生成するDynamicProxyと呼ばれる.NETの機能を使用することに注意することが重要です。クラスは次のことを行う必要があります。

  • インターフェイスになります。また
  • パラメーターなしのコンストラクターを持つ非シールクラス。また
  • MarshalByRefObjectから派生します(moqはこの機能から離れました)

メソッドは、実行時に代替動作を置き換えることができるように、インターフェースの一部であるか、仮想化されている必要があります。

于 2012-06-03T23:22:25.840 に答える