从调用者创建方法/应答方法

本文关键字:方法 应答 创建 调用者 | 更新日期: 2023-09-27 18:18:20

我有一个很奇怪的问题要问。由于反射,我将一个类指向我的模拟类而不是"真实"类。(测试)。我想知道是否有任何方法可以捕获模拟中的任何方法调用,并根据调用正在等待的内容返回我想要的任何内容。

Some sort of:

调用另一个对象执行X()并期望为bool类型的对象。

因为我已经用反射改变了它指向的对象,所以我希望我的mock在X()被调用时返回"true"(尽管它没有实现X()本身)。

换句话说,不是触发"MethodNotFoundException",而是接收所有内容并相应地执行一些逻辑。

从调用者创建方法/应答方法

感谢@millimoose,最好的方法(也是相当简单的方法)是:

DynamicObject。TryInvoke方法

http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.tryinvoke.aspx

再次感谢!

可能,您正在获得的异常是MissingMethodException。也许下面的控制台应用程序可以指导您实现更具体的实现,但逻辑应该是相同的:

class Program
{
    /// <summary>
    /// a dictionary for holding the desired return values
    /// </summary>
    static Dictionary<string, object> _testReturnValues = new Dictionary<string, object>();
    static void Main(string[] args)
    {
        // adding the test return for method X
        _testReturnValues.Add("X", true);
        var result = ExecuteMethod(typeof(MyClass), "X");
        Console.WriteLine(result);
    }
    static object ExecuteMethod(Type type, string methodName)
    {
        try
        {
            return type.InvokeMember(methodName, BindingFlags.InvokeMethod, null, null, null);
        }
        catch (MissingMethodException e)
        {
            // getting the test value if the method is missing
            return _testReturnValues[methodName];
        }
    }
}
class MyClass
{
    //public static string X() 
    //{
    //    return "Sample return";
    //}
}