gpt4 book ai didi

c# - 在 c# Specflow 中断言 Json 输出

转载 作者:太空宇宙 更新时间:2023-11-03 12:32:30 28 4
gpt4 key购买 nike

我正在 specflow 中编写测试以验证 API 获取输出

验证代码是

 [Then(@"the customer details will be returned")]
public void ThenTheCustomerDetailsWillBeReturned ()
{
var actualResponse = ScenarioContextWrapper.Response;
JObject jsonResult = new JObject();
jsonResult = JObject.Parse(actualResponse);
Assert.AreEqual("ABC008", jsonResult.GetType().GetProperty("CustomerCode").GetValue(jsonResult, null));
Assert.AreEqual("ABC Industry", jsonResult.GetType().GetProperty("CustomerName").GetValue(jsonResult, null));

}

但我收到异常“{“无法对空引用执行运行时绑定(bind)”}”。

API 的输出是

              {{
"Pagination": {
"NumberOfItems": 1,
"PageSize": 200,
"PageNumber": 1,
"NumberOfPages": 1
},
"Items": [
{
"Addresses": [],
"CustomerCode": "ABC008",
"CustomerName": "ABC Industry",
"GSTVATNumber": null,
"BankName": null,
"BankBranch": null,
"BankAccount": null,
"Website": null,
"PhoneNumber": null,
"FaxNumber": null,
"MobileNumber": null,
"DDINumber": null,
"TollFreeNumber": null,
"Email": null,
"EmailCC": null,
"Currency": {
"CurrencyCode": "NZD",
"Description": "New Zealand, Dollars",
"Guid": "29252c92-3d0e-4eba-a613-f9c6c22ed3a8",
"LastModifiedOn": "2017-01-31T20:22:20.816Z"
},
"Notes": null,
"Taxable": true,
"XeroContactId": null,
"SalesPerson": null,
"DiscountRate": null,
"PrintPackingSlipInsteadOfInvoice": null,
"PrintInvoice": null,
"StopCredit": false,
"Obsolete": false,
"XeroSalesAccount": null,
"XeroCostOfGoodsAccount": null,
"SellPriceTier": "",
"SellPriceTierReference": null,
"CustomerType": "",
"PaymentTerm": "",
"ContactFirstName": null,
"ContactLastName": null,
"SourceId": null,
"CreatedBy": "qa+applicant@tyt.com",
"CreatedOn": "2017-02-05T18:50:53.697Z",
"Guid": "15145a60-8688-48a5-b849-ab66da3c0288",
"LastModifiedOn": "2017-02-05T18:50:53.697Z"
}
]
}}

有人可以帮忙断言客户代码吗

谢谢

最佳答案

我使用了一个简短的 JSON 作为示例,因为您问题中的原始格式不完整:

        string actualResponse = "{\"Items\":[{\"CustomerCode\": \"ABC008\", \"TestBla\":\"Bla\"}]}";
JObject jsonResult = JObject.Parse(actualResponse);

// Get Null exception. Property does not exist.
//Object value = jsonResult.GetType().GetProperty("Items").GetValue(jsonResult, null);

// Will work
var items = jsonResult["Items"];

// To assert CustomerCode:
string value = jsonResult["Items"][0]["CustomerCode"].Value<string>();
Assert.AreEqual("ABC008", value);

GetProperty 获取类属性。在您的例子中,类是 JObject

如果您将对象转换为您自己的类(比方说 Result),那么您可以使用它自己的属性(比方说 Item):

    Result result = jsonResult.ToObject<Result>();
var items = result.Items

关于c# - 在 c# Specflow 中断言 Json 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42185234/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com