Using.cs 2.2 KB

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