我的测试使用了很多反射。NSubstitute可以像这样模拟反射属性(PropertyInfo
):
mock
.GetType().GetTypeInfo()
.GetProperty("SomePropertyName")
.GetValue(mock)
.Returns(someReturnValue); // NSubstitute does its thing here
如何为
MethodInfo
实现类似的功能?我的测试使用了很多反射。NSubstitute可以像这样模拟反射属性(PropertyInfo
):
mock
.GetType().GetTypeInfo()
.GetProperty("SomePropertyName")
.GetValue(mock)
.Returns(someReturnValue); // NSubstitute does its thing here
MethodInfo
实现类似的功能?像这样:
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";
}