Skip to content

Commit 5cbb828

Browse files
committed
Merge remote-tracking branch 'origin/master'
2 parents df966ff + 7ef4db5 commit 5cbb828

File tree

1 file changed

+48
-1
lines changed

1 file changed

+48
-1
lines changed

README.md

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,50 @@
11
## Xtensible.Time
2-
2+
[![Nuget](https://img.shields.io/nuget/dt/Xtensible.Time.Clock.svg?logo=Nuget&style=flat-square)](https://www.nuget.org/packages/Xtensible.Time.Clock)
3+
### TL;DR
34
An easy to use mockable clock. Pass `WallClock` to your services in production/dev code and use MockClock in unit tests; or, if you don't want to pass around a clock, do `Clock.Default = new MockClock();` in your unit tests.
5+
6+
### Usage
7+
Xtensible.Time supports two styles. You can write services that take in a clock object like so:
8+
```csharp
9+
public class MyService()
10+
{
11+
private IClock Clock {get;}
12+
public MyService(IClock clock)
13+
{
14+
Clock = clock;
15+
}
16+
17+
public DateTimeOffset GetTime()
18+
{
19+
return Clock.Default.Now;
20+
}
21+
}
22+
```
23+
24+
In your app (desktop, asp.net, xamarin, etc, you'd inject a `WallClock` like so:
25+
```csharp
26+
var service = new MyService(new WallClock());
27+
```
28+
and in your unit trsts, you'd inject a `MockClock` like so:
29+
```csharp
30+
var service = new MyService(new MockClock(new DateTimeOffset(2019, 7, 1, 14, 0, 0, TimeSpan.Zero)));
31+
```
32+
33+
If you find passing around clock objects cumbersome, you can override the `Default` clock in the static `Clock` object in your unit tests' constructor. By default, the `Default` clock is a `WallClock`:
34+
```csharp
35+
Clock.Default = new MockClock(new DateTimeOffset(2019, 7, 1, 14, 0, 0, TimeSpan.Zero));
36+
```
37+
38+
### Adjusting the `MockClock`'s time
39+
`MockClock` has an `Adjust` method that can update the clock. You can use timespans or an adjustment in milliseconds:
40+
```csharp
41+
var clock = new MockClock(new DateTimeOffset(2019, 7, 1, 14, 0, 0, TimeSpan.Zero));
42+
// new time will be Jul 1, 2019 14:01:00
43+
clock.Adjust(60000);
44+
```
45+
46+
For your convenience, `Clock` has an `AsMockClock()` method so that you can do the following in your unit tests:
47+
```csharp
48+
// new time will be Jul 1, 2019 14:01:00
49+
Clock.AsMockClock().Adjust(60000);
50+
```

0 commit comments

Comments
 (0)