我正在創建單元測驗,我將在其中將物件串列相互比較。
目前我將 Fluent 斷言與 specflow 和 nunit 結合使用。我已經使用 Fluent Assertions 進行了如下比較:
public void TestShizzle()
{
// I normally retrieve these lists from a moq database or a specflow table
var expected = list<myObject>
{
new myObject
{
A = 1,
B = "abc"
}
}
var found = list<myObject>
{
new myObject
{
A = 1,
B = "def"
}
}
// this comparison only compares a few columns. The comparison is also object dependent. I would like to make this dynamic
found.Should().BeEquivalentTo(
expected,
options =>
options.Including(x => x.A));
}
我真正想要的是能夠使用泛型而不是指定的型別。我還想決定在編譯時要比較哪些屬性。這是因為資料庫中有大量的表。我想我需要為此使用 Linq 運算式,但我不知道該怎么做。該函式應如下所示:
public void GenericShizzle<T>(List<T> expected, List<T> found, IEnumerable<PropertyInfo> properties)
{
Expression<Func<T, object>> principal;
foreach(var property in properties)
{
// create the expression for including fields
}
found.Should().BeEquivalentTo(
expected,
options =>
// here is need to apply the expression.
}
我不知道如何獲得作業的正確表達方式,或者這是否是最好的方法。我想我需要創建一個包含函式可以理解的屬性運算式,但也許可以使用不同的方法?
uj5u.com熱心網友回復:
有Including方法多載接受Expression<Func<IMemberInfo, bool>>,可用于根據有關成員的資訊動態過濾成員:
IEnumerable<PropertyInfo> properties = ...;
var names = properties
.Select(info => info.Name)
.ToHashSet();
found.Should()
.BeEquivalentTo(expected,
options => options.Including((IMemberInfo mi) => names.Contains(mi.Name))); // or just .Including(mi => names.Contains(mi.Name))
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/465683.html
