Search code examples
c#jsonmstestrestsharpweb-api-testing

Asserting JSON JArray Api responses


When asserting JArray Json responses, I am getting the error Assert.AreEqual failed. Expected:<Newtonsoft.Json.Linq.JArray[,] Newtonsoft.Json.Linq.JArray[,])>. Actual:<[ 1, 3]

Can you please tell me where the error in the code is? I believe the issue is with the ResponseReceived class.


dynamic jsonResponse = JsonConvert.DeserializeObject(response.Content);
var responseTarget = jsonResponse.target;

//create a new response expected object
var responseExpected = new ResponseExpected();

//create a new post response received object
var responseReceived = new ResponseReceived();
responseReceived.Target = responseTarget;

  //Assert
Assert.AreEqual(responseExpected.Target, responseReceived.Target);


    public class ResponseReceived
    {
        public JArray Target{ get; set; }

    }

    public class ResponseExpected
    {
        public JArray[,] Target{ get; set; } = new JArray[1, 3];
    }
//post request json
var myObject = new { 
    target = new []{ 5, 5 } 
    }

UPDATE: The issue has been resolved using public JArray Target{ get; set; } = new JArray(new[] { 1, 3 });

However this seems to work with the majority of the test frameworks apart from MSTest. How would this be resolved with MSTest?


Solution

  • You can't expect that single JArray will be equal to array of JArray Assuming your json looks similar to

    {
      "target": [
        5,
        5
      ]
    }
    

    You can write asserion like:

    var input = "{\r\n  \"target\": [\r\n    5,\r\n    5\r\n  ]\r\n}";
    dynamic json = JsonConvert.DeserializeObject(input);
    
    var expected = new JArray(new[] {1, 3}); // not "new JArray[1, 3];"
    var actual = json.target;
    
    Assert.AreEqual(expected, actual);