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

2

5

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?

Broomfield answered 18/8, 2014 at 15:4 Comment(3)
I don't think the chaining works if you try to use a property. IOW the method-chaining technique requires methods.Nelson
@DavidTansey But they are performing chaining with the And property.Broomfield
Chaining merely requires that an object is returned. You can chain using methods or properties.Cofer
C
11

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.

Cofer answered 18/8, 2014 at 15:8 Comment(0)
O
3

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.

Officialism answered 18/8, 2014 at 15:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.