为什么RhinoMocks有义务明确重新定义ToString()以便能够设置它的期望?

sll*_*sll 3 c# rhino-mocks mocking

我正在尝试模拟ToString()我的自定义对象的调用.我已经为界面创建了一个模拟,并在ToString()通话时设置了期望值

interface ICustomObject
{
}

var customObjectMock = MockRepository.GenerateMock<ICustomObject>();
var fakeDump = Guid.NewGuid().ToString();
customObjectMock.Expect(c => c.ToString()).Return(fakeDump).Repeat.Any();
Run Code Online (Sandbox Code Playgroud)

在测试运行时,我得到了运行时异常说:

System.InvalidOperationException:无效的呼叫,已使用的最后一个呼叫或未进行任何呼叫(确保您正在呼叫虚拟(C#).

众所周知的错误,但为什么我认为它ToString()是虚拟的呢?

而且更有趣 - 我只是通过ToString()在界面中明确定义来解决它:

interface ICustomObject
{
  // Weird! I believe such method definition in interface would be confusing
  // without a special remark comment saying that this method is redefined 
  // to satisfy RhinoMocks (perhaps Reflection?)
  string ToString();
}
Run Code Online (Sandbox Code Playgroud)

在此之后,RM允许设定期望值ToString().

只是想知道为什么RinoMocks要求我重新定义标准虚拟化Object.ToString()?也许RM不考虑可用于每个框架对象的这种标准方法,并且有义务重新定义所有方法/属性;为了能够设定期望,我们必须这样做?

Rob*_*vey 6

接口不是对象.

尽管可以ToString()隐式调用接口,但假设存在一些object实现接口的接口,因此提供了ToString()隐式实现.

由于你没有提供你的接口的实现,没有什么可以"挂钩"该ToString()方法,显然RhinoMocks认为测试一个实际上不存在的方法没有多大意义.