在NUnit 2.5中使用Lambdas作为约束?

时间:2010-01-14 09:26:11

标签: c# unit-testing nunit lambda

根据Charlie Poole's NUnit blog,可以在NUnit 2.5中使用Lambda表达式作为约束。我似乎无法让它工作?我使用的是NUnit 2.5.3.9345。

使用博客文章中的示例lambda:

[TestFixture]
public class Class1
{
    [Test]
    public void someTest()
    {
        int[] array = {1, 2, 3, 4};
        Assert.That( array, Is.All.Matches( (x) => x%4 == 0 && x%100 != 0 || x%400 == 0 ));
    }
}

编译器中的结果说: “无法将lambda表达式转换为'NUnit.Framework.Constraints.Constraint'类型,因为它不是委托类型”

程序集的目标框架是.NET Framework 3.5。有什么我愚蠢地做错了吗?

3 个答案:

答案 0 :(得分:13)

我认为编译器无法处理lambda,因为它无法推断出参数类型。 试试这个:

Assert.That( array, Is.All.Matches( (int x) => x%4 == 0 && x%100 != 0 || x%400 == 0 ));

答案 1 :(得分:3)

Matches约束在我正在使用的NUnit版本中有3个重载(2.5.9),其中一个是

public Constraint Matches<T>(Predicate<T> predicate)

因此,如果您在方法调用中传入type参数,那可能会起作用,如下所示:

Assert.That(array, Is.All.Matches<int>(x => (rest of lambda body)));

答案 2 :(得分:1)

可以使用 Has.All.Matches(somepredicate)在集合上定义约束,使用NUnit Framework版本2.6.12296进行测试。

    [Test]
    [TestCase("1000")]
    public void ListSubOrganizationsFiltersAwayDeprecatedOrganizations(string pasId)
    {
        var request = ListOrganizations2GRequest.Initialize(pasId);

        var unitsNotFiltered = OrganizationWSAgent.ListOrganizations2G(PasSystemTestProvider.PasSystemWhenTesting, request);

        request.ValidPeriod = new ListOrganizations2GRequestValidPeriod { ValidFrom = new DateTime(2015, 3, 24), ValidFromSpecified = true };

        var unitsFiltered = OrganizationWSAgent.ListOrganizations2G(PasSystemTestProvider.PasSystemWhenTesting, request);

        Assert.IsNotNull(unitsNotFiltered);
        Assert.IsNotNull(unitsFiltered);
        CollectionAssert.IsNotEmpty(unitsFiltered.Organization);
        CollectionAssert.IsNotEmpty(unitsNotFiltered.Organization);

        int[] unitIdsFiltered = unitsFiltered.Organization[0].SubsidiaryOrganization.Select(so => so.Id).ToArray();

        var filteredUnits = unitsNotFiltered.Organization[0].SubsidiaryOrganization
            .Where(u => !unitIdsFiltered.Contains(u.Id)).ToList();

        Assert.IsNotNull(filteredUnits);
        CollectionAssert.IsNotEmpty(filteredUnits);
        Assert.That(filteredUnits, Has.All.Matches<OrganizationHierarchySimpleType>(ohs => (!IsValidPeriodForToday(ohs)))); 
    }

    private static bool IsValidPeriodForToday(OrganizationHierarchySimpleType ohs)
    {
        return ohs.ValidPeriod != null
               && ohs.ValidPeriod.ValidFrom <= DateTime.Now && ohs.ValidPeriod.ValidTo >= DateTime.Now;
    }