Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Test to verify content of IEnumerable<dynamic>

Given the following WebAPI method:

public IHttpActionResult GetDeliveryTypes()
{
    return Ok(... .Select(dt => new { Id = dt.Id, Name = dt.Name }));
}

Where

typeof(Id) = long  
typeof(Name) = string

While unit testing, how can I

  1. Assert that the content is as I expect it? For example, the following assertion fails

    var contentResult = response as OkNegotiatedContentResult<IEnumerable<dynamic>>;
    Assert.IsNotNull(contentResult);
    
  2. Reduce this IEnumerable<dynamic> result to an IEnumerable<long> so I can verify that it contains the expected sequence of values?

I have already added the InternalsVisibleTo attribute to the AssemblyInfo.

like image 720
awj Avatar asked Oct 19 '22 06:10

awj


1 Answers

1. Something to start with:

response.GetType().GetGenericTypeDefinition() == typeof(OkNegotiatedContentResult<>)

You can continue type investigation from here if you want.

2. The solution for second point is pretty easy:

dynamic response = controller.GetDeliveryTypes();
Assert.True(response.GetType().GetGenericTypeDefinition() == typeof(OkNegotiatedContentResult<>));
var content = (IEnumerable<dynamic>)response.Content;
var ids = content.Select(i => i.Id).ToList();

If the tests are in separate assembly - add [assembly: InternalsVisibleTo("TestAssembly")] as anonymous types are generated as internal.

like image 167
Aleksey L. Avatar answered Nov 04 '22 20:11

Aleksey L.