UsingTest.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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.Text;
  7. using System.Linq;
  8. using Xunit;
  9. namespace Tests
  10. {
  11. public class UsingTest : Tests
  12. {
  13. [Fact]
  14. public void Using_Arguments()
  15. {
  16. AssertThrows<ArgumentNullException>(() => EnumerableEx.Using<int, MyDisposable>(null, d => new[] { 1 }));
  17. AssertThrows<ArgumentNullException>(() => EnumerableEx.Using<int, MyDisposable>(() => new MyDisposable(), null));
  18. }
  19. [Fact]
  20. public void Using1()
  21. {
  22. var d = default(MyDisposable);
  23. var xs = EnumerableEx.Using(() => d = new MyDisposable(), d_ => new[] { 1 });
  24. Assert.Null(d);
  25. var d1 = default(MyDisposable);
  26. xs.ForEach(_ => { d1 = d; Assert.NotNull(d1); Assert.False(d1.Done); });
  27. Assert.True(d1.Done);
  28. var d2 = default(MyDisposable);
  29. xs.ForEach(_ => { d2 = d; Assert.NotNull(d2); Assert.False(d2.Done); });
  30. Assert.True(d2.Done);
  31. Assert.NotSame(d1, d2);
  32. }
  33. [Fact]
  34. public void Using2()
  35. {
  36. var d = default(MyDisposable);
  37. var xs = EnumerableEx.Using(() => d = new MyDisposable(), d_ => EnumerableEx.Throw<int>(new MyException()));
  38. Assert.Null(d);
  39. AssertThrows<MyException>(() => xs.ForEach(_ => { }));
  40. Assert.True(d.Done);
  41. }
  42. [Fact]
  43. public void Using3()
  44. {
  45. var d = default(MyDisposable);
  46. var xs = EnumerableEx.Using<int, MyDisposable>(() => d = new MyDisposable(), d_ => { throw new MyException(); });
  47. Assert.Null(d);
  48. AssertThrows<MyException>(() => xs.ForEach(_ => { }));
  49. Assert.True(d.Done);
  50. }
  51. private class MyDisposable : IDisposable
  52. {
  53. public bool Done;
  54. public void Dispose()
  55. {
  56. Done = true;
  57. }
  58. }
  59. }
  60. }