我想模拟一些基于类型对象的接口(interface)。我需要这个来通过反射调用构造函数。它看起来像这样:
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 来完成?
最佳答案
bump 部分正确,但我想要得到的是通过反射创建的模拟,解决方案看起来像这样:
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[] {});
}
关于c# - 基于类型对象的模拟接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23042684/