How can I convert the anonymous type from HttpResponseMessage for unit testing?

I was tasked with writing a unit test for the following Web API 2 activity:

public HttpResponseMessage Get()
{
    IEnumerable<KeyValuePair<long, string>> things = _service.GetSomething();
    return ActionContext.Request.CreateResponse(things.Select(x => new 
        { 
            Thing1 = x.Prop1.ToString(), 
            Thing2 = x.Prop2 
        }).ToArray());
}

      

I am testing the status code and it works fine, but I have not been able to figure out how I can retrieve the content data and test it. Here's my test:

[TestMethod]
public void GetReturnsOkAndExpectedType()
{
    var controller = GetTheController();
    var response = controller.Get();
    Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
    dynamic responseContent;
    Assert.IsTrue(response.TryGetContentValue(out responseContent));
    //???? How can I cast/convert responseContent here ????
}

      

If I debug the test and check responseContent

in the immediate window I see this (I mocked / shaded in one fake value for testing):

{<>f__AnonymousType1<string, string>[1]}
    [0]: { Thing1 = "123", Thing2 = "unit test" }

      

I can use this as an array of an object, but if I try to extract values ​​by their property names, I get an error (immediate window again):

((object[])responseContent)[0].Thing1
'object' does not contain a definition for 'Thing1' and no extension method 'Thing1' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

      

Likewise, if I try to use and project an anonymous type of the same form, it won't compile:

//Thing1 and Thing2 get red-lined here as 'cannot resolve symbol'
var castResult = ((object[]) responseContent).ToList().Select(x => new {x.Thing1, x.Thing2});  

      

I know that I can probably achieve what I want if I serialize / deserialize everything using something like JsonConvert

, but that doesn't seem like the "right" way to do it. I feel like I am missing something fundamental. How can I convert the anonymous type from HttpResponseMessage

for unit testing?

+3


source to share


1 answer


As @Daniel JG said in the comments above, one option would be to use reflection to retrieve the values ​​of your properties. Since you appear to be using an MS testing framework, another alternative is to use the PrivateObject class to do some of the reflection work.

So, you can do something like this in your test:



var poContent = ((object[])responseContent).Select(x => new PrivateObject(x)).ToArray();

Assert.AreEqual("123", poContent[0].GetProperty("Thing1"));
Assert.AreEqual("unit test", poContent[0].GetProperty("Thing2"));

      

+1


source







All Articles