犀牛制品:对存根的方法重新分配一个新的结果 [英] Rhino Mocks: Re-assign a new result for a method on a stub
问题描述
我知道我能做到这一点:
I know I can do this:
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(),我怎么做同样的事情?
What if instead of IDateTimeFactory.Now being a property it is a method IDateTimeFactory.GetNow(), how do I do the same thing?
根据犹大的建议,下面我已经重写我的SetDateTime helper方法如下:
As per Judah's suggestion below I have rewritten my SetDateTime helper method as follows:
private void SetDateTime(DateTime dt) {
Expect.Call(_now_factory.GetNow()).Repeat.Any();
LastCall.Do((Func<DateTime>)delegate() { return dt; });
}
但它仍然抛出的结果ICurrentDateTimeFactory.GetNow();已经被设置。错误。
but it still throws "The result for ICurrentDateTimeFactory.GetNow(); has already been setup." errors.
另外它还是不会有存根工作....
Plus its still not going to work with a stub....
推荐答案
乔治
使用更新后的code,我得到这个工作:
Using your updated code, I got this to work:
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,我不相信你可以做到这一点使用存根;你需要使用一个模拟代替。
FWIW, I don't believe you can accomplish this using stubs; you need to use a mock instead.
这篇关于犀牛制品:对存根的方法重新分配一个新的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!