ThreadAbstraction_ExecuteThread.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System;
  2. using System.Threading;
  3. #if SILVERLIGHT
  4. using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
  5. #else
  6. using Microsoft.VisualStudio.TestTools.UnitTesting;
  7. #endif
  8. using Renci.SshNet.Abstractions;
  9. namespace Renci.SshNet.Tests.Abstractions
  10. {
  11. [TestClass]
  12. public class ThreadAbstraction_ExecuteThread
  13. {
  14. [TestMethod]
  15. public void ShouldThrowArgumentNullExceptionWhenActionIsNull()
  16. {
  17. const Action action = null;
  18. try
  19. {
  20. ThreadAbstraction.ExecuteThread(action);
  21. Assert.Fail();
  22. }
  23. catch (ArgumentNullException ex)
  24. {
  25. Assert.IsNull(ex.InnerException);
  26. Assert.AreEqual("action", ex.ParamName);
  27. }
  28. }
  29. [TestMethod]
  30. public void ShouldExecuteActionOnSeparateThread()
  31. {
  32. DateTime? executionTime = null;
  33. int executionCount = 0;
  34. EventWaitHandle waitHandle = new ManualResetEvent(false);
  35. Action action = () =>
  36. {
  37. ThreadAbstraction.Sleep(500);
  38. executionCount++;
  39. executionTime = DateTime.Now;
  40. waitHandle.Set();
  41. };
  42. DateTime start = DateTime.Now;
  43. ThreadAbstraction.ExecuteThread(action);
  44. Assert.AreEqual(0, executionCount);
  45. Assert.IsNull(executionTime);
  46. Assert.IsTrue(waitHandle.WaitOne(2000));
  47. Assert.AreEqual(1, executionCount);
  48. Assert.IsNotNull(executionTime);
  49. var elapsedTime = executionTime.Value - start;
  50. Assert.IsTrue(elapsedTime > TimeSpan.Zero);
  51. Assert.IsTrue(elapsedTime > TimeSpan.FromMilliseconds(500));
  52. Assert.IsTrue(elapsedTime < TimeSpan.FromMilliseconds(1000));
  53. }
  54. }
  55. }