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,
Properties
method returnsPropertiesAssertion
, which only haveEqualTo
method for equality comparison. NoNotEqualTo
method orNotNull
. In your test, your expectedPropertiesAssertion
not to benull
, that's why it will always pass.You can implement a
AssertionHelper
static class and pass an array ofFunc
s, 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 null
messageTwo problems with that solution:
Id
property is of a value type,getter(objectToInspect) == null
is alwaysfalse
To 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 callEquals
I'll show you the second case. You can create a
IsDefault
method, 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
Description
is astring
andId
is a value typeint
. If I set that properties to some non-default values, I'll get no error and test will pass.