Skip to content

Compare table to dynamic instance

Jezusfan edited this page Sep 4, 2017 · 10 revisions

You can compare a dynamic instance to a table with the CompareToDynamicInstance extension method. This is useful and very common.

Consider the following scenario:

Scenario: Matching a dynamic instance against a table
    Given I create a dynamic instance from this table
        | Name   | Age | Birth date | Length in meters |
        | Marcus | 39  | 1972-10-09 | 1.96             |
    When I compare it to this table
        | Name   | Age | Birth date | Length in meters |
        | Marcus | 39  | 1972-10-09 | 1.96             |
    Then no instance comparison exception should have been thrown

And then comparing it using the following step definitions:

private dynamic _instance; // hold states between steps
private DynamicInstanceComparisonException _exception; // hold any exceptions thrown

[Given(@"I create a dynamic instance from this table")]
public void CreateDynamicInstanceFromTable(Table table)
{
    _instance = table.CreateDynamicInstance();
}

[When("I compare it to this table")]
public void ComparingAgainstDynamicInstance(Table table)
{
    try
    {
        // COMPARISION DONE HERE
        table.CompareToDynamicInstance((object)_instance);
    }
    catch (DynamicInstanceComparisonException ex)
    {
        _exception = ex;
    }
}

[Then("no instance comparison exception should have been thrown")]
public void NoException()
{
    _exception.Should().Be.Null();
}  

Please note that an cast to object is made for the comparison. This has to do with the fact that extension methods and dynamic parameters doesn't play nice together.

Clone this wiki locally