NSubstitute可以模拟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";
}
标签:nsubstitute,unit-testing,c 来源: https://codeday.me/bug/20191111/2022292.html