2012-06-02 40 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已经从该特征移开)

方法必须是在接口的一部分,或由虚拟的,这样交替的行为可以在运行时被取代。