13

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);

できます。

誰かがなぜこれが起こるのか説明できるかどうか疑問に思っていますか?

4

1 に答える 1