0

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

下面的代码将在 TypeBuilderTest 的 TypeMock.Foo() 处抛出 Expected: But was: (Common Language Runtime detected an invalid program.)。

    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());
    }
4

0 回答 0