我在使用 NSubstitute 几次时遇到了一个奇怪的问题,虽然我知道如何解决它,但我一直无法解释它。
我精心设计了似乎是证明问题所需的最低限度的测试,它似乎与使用一种方法来创建替代返回值有关。
public interface IMyObject
{
int Value { get; }
}
public interface IMyInterface
{
IMyObject MyProperty { get; }
}
[TestMethod]
public void NSubstitute_ReturnsFromMethod_Test()
{
var sub = Substitute.For<IMyInterface>();
sub.MyProperty.Returns(MyMethod());
}
private IMyObject MyMethod()
{
var ob = Substitute.For<IMyObject>();
ob.Value.Returns(1);
return ob;
}
当我运行上述测试时,出现以下异常:
Test method globalroam.Model.NEM.Test.ViewModel.DelayedAction_Test.NSubstitute_ReturnsFromMethod_Test threw exception:
NSubstitute.Exceptions.CouldNotSetReturnException: Could not find a call to return from.
Make sure you called Returns() after calling your substitute (for example: mySub.SomeMethod().Returns(value)).
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.
但是,如果我更改测试方法以返回:
sub.MyProperty.Returns((a) => MyMethod());
或这个:
var result = MyMethod();
sub.MyProperty.Returns(result);
有用。
我只是想知道是否有人可以解释为什么会发生这种情况?