I want to verify (assert) that certain properties on my DTO object are set. I was trying to do it with Fluent Assertions, but the following code does not seem to work:
mapped.ShouldHave().Properties(
    x => x.Description,
    ...more
    x => x.Id)
    .Should().NotBeNull(); 
Is it possible to achieve that with Fluent Assertions, or other tool ? Fluent assertions have ShouldBeEquivalentTo, but actually I only care whether those are not nulls/empties, so that one I was not able to utilize.
Of course I can just do an Assert on each property level, but interested in some more elegant way.
                        
Indeed,
Propertiesmethod returnsPropertiesAssertion, which only haveEqualTomethod for equality comparison. NoNotEqualTomethod orNotNull. In your test, your expectedPropertiesAssertionnot to benull, that's why it will always pass.You can implement a
AssertionHelperstatic class and pass an array ofFuncs, which you would use to validate an object. This is very naive implementation and you won't get nice error reporting, but I'm just showing the general ideaNow this test would fail with
some of the properties are nullmessageTwo problems with that solution:
Idproperty is of a value type,getter(objectToInspect) == nullis alwaysfalseTo address the first point, you can:
CheckAllPropertiesAreNotNull, each will have different number of GenericFunc<TInput, TFirstOutput> firstGetter, then you would compare return value of each getter to correspondingdefault(TFirstOutput)Activator, to create default instance and callEqualsI'll show you the second case. You can create a
IsDefaultmethod, which would accept parameter of typeobject(note, that this could be a boxed int):Now our overall code, that handler value types will look like:
To address the second point, you can pass an
Expression<Func<T, object>>[] getters, which will contain information about a called Property. Create a methodGetName, which would acceptExpression<Func<T, object>>and return the called property nameNow the resulting code would look like:
Now for my call
I get
error message. In my Dto
Descriptionis astringandIdis a value typeint. If I set that properties to some non-default values, I'll get no error and test will pass.