Pure.Krome
Pure.Krome

Reputation: 86997

How can I return a Dictionary<string, string> as an IEnumerable<object> which XUnit's MemberData requires

I'm trying to use xunit's MemberDataAttribute to return a list of Key/Values.

For example, like this:

[Theory]
[MemberData("ValidCardData")]
public void GivenANumber_Constructor_CreatesANewInstance(NotSureWhatType data)
{
  ..
}

And this is how i'm trying to make the actuall data.

public static IEnumerable<object> ValidCardData
{
    get
    {
        var json = File.ReadAllText("Data\\ValidCards.json");
        var cardNumbers = JsonConvert.DeserializeObject<Dictionary<string, string[]>>(json);

        return cardNumbers
            .Select(x => new KeyValuePair<string, string[]>(x.Key, x.Value))
            .ToList()
            .Cast<IEnumerable<object>>();
    }
}

but it's not working:

System.InvalidCastExceptionUnable to cast object of type 'System.Collections.Generic.KeyValuePair2[System.String,System.String[]]' to type 'System.Collections.Generic.IEnumerable1[System.Object]'.

Upvotes: 1

Views: 419

Answers (1)

Oblivious Sage
Oblivious Sage

Reputation: 3405

You're trying to cast each key/value pair of the dictionary to an IEnumerable.

If cardNumbers is a Dictionary<string, string[]>, then you can just do this:

return cardNumbers.Cast<object>();

A dictionary is an IEnumerable<KeyValuePair> to begin with, so you just need to type them as objects.

Upvotes: 4

Related Questions