Skip to content

Use Time Provider to fix time related tests#3077

Merged
iancooper merged 2 commits into
masterfrom
fix_time_tests
May 12, 2024
Merged

Use Time Provider to fix time related tests#3077
iancooper merged 2 commits into
masterfrom
fix_time_tests

Conversation

@iancooper

Copy link
Copy Markdown
Member

.NET 8 adds TimeProvider which can be used to provide system time; it also supports FakeTimeProvider which can be used to fake an advancing clock, provide a fake timer etc. There is a backport of the interface and library to netstandard2.0

We have tests that rely on time, specifically where we:

  • Clear a cache following expiry of a time period (in memory box)
  • Determine if items in an Outbox are outstanding.

Many of these come together in Paramore.Brighter.InMemory.Tests. We stopped running these because they were flaky in contested CI environments as they relied on delaying action/assertion until time had passed.

With this change we use TimeProvider with our InMemoryBox (used by default if you don't provide an out of process alternative). This allows us to advance time for use with the tests around this functionality. The Advance method to set the clock forward works well, and helps with our tests where we want something to expire.

Note the Delay method doesn’t work as expected where we need to yield to allow another thread to complete. So we continue to use Task.Delay where we need a background thread to run. (It also doesn't seem to play nice with async xunit tests, which seem to spin).

@preardon preardon left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good, good to know that Microsoft do this out of the box now

@iancooper iancooper merged commit bfc4681 into master May 12, 2024
@iancooper iancooper deleted the fix_time_tests branch May 12, 2024 17:17
DevJonny pushed a commit to DevJonny/Brighter that referenced this pull request Feb 28, 2026
* Move to using TimeProvider with InMemoryBox to allow easier faking of times in tests.

* Add in memory tests back; use Task.Delay to delay, but advance when window closure required.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants