mirror of
https://github.com/jcreek/Creek.HelpfulExtensions.git
synced 2026-07-14 03:33:44 +00:00
Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| af60820c10 | |||
| 14530efb0f |
@@ -19,8 +19,8 @@
|
|||||||
<PackageLicenseFile>LICENSE</PackageLicenseFile>
|
<PackageLicenseFile>LICENSE</PackageLicenseFile>
|
||||||
<RepositoryType>git</RepositoryType>
|
<RepositoryType>git</RepositoryType>
|
||||||
<PackageTags>creek</PackageTags>
|
<PackageTags>creek</PackageTags>
|
||||||
<Version>1.1.0</Version>
|
<Version>1.2.0</Version>
|
||||||
<AssemblyVersion>1.1.0.0</AssemblyVersion>
|
<AssemblyVersion>1.2.0.0</AssemblyVersion>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace Creek.HelpfulExtensions
|
||||||
|
{
|
||||||
|
public static class SystemTime
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// This method exposes DateTime.Now as an instance of a function, that can be replaced in tests.
|
||||||
|
/// </summary>
|
||||||
|
#pragma warning disable S1104 // Fields should not have public accessibility
|
||||||
|
#pragma warning disable S2223 // Non-constant static fields should not be visible
|
||||||
|
public static Func<DateTime> Now = () => DateTime.Now;
|
||||||
|
#pragma warning restore S2223 // Non-constant static fields should not be visible
|
||||||
|
#pragma warning restore S1104 // Fields should not have public accessibility
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -40,3 +40,31 @@ foreach (var (item, index) in list.WithIndex())
|
|||||||
// ...
|
// ...
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## DateTime Extensions
|
||||||
|
|
||||||
|
### SystemTime.Now
|
||||||
|
|
||||||
|
This is technically not an extension, but fits well in this package. It's taken from [this blog](https://lostechies.com/jimmybogard/2008/11/09/systemtime-versus-isystemclock-dependencies-revisited/). This method exposes DateTime.Now as an instance of a function, that can be replaced in tests.
|
||||||
|
|
||||||
|
If you want to replace SystemTime.Now in a test you can do it like this:
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
[Test]
|
||||||
|
public void Should_test_something_here()
|
||||||
|
{
|
||||||
|
var systemTimeDate = new DateTime(2021, 9, 2);
|
||||||
|
SystemTime.Now = () => new DateTime(2021, 9, 2);
|
||||||
|
|
||||||
|
DateTime dateTimeToBeTested = systemTimeDate;
|
||||||
|
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
You can also set SystemTime.Now to any function that returns a DateTime:
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
var startDate = new DateTime(2021, 9, 2);
|
||||||
|
SystemTime.Now = () => startDate.AddDays(2);
|
||||||
|
```
|
||||||
|
|||||||
Reference in New Issue
Block a user