SystemClockTests.cs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading.Tasks;
  4. namespace DesktopClock.Tests;
  5. public class SystemClockTimerTests
  6. {
  7. private readonly SystemClockTimer _timer;
  8. public SystemClockTimerTests()
  9. {
  10. _timer?.Dispose();
  11. _timer = new SystemClockTimer();
  12. }
  13. [Theory(Skip = "Relies on system performance")]
  14. [InlineData(3)]
  15. public async Task ShouldTickEverySecondAccurately(int seconds)
  16. {
  17. // Ensure the timer is started at an unclean time to test accuracy.
  18. await Task.Delay(1000 - DateTimeOffset.Now.Millisecond + 234);
  19. Assert.NotInRange(DateTimeOffset.Now.Millisecond, 0, 100);
  20. var tickTimes = new List<DateTimeOffset>();
  21. _timer.SecondChanged += (sender, args) =>
  22. {
  23. tickTimes.Add(DateTimeOffset.Now);
  24. };
  25. _timer.Start();
  26. await Task.Delay(TimeSpan.FromSeconds(seconds));
  27. _timer.Stop();
  28. Assert.Equal(seconds, tickTimes.Count);
  29. // Check that each tick is close to the exact second.
  30. foreach (var tickTime in tickTimes)
  31. {
  32. Assert.InRange(tickTime.Millisecond, 0, 100);
  33. }
  34. }
  35. }