我有一个 TimeMachine
类,它为我提供当前日期/时间值。该类看起来像这样:
public class TimeMachine
{
public virtual DateTime GetCurrentDateTime(){ return DateTime.Now; };
public virtual DateTime GetCurrentDate(){ return GetCurrentDateTime().Date; };
public virtual TimeSpan GetCurrentTime(){ return GetCurrentDateTime().TimeOfDay; };
}
我想在我的测试中使用 TimeMachine
stub ,我只是 stub GetCurrentDateTime
方法,让其他 2 个方法使用 stub GetCurrentDateTime
方法,这样我就不必对所有这三种方法进行 stub 。我试着像这样写测试:
var time = MockRepository.GenerateStub<TimeMachine>();
time.Stub(x => x.GetCurrentDateTime())
.Return(new DateTime(2009, 11, 25, 12, 0, 0));
Assert.AreEqual(new DateTime(2009, 11, 25), time.GetCurrentDate());
但是测试失败了。 GetCurrentDate
返回 default(DateTime)
而不是在内部使用 GetCurrentDateTime
stub 。
有没有什么方法可以用来实现这种行为,或者它只是我目前没有掌握的 RhinoMocks 的一些基本概念特征?我知道我可以摆脱这两个 GetDate
/Time
方法并内联 .Date
/.TimeOfDay
用法,但我想了解这是否可能。
最佳答案
如果该方法被标记为virtual
,Stub 将不会调用原始方法,即使您没有对该方法进行 Stub。您可以通过以下方式强制 RhinoMocks 调用原始方法:
var time = MockRepository.GenerateStub<TimeMachine>();
time.Stub(x => x.GetCurrentDateTime()).Return(new DateTime(2009, 11, 25, 12, 0, 0));
time.Stub(x => x.GetCurrentDate()).CallOriginalMethod(OriginalCallOptions.NoExpectation);
Assert.AreEqual(new DateTime(2009, 11, 25), time.GetCurrentDate());
这是使 RhinoMocks 调用底层原始方法的第三行(分开的)。
关于c# - stub 类的一个方法,让其他真正的方法使用这个 stub 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1797749/