TimeProvider example for mocking time and timer in xUnit

The 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.

C# coding challenges

C# coding challenges

Our online code editor allows you to compile the answer.

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.

Software

As .NET 8 is currently in preview, you'll need the preview version of Visual Studio 2022 (version 17.8 preview) and .NET 8 SDK (RC 2 or above).

.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.

Get the application working

These are the steps to get the application working.

  • Fill out the code example form. We will send you an email where you can download the code example.

You are now ready to go.

Open the project in Visual Studio

Open up RoundTheCode.TimeProviderMock.sln in Visual Studio 2022 Preview.

This will open up an xUnit test project.

All the tests are written in the TimeTests class.

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.

More information

Watch our video where we go ahead and use the TimeProvider class to set up these unit tests.