我知道我可以这样做:
IDateTimeFactory dtf = MockRepository.GenerateStub<IDateTimeFactory>();
dtf.Now = new DateTime();
DoStuff(dtf); // dtf.Now can be called arbitrary number of times, will always return the same value
dtf.Now = new DateTime()+new TimeSpan(0,1,0); // 1 minute later
DoStuff(dtf); //ditto from above
Run Code Online (Sandbox Code Playgroud)
如果不是IDateTimeFactory.Now是一个属性它是一个方法IDateTimeFactory.GetNow(),我怎么做同样的事情呢?
根据Judah的建议,我已经重写了我的SetDateTime辅助方法,如下所示:
private void SetDateTime(DateTime dt) {
Expect.Call(_now_factory.GetNow()).Repeat.Any();
LastCall.Do((Func<DateTime>)delegate() { return dt; });
}
Run Code Online (Sandbox Code Playgroud)
但它仍然会抛出"ICurrentDateTimeFactory.GetNow();的结果已经设置好了." 错误.
加上它仍然无法使用存根....
我知道这是一个老问题,但我想我会发布更新的Rhino Mocks版本的更新.
基于之前使用Do()的答案,如果您在Rhino Mocks中使用AAA(可从3.5+版本获得),则可以使用稍微清洁(IMO)的方式.
[Test]
public void TestDoStuff()
{
var now = DateTime.Now;
var dtf = MockRepository.GenerateStub<IDateTimeFactory>();
dtf
.Stub(x => x.GetNow())
.Return(default(DateTime)) //need to set a dummy return value
.WhenCalled(x => x.ReturnValue = now); //close over the now variable
DoStuff(dtf); // dtf.Now can be called arbitrary number of times, will always return the same value
now = now + new TimeSpan(0, 1, 0); // 1 minute later
DoStuff(dtf); //ditto from above
}
private void DoStuff(IDateTimeFactory dtf)
{
Console.WriteLine(dtf.GetNow());
}
Run Code Online (Sandbox Code Playgroud)