mercredi 3 juin 2015

How can I cast/convert an anonymous type from HttpResponseMessage for unit testing?

I have been tasked with writing a unit test for the following Web API 2 action:

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 that works fine, but I have not been able to figure out how I can extract the content data and test it. Here's my test so far:

[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 inspect responseContent in the immediate window, I see this (I have mocked/stubbed in a single fake value for testing):

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

I can cast this as an array of object, but if I try and extract the 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?)

Similarly, if I try to cast and project to an anonymous type of the same shape, it will not 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 I can probably achieve what I want to do 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'm missing something fundamental, here. How can I cast/convert an anonymous type from HttpResponseMessage for unit testing?

Aucun commentaire:

Enregistrer un commentaire