내가하려는 것은 AutoFixture 및 Moq를 사용하여 리포지토리를 일반화하는 것입니다. 목록에 가짜 레코드를 추가하는 'add'라는 메서드가 있습니다. 목록을 레코드라고하며 클래스 전체에 적용됩니다. 일반 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;
}
확장 클래스와 함께 (이 검색 SO를 찾았습니다) :
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);
}
}
내가 받고있는 오류는 "Ploeh.AutoFixture.dll에서 ArgumentException이 발생했습니다"입니다.
내 질문은 : 컴파일 타임에 모델을 알 수 없을 때 메서드의 매개 변수로 일반 개체의 속성을 어떻게 전달할 수 있습니까?
With
메소드에는 Expression<Func<T, TProperty>>
매개 변수 가 필요 하지 않습니다 PropertyInfo
.
문자열 대신 사용할 add
방법을 변경할 수 있습니다 Expression<Func<T, TProperty>>
.
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] 삭제
몇 마디 만하겠습니다