DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Shallow and Deep Copies in JavaScript: What’s the Difference?
  • Commonly Occurring Errors in Microsoft Graph Integrations and How To Troubleshoot Them (Part 4)
  • Develop XR With Oracle Cloud, Database on HoloLens, Ep 2: Property Graphs, Data Visualization, and Metaverse
  • What Is Ant, Really?

Trending

  • Agile Estimation: Techniques and Tips for Success
  • Vector Database: A Beginner's Guide
  • Setting up Request Rate Limiting With NGINX Ingress
  • Breaking Down Silos: The Importance of Collaboration in Solution Architecture
  1. DZone
  2. Coding
  3. Languages
  4. Asserting Object Graph Equivalence Using Fluent Assertions 2.0

Asserting Object Graph Equivalence Using Fluent Assertions 2.0

Dennis Doomen user avatar by
Dennis Doomen
·
Sep. 03, 12 · Interview
Like (0)
Save
Tweet
Share
9.44K Views

Join the DZone community and get the full member experience.

Join For Free
As promised in the announcement about version 2.0, I will finally explain the details behind the new extension methods for asserting that two object graphs are equivalent. For the record, these new extension methods are going to supersede the old ShouldHave() method somewhere in a next major version. Internally the old methods are already using the new comparison engine, but new functionality will only be available through the new methods.

Selecting the right properties

Consider the class Order and its wire-transfer equivalent OrderDto (a so-called DTO). Suppose also that an order has one or more Products and an associated Customer. Coincidentally, the OrderDto will have one or more ProductDtos and a corresponding CustomerDto. Now if you want to make sure that all the properties of all the objects in the OrderDto object graph match the equally named properties of the Order object graph, you can do this.
orderDto.ShouldBeEquivalentTo(order);
In contrast to the ShouldHave() extension method, the comparison is recursive by default and all properties of the OrderDto must be available on the Order. If not, an exception is thrown. You can override this behavior in different ways. For instance, you may only want to include the properties both object graphs have:
orderDto.ShouldBeEquivalentTo(order, options =>
    options.ExcludingMissingProperties());
You can also exclude certain (potentially deeply nested) properties using the Excluding() method.
orderDto.ShouldBeEquivalentTo(order, options => 
    options.Excluding(o => o.Customer.Name));
Obviously, Excluding() and ExcludingMissingProperties() can be combined. Maybe farfetched, but you may even decide to exclude a property on a particular nested object by its index.
orderDto.ShouldBeEquivalentTo(order, options =>
    options.Excluding(o => o.Products[1].Status));
The Excluding() method on the options object also takes a lambda expression that offers a bit more flexibility for deciding what property to include.
orderDto.ShouldBeEquivalentTo(order, options => options
    .Excluding(ctx => ctx.PropertyPath == "Level.Level.Text"));
This expression has access to the property path, the property info and the subject’s run-time and compile-time type. You could also take a different approach and explicitly tell FA which properties to include.
orderDto.ShouldBeEquivalentTo(order, options => options
    .Including(o => o.OrderNumber)
    .Including(o => o.Date));

Overriding and collections

In addition to influencing the properties that are including in the comparison, you can also override the actual assertion operation that is executed on a particular property.
orderDto.ShouldBeEquivalentTo(order, options => options
    .Using<DateTime>(ctx => ctx.Date.Should().BeCloseTo(ctx.Date, 1000))
    .When(info => info.PropertyPath.EndsWith("Date")));
If you want to do this for all properties of a certain type, you can shorten the above call like this.
orderDto.ShouldBeEquivalentTo(order, options => options
    .Using<DateTime>(ctx => ctx.Date.Should().BeCloseTo(ctx.Date, 1000))
    .WhenTypeIs<DateTime>();
The original ShouldHave() extension method does support collections now, but it doesn’t allow you to influence the comparison based on the actual collection type. The new extension method ShouldAllBeEquivalentTo() does support that so you can now take the 2nd example from the post and apply it on a collection of OrderDtos.
orderDtos.ShouldAllBeEquivalentTo(orders, options =>   
    options.Excluding(o => o.Customer.Name));

Extensibility

Internally the comparison process consists of three phases.

  1. Select the properties of the subject object to include in the comparison.
  2. Find a matching property on the expectation object and decide what to do if it can’t find any.
  3. Select the appropriate assertion method for the property’s type and execute it.
Each of these phases is executed by one or more implementations of ISelectionRule, IMatchingRule and IAssertionRule that are maintained by the EquivalencyAssertionOptions. The ExcludePropertyByPredicateSelectionRule for example, is added to the collection of selection rules when you use the Excluding(property expression) method on the options parameter of ShouldBeEquivalentTo(). Even the Using().When() construct in the previous section is doing nothing more than inserting an AssertionRule<TSubject> in to the list of assertion rules. Creating your own rule is quite straightforward. 
  1. Choose the appropriate phase that the rule should influence
  2. Select the corresponding interface
  3. Create a class that implements this interface
  4. Add it to the ShouldBeEquivalentTo() call using the Using() method on the options parameters.
    subject.ShouldBeEquivalentTo(expected, options => options
        .Using(new ExcludeForeignKeysSelectionRule()))
That’s it for now. As usual, for questions, remarks or suggestions, you can use the Discussions page, StackOverflow, or you can contact me directly by email or Twitter.

Off topic: Although we’re still on CodePlex, the source code of Fluent Assertions is now stored in a Git repository. That should make it a whole lot easier for contributors to fork the code, write a nice improvement, and send us a pull request.
Object (computer science) Assertion (software development) Property (programming) Graph (Unix)

Opinions expressed by DZone contributors are their own.

Related

  • Shallow and Deep Copies in JavaScript: What’s the Difference?
  • Commonly Occurring Errors in Microsoft Graph Integrations and How To Troubleshoot Them (Part 4)
  • Develop XR With Oracle Cloud, Database on HoloLens, Ep 2: Property Graphs, Data Visualization, and Metaverse
  • What Is Ant, Really?

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: