创建运行时模拟:编译Expression.Throw与Expression.Throw后,InvalidProgramException

时间:2018-08-23 14:26:59

标签: c# .net linq emit invalidprogramexception

我正在尝试创建一个运行时模拟程序,它将对每种方法都有特定的行为,将被调用。例如,此模拟应始终返回null-已经在工作-或为无法访问的数据库引发异常,或者在这种特定情况下,引发Argument Exception。 我知道,使用模拟框架可以很容易地做到这一点。但是由于我必须通过Spring.NET使用它,据我所知,我不能使用模拟框架。这是因为我必须在StaticApplicationContext中提供类型。如果有更简单的方法来创建模拟类型,请告诉我。

以下代码将引发Expected:   但是是:(公共语言运行时检测到无效程序。)    在TypeMock.Foo()    在TypeBuilderTest中。

    public interface IInterfaceWithObject
    {
        String Foo();
    }

    [Test]
    public void MinimalExample()
    {
        //build expression
        var constructorInfo = typeof(ArgumentNullException).GetConstructor(new Type[0]);
        Assert.IsNotNull(constructorInfo);
        Expression expression = Expression.Throw(Expression.New(constructorInfo));

        //create type
        // based upon https://stackoverflow.com/questions/38345486/dynamically-create-a-class-by-interface
        var ab = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("TestAssembly"), AssemblyBuilderAccess.Run);
        var mb = ab.DefineDynamicModule("Test");

        TypeBuilder typeBuilder = mb.DefineType("TypeMock");

        typeBuilder.DefineDefaultConstructor(MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);

        typeBuilder.AddInterfaceImplementation(typeof(IInterfaceWithObject));
        List<MethodInfo> methods = new List<MethodInfo>(typeof(IInterfaceWithObject).GetMethods());
        foreach (Type interf in typeof(IInterfaceWithObject).GetInterfaces())
        {
            foreach (MethodInfo method in interf.GetMethods())
                if (!methods.Contains(method))
                    methods.Add(method);
        }
        foreach (var imethod in methods)
        {
            var parameters = imethod.GetParameters();
            List<Type> parameterTypes = new List<Type>();
            foreach (var parameter in parameters)
            {
                parameterTypes.Add(parameter.ParameterType);
            }
            var method =
              typeBuilder.DefineMethod
              (
                "@@" + imethod.Name,
                MethodAttributes.Public | MethodAttributes.Static,
                imethod.ReturnType,
                parameterTypes.ToArray()
              );
            var thisParameter = Expression.Parameter(typeof(IInterfaceWithObject), "this");
            var bodyExpression = Expression.Lambda
                (expression
                    ,
                    thisParameter
                );

            bodyExpression.CompileToMethod(method);
            var stub =
              typeBuilder.DefineMethod(imethod.Name, MethodAttributes.Public | MethodAttributes.Virtual, imethod.ReturnType, parameterTypes.ToArray());
            var il = stub.GetILGenerator();
            il.Emit(OpCodes.Ldarg_0);
            il.EmitCall(OpCodes.Call, method, null);
            il.Emit(OpCodes.Ret);

            typeBuilder.DefineMethodOverride(stub, imethod);
        }
        Type type =  typeBuilder.CreateType();

        //create instance via spring.net
        StaticApplicationContext context = new StaticApplicationContext();
        MutablePropertyValues value = new MutablePropertyValues();
        string objectName = "Integer";
        context.RegisterSingleton(objectName, type, value);
        var objectInstance = (IInterfaceWithObject)context.GetObject(objectName);
        Assert.Throws<ArgumentNullException>(() => objectInstance.Foo());
    }

0 个答案:

没有答案