Search code examples
c#unit-testingserializationwcf-web-api

C# Wcf Web API Deserializing Response


I am trying to unit test a web service that returns a non primitive. The response can be either xml or json depending on the request. In my test it'd be great if I could deserialize the content body to one of my objects. Here's some code:

    [WebGet(UriTemplate = "{arg1}/{arg2}")]
    public HttpResponseMessage<MyType> GetSomethingCool(string arg1, long arg2)
    {    
         return new HttpResonseMessage<MyTpe>(new MyType());
    }

    public class MyType
    {
         public string Property1 { get; set; }
         public long Property2 { get; set; }
         public string Property3 { get; set; }
    }

And my test:

    [Test]
    public void MyTestForTheWebService_ReturnsText()
    {
          Service1 service = new  Service1 (_mockRepository.Object);
          HttpResponseMessage<MyType> result = service.GetSomethingCool("Something", **);

          Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);

          MyType resultContent = result.Content.ReadAs<MyType>(); // doesn't work
          Assert.AreEqual("expected value", resultContent .Property1);
          .....

So basically I need to be able to turn result.Content to a MyType and don't know how. Thanks


Solution

  • Try doing:

    MyType resultContent = (MyType)result.Content.ReadAs();
    

    I believe you are running into a known bug.