Shouldly
Search…
ShouldBe

Objects

ShouldBeExamples works on all types and compares using .Equals.
1
var theSimpsonsCat = new Cat { Name = "Santas little helper" };
2
theSimpsonsCat.Name.ShouldBe("Snowball 2");
Copied!
Exception
1
theSimpsonsCat.Name
2
should be
3
"Snowball 2"
4
but was
5
"Santas little helper"
6
difference
7
Difference | | | | | | | | | | | | | | | | | | |
8
| \|/ \|/ \|/ \|/ \|/ \|/ \|/ \|/ \|/ \|/ \|/ \|/ \|/ \|/ \|/ \|/ \|/ \|/
9
Index | 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
10
Expected Value | S n o w b a l l \s 2
11
Actual Value | S a n t a s \s l i t t l e \s h e l p e r
12
Expected Code | 83 110 111 119 98 97 108 108 32 50
13
Actual Code | 83 97 110 116 97 115 32 108 105 116 116 108 101 32 104 101 108 112 101 114
Copied!

Numeric

ShouldBe numeric overloads accept tolerances and has overloads for float, double and decimal types.
1
const decimal pi = (decimal)Math.PI;
2
pi.ShouldBe(3.24m, 0.01m);
Copied!
Exception
1
pi
2
should be within
3
0.01m
4
of
5
3.24m
6
but was
7
3.14159265358979m
Copied!

DateTime(Offset)

DateTime overloads are similar to the numeric overloads and support tolerances.
1
var date = new DateTime(2000, 6, 1);
2
date.ShouldBe(new DateTime(2000, 6, 1, 1, 0, 1), TimeSpan.FromHours(1));
Copied!
Exception
1
date
2
should be within
3
01:00:00
4
of
5
2000-06-01T01:00:01.0000000
6
but was
7
2000-06-01T00:00:00.0000000
Copied!

TimeSpan

TimeSpan also has tolerance overloads
1
var timeSpan = TimeSpan.FromHours(1);
2
timeSpan.ShouldBe(timeSpan.Add(TimeSpan.FromHours(1.1d)), TimeSpan.FromHours(1));
Copied!
Exception
1
timeSpan
2
should be within
3
01:00:00
4
of
5
02:06:00
6
but was
7
01:00:00
Copied!

Enumerables

Enumerable comparison is done on the elements in the enumerable, so you can compare an array to a list and have it pass.
1
var apu = new Person { Name = "Apu" };
2
var homer = new Person { Name = "Homer" };
3
var skinner = new Person { Name = "Skinner" };
4
var barney = new Person { Name = "Barney" };
5
var theBeSharps = new List<Person> { homer, skinner, barney };
6
theBeSharps.ShouldBe(new[] { apu, homer, skinner, barney });
Copied!
Exception
1
theBeSharps
2
should be
3
[Apu, Homer, Skinner, Barney]
4
but was
5
[Homer, Skinner, Barney]
6
difference
7
[*Homer*, *Skinner*, *Barney*, *]
Copied!

Enumerables of Numerics

If you have enumerables of float, decimal or double types then you can use the tolerance overloads, similar to the value extensions.
1
var firstSet = new[] { 1.23m, 2.34m, 3.45001m };
2
var secondSet = new[] { 1.4301m, 2.34m, 3.45m };
3
firstSet.ShouldBe(secondSet, 0.1m);
Copied!
Exception
1
firstSet
2
should be within
3
0.1m
4
of
5
[1.4301m, 2.34m, 3.45m]
6
but was
7
[1.23m, 2.34m, 3.45001m]
8
difference
9
[*1.23m*, 2.34m, *3.45001m*]
Copied!

Bools

1
const bool myValue = false;
2
myValue.ShouldBe(true, "Some additional context");
Copied!
Exception
1
myValue
2
should be
3
True
4
but was
5
False
6
7
Additional Info:
8
Some additional context
Copied!
Last modified 1yr ago