ElementAtOrDefault.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using Xunit;
  10. namespace Tests
  11. {
  12. public class ElementAtOrDefault : AsyncEnumerableTests
  13. {
  14. [Fact]
  15. public async Task ElementAtOrDefault_Null()
  16. {
  17. await Assert.ThrowsAsync<ArgumentNullException>(() => AsyncEnumerable.ElementAtOrDefault<int>(default, 0));
  18. await Assert.ThrowsAsync<ArgumentNullException>(() => AsyncEnumerable.ElementAtOrDefault<int>(default, 0, CancellationToken.None));
  19. }
  20. [Fact]
  21. public void ElementAtOrDefault1()
  22. {
  23. var res = AsyncEnumerable.Empty<int>().ElementAtOrDefault(0);
  24. Assert.Equal(0, res.Result);
  25. }
  26. [Fact]
  27. public void ElementAtOrDefault2()
  28. {
  29. var res = Return42.ElementAtOrDefault(0);
  30. Assert.Equal(42, res.Result);
  31. }
  32. [Fact]
  33. public void ElementAtOrDefault3()
  34. {
  35. var res = Return42.ElementAtOrDefault(1);
  36. Assert.Equal(0, res.Result);
  37. }
  38. [Fact]
  39. public void ElementAtOrDefault4()
  40. {
  41. var res = new[] { 1, 42, 3 }.ToAsyncEnumerable().ElementAtOrDefault(1);
  42. Assert.Equal(42, res.Result);
  43. }
  44. [Fact]
  45. public void ElementAtOrDefault5()
  46. {
  47. var res = new[] { 1, 42, 3 }.ToAsyncEnumerable().ElementAtOrDefault(7);
  48. Assert.Equal(0, res.Result);
  49. }
  50. [Fact]
  51. public void ElementAtOrDefault6()
  52. {
  53. var res = Return42.ElementAtOrDefault(-1);
  54. Assert.Equal(0, res.Result);
  55. }
  56. [Fact]
  57. public void ElementAtOrDefault7()
  58. {
  59. var ex = new Exception("Bang!");
  60. var res = Throw<int>(ex).ElementAtOrDefault(15);
  61. AssertThrows<Exception>(() => res.Wait(WaitTimeoutMs), SingleInnerExceptionMatches(ex));
  62. }
  63. }
  64. }