0

I have the following code in a Unit Test:

        SomeModel test = new SomeModel();
        test.TestField = "Some Content Here"; //Where TestField is a String attribute of the SomeModel class

        var expected = Json(test, JsonRequestBehavior.AllowGet);

When I run

System.Diagnostics.Debug.WriteLine("Expected " + expected.Data.ToString());

I get this in the output: Expected Fake.Path.SomeModel

When I run the test through the debugger I am able to see the data: Debugger Result

How can I access the data through my unit test? I want to be able to verify that the data in it is correct through automated tests.

I am using Visual Studio 2012 Professional

Thanks!

4
  • 2
    The default ToString is just to show the type name, which is what you are seeing. If you want the message, it's going to be expected.Data.TestField Commented Jul 28, 2015 at 21:05
  • I get an error when I do that: 'Object' does not contain reference for 'TestField' Commented Jul 28, 2015 at 21:08
  • 1
    Then cast it. ((SomeModel)expected.Data).TestField) Commented Jul 28, 2015 at 21:09
  • @MattBurland Beautiful!!!! Works like a charm! Commented Jul 28, 2015 at 21:14

2 Answers 2

1

The default implementation (in Object) of ToString is to display the type name. That's what you are seeing when you do this:

expected.Data.ToString()

If you want to get at the actual TestField, and Data is defined as object, then you need:

((SomeModel)expected.Data).TestField
Sign up to request clarification or add additional context in comments.

Comments

0

I would download Newtonsoft's JSON library from NuGet if you haven't already. This is the code I used on one of my applications which used that libraries JObject class:

var parsed = JObject.Parse(jsonString);
JToken token;
if (parsed.TryGetValue("Key", out token))
{
    var value = token.ToString();
    ... //Do stuff
}

3 Comments

JObject.Parse only takes string arguments. Is there a way to parse the JsonResult?
myJsonResult.ToString() or maybe myJsonResult.Data.ToString() whichever returns the JSON formatted string containing the data.
See Matt's response in the original question. His solution worked perfectly for me!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.