Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In FluentAssertions, why is Should a method instead of a property?

In FluentAssertions, you can make various claims in various formats.

x.Should().BeEquivalentTo(y);
x.ShouldBeEquivalentTo(y);

are both valid assertions.

Why is Should a method and not a property? I haven't seen any examples in which Should takes a parameter, so it seems to me like it could have easily been a property.

You can also assert that

x.Should().NotBeNull().And.BeEquivalentTo(y);

Here, And is a property instead of a method. Shouldn't And and Should each be the same type of element (methods/properties)?

TL;DR Was there a valid reason behind the design choice to make Should a method in FluentAssertions instead of a property?

like image 306
Luke Willis Avatar asked Aug 18 '14 15:08

Luke Willis


2 Answers

Should() is an extension method being added onto the class of x. You can only add extension methods -- C# doesn't have extension properties.

And is a property on whatever class NotBeNull() returns. There we have control over the class, and can add real properties to it.

like image 189
James Curran Avatar answered Oct 19 '22 21:10

James Curran


Should() is a method because of the limitations of the C# language. It's an extension method; a method that is defined in the FluentAssertions library to be available to call on any type (hence x.Should()) - even though the original code for the class doesn't implement the method.

You can't implement extension properties, so Should has to be a method.

That method returns an object defined within FluentAssertions, as does NotBeNull(), and so these objects can include properties where it's relevant/useful/meaningful to do so.

In short: the valid reason is that it's the only choice available.

like image 3
Dan Puzey Avatar answered Oct 19 '22 21:10

Dan Puzey