How to assert that all selected properties are set (not null or empty)

Viewed 15501

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.

4 Answers

try this:

 var mySelectedProperties = new string[] { "Description", "Id", "other" };
 Assert.IsTrue(mapped.GetType().GetProperties().ToList().
            Where(p => mySelectedProperties.Contains(p.Name)).
            Where(p => p.GetValue(mapped) == null).
            Count() == 0);
Related