将通用类的属性作为参数传递给AutoMoq

亚伦·盖茨

我想做的是概括使用AutoFixture和Moq制作存储库。我有一个称为“添加”的方法,可将伪造的记录添加到列表中。该列表称为记录,对于该类而言是全局的。通用M是要模拟的模型。该方法返回“ this”,因此可以链接该方法。

public Repo<M> add(string prop, string val) {
    var a = fixture.Build<M>().With(m => m.GetProperty(prop), val).Create();
    records.Add(a);
    return this;
}

与扩展类(我发现这样搜索):

public static class MyExtensions
{
    public static object GetProperty<T>(this T obj, string name) where T : class
    {
        Type t = typeof(T);
        return t.GetProperty(name).GetValue(obj, null);
    }
}

我收到的错误是“ ArgumentException发生在Ploeh.AutoFixture.dll中”。

我的问题是:当模型在编译时未知时,如何传递通用对象的属性作为方法的参数?

Arkadiusz K

With方法需要Expression<Func<T, TProperty>>参数not PropertyInfo

您可以将add方法Expression<Func<T, TProperty>>改为采用string代替:

public Repo<M> add<T>(Expression<Func<M, T>> propertyPicker, T val) 
{
   var a = fixture.Build<M>().With(propertyPicker, val).Create();
   records.Add(a);
   return this;
}

这是用法:

add(foo => foo.Name, "abc");

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章