NSubstitute可以模拟MethodInfo的返回值吗?

3

我的测试使用了很多反射。NSubstitute可以像这样模拟反射属性(PropertyInfo):

mock
.GetType().GetTypeInfo()
.GetProperty("SomePropertyName")
.GetValue(mock)
.Returns(someReturnValue);   // NSubstitute does its thing here

如何为 MethodInfo 实现类似的功能?
1个回答

4

像这样:

  internal class Program
  {
    private static void Main()
    {
      var mock = Substitute.For<SomeClass>();
      var mi = mock.GetType().GetTypeInfo()
        .GetMethod("SomeMethod", BindingFlags.NonPublic | BindingFlags.Instance);

      mi.Invoke(mock, null).Returns("xxxxXXX");

      Console.WriteLine(mi.Invoke(mock, null)); // -> Write xxxxXXX
    }
  }

  public class SomeClass
  {
    protected virtual string SomePropertyName { get; set; }

    protected virtual string SomeMethod() => "aaa";
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接