YMM
YMM

Reputation: 702

Asserting that a collection is ordered by specific properties passed to test method as parameters

I have a parameterized test with the following property names passed to it:

[TestCase("customerId")]
[TestCase("connectionType")]
public void CanSearchClientsOrderedByProperties(string property)

I cannot figure out how to pass the property name in the assertion expression below:

searchResponse.Items.Should().BeInAscendingOrder(i => i.{How to use property name here?});

Upvotes: 0

Views: 34

Answers (1)

Michał Turczyn
Michał Turczyn

Reputation: 37337

This is just proof of concept, how it could be done.

It requires more details on how to dynamically assign the type of a field etc., but the mian idea of getting lambda expression for fluent assertion is there:

[Test]
public void Test1()
{
    var items = Enumerable.Range(0, 10)
        .Select(i => new ExampleClass
        {
            I1 = i,
            I2 = 10 - i,
        }).ToArray();

    var propName = nameof(ExampleClass.I1);
    var type = typeof(ExampleClass);
    var x = Expression.Parameter(type, "x");
    var body = Expression.PropertyOrField(x, propName);
    var lambda = Expression.Lambda<Func<ExampleClass, int>>(body, x);

    items.Should().BeInAscendingOrder(lambda);
}

Upvotes: 0

Related Questions