当我尝试使用 NSubstitute 1.7.1.0 来定义 Object.ToString 的行为(这是一个虚拟方法)时,NSubstitute 正在引发异常。
重现:
[Test]
public static void ToString_CanBeSubstituted()
{
var o = Substitute.For<object>();
o.ToString().Returns("Hello world");
Assert.AreEqual("Hello world", o.ToString());
}
失败:
NSubstitute.Exceptions.CouldNotSetReturnDueToNoLastCallException : Could not find a call to return from.
Make sure you called Returns() after calling your substitute (for example: mySub.SomeMethod().Returns(value)),
and that you are not configuring other substitutes within Returns() (for example, avoid this: mySub.SomeMethod().Returns(ConfigOtherSub())).
If you substituted for a class rather than an interface, check that the call to your substitute was on a virtual/abstract member.
Return values cannot be configured for non-virtual/non-abstract members.
Correct use:
mySub.SomeMethod().Returns(returnValue);
Potentially problematic use:
mySub.SomeMethod().Returns(ConfigOtherSub());
Instead try:
var returnValue = ConfigOtherSub();
mySub.SomeMethod().Returns(returnValue);
有没有办法使上述测试通过?
我的天真测试引发的异常是错误还是“设计使然”?