ShouldBe() is overly permissive in null propagation scenarios
blake-costar opened this issue · comments
When NULL propagates down to a property value via the propagation operator ?. shouldly seems to glibly agree to almost any assertion. I don't think the following test should pass:
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
//Act:
Person p = null;
//Assert:
p?.BirthDate.ShouldBe(DateTimeOffset.Now);
}
}
public class Person
{
public DateTimeOffset? BirthDate { get; set; }
}
The above code translates into:
[TestMethod]
public void TestMethod1()
{
//Act:
Person p = null;
//Assert:
if(p != null)
{
p.BirthDate.ShouldBe(DateTimeOffset.Now);
}
}
The code is not even reaching the assert statement. I'm not sure if it even would be possible to handle this scenario.
That's correct, we'd need to implement an analyzer package to detect and warn when mixing this usage with Shouldly assertions.
Bit late but i have just come across this and there seem to be a very simple fix for the problem:
Just wrap the null-propagated terms in round brackets:
(p?.BirthDate).ShouldBe(DateTimeOffster.Now);
Also consider p.ShouldNotBeNull().BirthDaty.ShouldBe(...);
Duplicate of #710.