基于类型对象的模拟接口

时间:2014-04-13 12:22:53

标签: c# mocking

我想基于类型对象模拟一些接口。我需要这个通过反射来调用构造函数。它看起来像这样:

        var type = typeof (T);
        var constructors = type.GetConstructors();
        var constructor = constructors.First();
        var parameters = constructor.GetParameters();
        var objects = new object[parameters.Count()];
        //TODO create mock parameters and add to aobject array
        constructor.Invoke(objects);

是否有可能实现这样的目标?是否有任何模拟框架为此提供了功能?或者也许可以使用BCL完成?

1 个答案:

答案 0 :(得分:0)

碰撞是部分正确的,但我想要得到的是通过反射和解决方案的模拟,这将是这样的:

public static object DynamicMock(Type type)
{
   var mock = typeof(Mock<>).MakeGenericType(type).GetConstructor(Type.EmptyTypes).Invoke(new object[] { });
   return mock.GetType().GetProperties().Single(f => f.Name == "Object" && f.PropertyType == type).GetValue(mock, new object[] {});
}
相关问题