views:

361

answers:

4

I am writing an unit test for a mvc web application that checks if a returned list of anonymous variables(in a jsonresult) is correct. therefore i need to iterate through that list but i cannot seem to find a way to do so.

so i have 2 methods

1) returns a json result . In that json result there is a property called data. that property is of type object but internally it's a list of anonymous variables

2) the method calls method 1 and checks if the returned jsonresult is ok.

if i run the test and i break the debugger i can hover over the result and see the items in it. i just don't find a way to do so in code.(just using a foreach isn't possible because at the point i need it i'm not in the method that created the anonymous method)

+1  A: 

I think you mean "anonymous type" everywhere you've said "anonymous variable" - but you can still iterate over the list with foreach, just declaring the iteration variable as type object:

foreach (object o in myList)
{
    // Not sure what you're actually trying to do in here...
}

If you need to check the contents, you can use the fact that anonymous types override ToString in a useful way. Your test can check the result of projecting each element to a string. Indeed, you could convert your result object to a sequence of strings quite easily:

var strings = ((IEnumerable) result).Cast<object>.Select(x => x.ToString());

Then test strings possibly using SequenceEqual.

Jon Skeet
A: 

thanks for your reply.

I meant anonymous type as you say. i can't use foreach because the variable myList is of type object at that moment. i cannot cast it to list or Enumerable or collection or anything of that kind

Just so you know, you can edit your post (there should be an "edit" link just below the tags) and update your misnomer. That should help people to answer your question better.
Coderer
A: 

Create an identical set of objects to the one you expect, then serialize both it and the result.Data of the action under unit test. Finally, compare the streams to see if they are identical.

Craig Stuntz
A: 

ok i found it thx to a part of your solution:) apparently i can convert it to IEnumerable and then i can iterate through the results. thx!

    var objects= ((IEnumerable)result.Data);
    foreach (object obj in objects)
    {
       //inhere i can use reflection to get the properties out of it
    }