我知道我可以这样做:
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
如果不是 IDateTimeFactory.Now 是一个属性,而是一个方法 IDateTimeFactory.GetNow() ,我该如何做同样的事情?
根据下面犹大的建议,我将我的 SetDateTime 辅助方法重写如下:
private void SetDateTime(DateTime dt) {
Expect.Call(_now_factory.GetNow()).Repeat.Any();
LastCall.Do((Func<DateTime>)delegate() { return dt; });
}
但它仍然抛出“ICurrentDateTimeFactory.GetNow() 的结果;已经设置。”错误。
此外,它仍然无法与 stub 一起使用....
最佳答案
乔治,
使用您更新的代码,我得到了这个工作:
MockRepository mocks = new MockRepository();
[Test]
public void Test()
{
IDateTimeFactory dtf = mocks.DynamicMock<IDateTimeFactory>();
DateTime desiredNowTime = DateTime.Now;
using (mocks.Record())
{
SetupResult.For(dtf.GetNow()).Do((Func<DateTime>)delegate { return desiredNowTime; });
}
using (mocks.Playback())
{
DoStuff(dtf); // Prints the current time
desiredNowTime += TimeSpan.FromMinutes(1); // 1 minute later
DoStuff(dtf); // Prints the time 1 minute from now
}
}
void DoStuff(IDateTimeFactory factory)
{
DateTime time = factory.GetNow();
Console.WriteLine(time);
}
FWIW,我不相信您可以使用 stub 来完成此操作;你需要使用模拟来代替。
关于.net - Rhino Mocks : Re-assign a new result for a method on a stub,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/123394/