简体   繁体   中英

Can NSubstitute mock the return of a MethodInfo?

My tests use lots of reflection. NSubstitute can mock reflected properties ( PropertyInfo ) like this:

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

How do I do something similar for a MethodInfo ?

Something like this:

  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";
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM