2012-06-02 37 views
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):「部分模擬會調用在類上定義的方法,除非您定義了該方法的期望值。如果您已經定義了期望值,它將使用此常規規則。」

+0

我認爲'TryA'應該是虛擬的 – Steve

+0

@Steve,這似乎解決了這個問題。我寧願不必爲該功能添加虛擬功能,但我認爲它很少會發生。謝謝! –

回答

2

重要的是要注意像Rhinomocks,Moq和NSubstitute這樣的模擬框架在.NET中使用了一個名爲DynamicProxy的功能,它動態地在內存中生成模擬的派生類。類必須:

  • 是一個接口;或
  • 帶無參數構造函數的非密封類;或
  • 自MarshalByRefObject派生(MOQ已經從該特徵移開)

方法必須是在接口的一部分,或由虛擬的,這樣交替的行爲可以在運行時被取代。