0

Using MSTest, when I try to run a test that has a type of dynamic that is a container of a JSON object (from an API Query) I am ment to be able to dereference the JSON elements in the commented out be below, but it fails, where as treating it as an item collection it seems ok. If inspect '(jsonResponse.message)' it has a value of "Hi" - but it wont work in a Unit Test. Why is that?

// http://www.newtonsoft.com/json/help/html/LINQtoJSON.htm // Deserialize json object into dynamic object using Json.net

[TestMethod]
public void DynamicDeserialization()
{
    dynamic jsonResponse = JsonConvert.DeserializeObject("{\"message\":\"Hi\"}");
    JObject  d = JObject.Parse("{\"message\":\"Hi\"}");
    Assert.IsTrue((string)d["message"]  == "Hi");          // Is ok
// Assert.IsTrue(jsonResponse.message.ToString() == "Hi"); // is not ok
}    
Community
  • 1
  • 1
  • 1
    Define "won't work" -- are you getting an exception? If so, what does the exception message say? If not, what behavior are you observing, and how does that differ from what you expected to happen? – Brian Rogers Sep 26 '16 at 17:18
  • Uncommented last line, ran the code and test worked/passed. What is the problem. if you look at `jsonResponse` while debugging you will see that it is a `JObject` as well wrapped as `dynamic`. – Nkosi Sep 30 '16 at 01:07

1 Answers1

0

Uncommented last line, ran the code and test worked/passed. If you look at jsonResponse while debugging you will see that it is a JObject as well wrapped as dynamic.

In fact if I convert d to dynamic I can perform the same assertion and it passes as well.

[TestMethod]
public void DynamicDeserialization() {
    var json = "{\"message\":\"Hi\"}";
    dynamic jsonResponse = JsonConvert.DeserializeObject(json);
    dynamic d = JObject.Parse(json);
    Assert.IsTrue(d.message.ToString() == "Hi");
    Assert.IsTrue(jsonResponse.message.ToString() == "Hi");
}

You may need to check to make sure you are using the latest version of Json.Net

Nkosi
  • 235,767
  • 35
  • 427
  • 472