断言JArray Json响应时,出现错误Assert.AreEqual failed. Expected:<Newtonsoft.Json.Linq.JArray[,] Newtonsoft.Json.Linq.JArray[,])>. Actual:<[ 1, 3]

您能告诉我代码中的错误在哪里吗?我认为问题出在ResponseReceived类。


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 }
    }



更新:问题已使用public JArray Target{ get; set; } = new JArray(new[] { 1, 3 });解决

但是,这似乎适用于除MSTest之外的大多数测试框架。 MSTest将如何解决?

最佳答案

您不能期望单个JArray等于JArray数组
假设您的json看起来类似于

{
  "target": [
    5,
    5
  ]
}


您可以像这样编写asserion:

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);

09-30 18:53