我的测试使用了大量的反射。 NSubstitute可以像这样模拟反射属性(PropertyInfo
):
mock
.GetType().GetTypeInfo()
.GetProperty("SomePropertyName")
.GetValue(mock)
.Returns(someReturnValue); // NSubstitute does its thing here
如何为MethodInfo
执行类似操作?
答案 0 :(得分:3)
这样的事情:
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";
}