ShouldBeNull
and ShouldNotBeNull
allow you to check whether a value is null.
ShouldNotBeNull
returns the non-null value if it succeeds so that further assertions can be chained. When used with a reference type, the returned value is the same reference annotated as non-null. Equivalently, when used on a System.Nullable<T>
expression, the returned value is the unwrapped T
value.
var myRef = "Hello World";myRef.ShouldBeNull();
​snippet source | anchor
Exception
myRefshould be null but was"Hello World"
int? nullableValue = 42;nullableValue.ShouldBeNull();
​snippet source | anchor
Exception
nullableValueshould be null but was42
string? myRef = null;myRef.ShouldNotBeNull();
​snippet source | anchor
Exception
myRefshould not be null but was
int? myRef = null;myRef.ShouldNotBeNull();
​snippet source | anchor
Exception
myRefshould not be null but was
var myRef = (string?)"1234";myRef.ShouldNotBeNull().Length.ShouldBe(5);
​snippet source | anchor
Exception
myRef.ShouldNotBeNull().Lengthshould be5but was4
SomeStruct? nullableValue = new SomeStruct { IntProperty = 41 };nullableValue.ShouldNotBeNull().IntProperty.ShouldBe(42);
​snippet source | anchor
Exception
nullableValue.ShouldNotBeNull().IntPropertyshould be42but was41