是否可以在没有 for 循环的情况下断言数组中一个或多个元素的存在?

Is it possible to assert the existence of one or more elements in an array without a for loop?

我正在用 XUnit 测试一个函数。虽然测试正确地完成了在返回的 Type[] 数组中识别 "System.DateTime" 是否存在的工作,但我必须通过遍历数组来完成这项工作。 (为什么要测试我已经知道的 DateTime 属性 是否存在?因为我正在通过玩一些我已经熟悉的代码来学习 TDD。)

有没有Assert函数可以确认数组中某个元素的存在?我问这个问题是因为,虽然它有效,但我不禁想知道除了遍历数组之外是否还有更有效或更紧凑的方法来做到这一点。

我希望 Assert 中有一个我可以利用的未记录的功能。

/// <summary>
/// This tests the "GetPropertyTypes(PropertyInfo[] properties)" function to 
/// confirm that any DateTime properties in the "TestClass" are confirmed as existing.
/// </summary>
[Fact]
public void ConfirmDateTimePropertiesInModelExist()
{
    // Arrange
    PropertyInfo[] propertiesInfos = typeof(TestClass).GetProperties();
    int dateTimeCount = 0;

    // Act
    // The names array the list of property types in "TestClass"
    Type[] propertyTypes = ExportToExcelUtilities.GetPropertyTypes(propertiesInfos);

    for (int i = 0; i < propertyTypes.Length; i++)
        if (propertyTypes[i] == typeof(DateTime))
            dateTimeCount++;

    // Assert
    // Assert that the names array contains one or more "System.DateTime" properties.
    Assert.True(dateTimeCount>0,
        "Existing DateTime properties were not identified in the class.");
}

LINQ 可以快速解决这个问题:

Assert.True(propertyTypes.Any(n => n == typeof(DateTime)))

您不一定需要自定义断言,因为您可以在 Assert.True().

中使用标准数组命令

例如,您可以使用 Array.FindIndex()

var index = Array.FindIndex(propertyTypes, t => t == typeof(DateTime));

如果索引大于 -1,则找到一个项目。所以在断言中使用它:

Assert.True(
    Array.FindIndex(propertyTypes, t => t == typeof(DateTime)) > -1,
    "Existing DateTime properties were not identified in the class."
);