2010-01-14 37 views
9

根據Charlie Poole's NUnit blog,可以在NUnit 2.5中使用Lambda表達式作爲約束條件。我似乎無法得到它的工作?我正在使用NUnit 2.5.3.9345。在NUnit 2.5中使用Lambdas作爲約束條件?

從博客文章使用示例拉姆達:在編譯

[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。有什麼我愚蠢地做錯了嗎?

回答

12

我認爲編譯器無法處理lambda,因爲它不能推斷參數類型。 試試這個:

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

它的工作原理應該如此。有點慚愧我沒有注意到我自己:( – 2010-01-14 10:18:23

+0

編譯器消息不是特別明確的...... – 2010-01-14 10:26:01

+0

我有同樣的問題,它看起來像我只是沒有得到lambda語法正確。謝謝!:) – adamjford 2010-12-10 21:13:39

2

Matches約束在NUnit的版本3個重載我使用(2.5.9),其中之一是

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

所以,如果您在類型傳遞在方法調用的參數,可能的工作,像這樣:

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

它可以定義在一個集合的約束,與NUnit的Framework版本2.6.12296測試,使用Has.All.Matches(somepredicate)

[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; 
    }