1 // Licensed to the .NET Foundation under one or more agreements. 2 // The .NET Foundation licenses this file to you under the MIT license. 3 // See the LICENSE file in the project root for more information. 4 5 using System.Linq.Expressions; 6 using Xunit; 7 8 namespace System.Linq.Tests 9 { 10 public class TakeWhileTests : EnumerableBasedTests 11 { 12 [Fact] SourceNonEmptyPredicateTrueSomeFalseSecond()13 public void SourceNonEmptyPredicateTrueSomeFalseSecond() 14 { 15 int[] source = { 8, 3, 12, 4, 6, 10 }; 16 int[] expected = { 8 }; 17 18 Assert.Equal(expected, source.AsQueryable().TakeWhile(x => x % 2 == 0)); 19 } 20 21 [Fact] SourceNonEmptyPredicateTrueSomeFalseSecondWithIndex()22 public void SourceNonEmptyPredicateTrueSomeFalseSecondWithIndex() 23 { 24 int[] source = { 8, 3, 12, 4, 6, 10 }; 25 int[] expected = { 8 }; 26 27 Assert.Equal(expected, source.AsQueryable().TakeWhile((x, i) => x % 2 == 0)); 28 } 29 30 [Fact] ThrowsOnNullSource()31 public void ThrowsOnNullSource() 32 { 33 IQueryable<int> source = null; 34 AssertExtensions.Throws<ArgumentNullException>("source", () => source.TakeWhile(x => true)); 35 } 36 37 [Fact] ThrowsOnNullPredicate()38 public void ThrowsOnNullPredicate() 39 { 40 IQueryable<int> source = new[] { 1, 2, 3 }.AsQueryable(); 41 Expression<Func<int, bool>> nullPredicate = null; 42 AssertExtensions.Throws<ArgumentNullException>("predicate", () => source.TakeWhile(nullPredicate)); 43 } 44 45 [Fact] ThrowsOnNullSourceIndexed()46 public void ThrowsOnNullSourceIndexed() 47 { 48 IQueryable<int> source = null; 49 AssertExtensions.Throws<ArgumentNullException>("source", () => source.TakeWhile((x, i) => true)); 50 } 51 52 [Fact] ThrowsOnNullPredicateIndexed()53 public void ThrowsOnNullPredicateIndexed() 54 { 55 IQueryable<int> source = new[] { 1, 2, 3 }.AsQueryable(); 56 Expression<Func<int, int, bool>> nullPredicate = null; 57 AssertExtensions.Throws<ArgumentNullException>("predicate", () => source.TakeWhile(nullPredicate)); 58 } 59 60 [Fact] TakeWhile1()61 public void TakeWhile1() 62 { 63 var count = (new int[] { 0, 1, 2 }).AsQueryable().TakeWhile(n => n < 2).Count(); 64 Assert.Equal(2, count); 65 } 66 67 [Fact] TakeWhile2()68 public void TakeWhile2() 69 { 70 var count = (new int[] { 0, 1, 2 }).AsQueryable().TakeWhile((n, i) => n + i < 4).Count(); 71 Assert.Equal(2, count); 72 } 73 } 74 } 75