在我的API测试中,我正在使用Jcontainer将响应转换为Json。例如:
[Test]
public void GetUsersList()
{
var response = us.UserList();
JContainer jsonresponse = rh.ConvertResponseToJson(response);
}
我正在尝试针对Json进行以下验证验证是否存在所有密钥(如果json中的所有密钥都存在,例如id,时间戳,类型等。)这是我的json
[
{
"id": "aa0db615-d4cb-4466-bc23-0e0083002330",
"timestamp": "2020-02-11T19:00:00-05:00",
"type": 33554432,
"info": "Full Synchronization request for all endpoints",
"schedule": "once",
"lastRun": null,
"flags": 6,
"creator": null,
"isEditable": true,
"location": 0,
"duration": null
},
{
"id": "70baa28c-e270-447b-b88a-20d30a9542db",
"timestamp": "2020-02-11T19:00:00-05:00",
"type": 33554432,
"info": "Full Synchronization request for all endpoints",
"schedule": "once",
"lastRun": null,
"flags": 6,
"creator": null,
"isEditable": true,
"location": 0,
"duration": null
}
]
这是我转换后的回复给Json供参考
public JContainer ConvertResponseToJson(HttpWebResponse response)
{
string localString;
if (response.ContentEncoding.Contains("application/xml"))
{
// Convert the escaped Stream into an XML document.
ConfigXmlDocument xmlDocument = new ConfigXmlDocument();
xmlDocument.LoadXml(ConvertResponseStreamToString(response));
// Now convert the properly-escaped JSON for the response into a JContainer
localString = JsonConvert.SerializeXmlNode(xmlDocument);
}
else
localString = ConvertResponseStreamToString(response);
return JToken.Parse(localString) as JContainer;
}
目前,我创建了一个Json模型以通过数组索引读取它。但是我正在进行多种资产验证所有密钥。我只想遍历它们。这是我到目前为止的内容
var response = us.UserList();
JContainer jsonresponse = rh.ConvertResponseToJson(response);
var castedModel = Jsonresponse.ToObject<IList<Model>>();
Assert.IsNotNull(castedModel[0].info); //This is repeated I am trying to avoid this
Assert.IsNotNull(castedModel[0].task);
Assert.IsNotNull(castedModel[0].timestamp)
您可以只使用一个for循环。
var castedModel = Jsonresponse.ToObject<IList<Model>>();
for(int i = 0; i < castedModel.Count; i++)
{
Assert.IsNotNull(castedModel[i].info);
Assert.IsNotNull(castedModel[i].task);
Assert.IsNotNull(castedModel[i].timestamp)
{