Earlier this week, I wrote about how to create and populate objects from tables created in your SpecFlow scenarios. If the only reason you’re populating an object is to do a comparison, there’s an easier way: the CompareToInstance<T> method.
Similar to the previously discussed method, CreateInstance<T>, an object will be created using the properties contained in a table of values. The object properties will be matched ignoring case and whitespace. CompareToInstance allows you to provide an instance of the same type and does a property-by-property comparison. If any of the property values are different, a TechTalk.SpecFlow.Assist.ComparisonException is thrown with a message containing all differences that were found.
Here’s an example!
Scenario: Update a person name Given I have an existing person And I change the name to the following | first | middle | last | | Ftest | Mtest | Ltest | When I save the person And I retrieve person Then the name was changed to the following | first | middle | last | | Ftest | Mtest | Ltest |
// don't forget! // using TechTalk.SpecFlow.Assist; [Given(@"I change the name to the following")] public void GivenIChangeTheNameToTheFollowing(Table table) { var p = ScenarioContext.Current.Get<Person>(); p.Name = table.CreateInstance<NameType>(); } [Then(@"the name was changed to the following")] public void ThenTheNameWasChangedToTheFollowing(Table table) { var p = ScenarioContext.Current.Get<Person>(); table.CompareToInstance<NameType>(p.Name); }
One thought on “Compare Objects from Tables in SpecFlow”