2017-01-29 130 views
3

我的測試使用了很多反射。 NSubstitute可以模擬反射特性(PropertyInfo)是這樣的:NSBuild可以模擬MethodInfo的返回嗎?

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

我該怎麼做了MethodInfo類似的東西?

回答

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