TimeProvider abstract class is a .NET 8 feature that provides the abstractions to be able to mock time in a unit test.
Combined with the
FakeTimeProvider class, we can set the current UTC time and local time zone. In-addition, we can also create a timer.
You can learn more about this with our TimeProvider and mocking time tutorial.
This code example is a xUnit test project which provides examples on how to mock the time and mock a timer for when the callback has been invoked.
.NET 8 is due to be released in November 2023. When it is released, you'll need to update Visual Studio 2022 to version 17.8 and ensure that the .NET 8 SDK is installed.
These are the steps to get the application working.
You are now ready to go.
RoundTheCode.TimeProviderMock.sln in Visual Studio 2022 Preview.
This will open up an xUnit test project.
All the tests are written in the
You can run the tests in Visual Studio by going to Test and Run All Tests in the top menu. This will open up Test Explorer and you should see that all three tests pass.
Watch our video where we go ahead and use the TimeProvider class to set up these unit tests.