简体   繁体   中英

How to iterate through multiple child nodes with same name in a json response using C# and assert right content

I am getting below response from a webservice . I want to write a test for this using specflow , and C# Nunit framework

{
   "status": "Healthy",
   "results":    [
            {
              "name": "Microservice one",
              "status": "Healthy",
              "description": "Url check MSOneURI success : status(OK)"
            },
            {
              "name": "Microservice two",
              "status": "Healthy",
              "description": "Url check MSTwoURI success : status(OK)"
            },
            {
              "name": "Microservice three",
              "status": "Healthy",
              "description": "Url check MSThreeURI success : status(OK)"
              },
            {
              "name": "Microservice four",
              "status": "Healthy",
              "description": "Url check MSFourURI success : status(OK)"
              },
            {
              "name": "Microservice five",
              "status": "Healthy",
              "description": "Url check MSFiveURI success : status(OK)"
              }
                ]

}

This is how my feature file looks

@uService
Feature: Micro Service - health check
In order to perform health check 
As a service
I want to ensure downstream Micro Services are healthy 

Scenario Outline: [uService] Status of downstream microservices are healthy
Given health check micro service
When health check is performed      
Then <nameoftheservice> service returns correct description and status


Examples: 
| downstreamservice   | 
| Microservice one    | 
| Microservice two    | 
| Microservice three  | 
| Microservice four   | 
| Microservice five   | 

I need help with writing the binding method for the Then step

You could deserialize the JSON with the Newtonsoft.JSON package then iterate over the list of services with LINQ in order to do the comparison.

Something like:

class MicroserviceStatus {
   public string Name { get; set; }
   public string Status { get; set; }
   public string Description { get; set; }
}

class MicroserviceHealthCheck {
   public string Status { get; set; }
   public List<MicroserviceStatus> MicroserviceStatuses { get; set; }
}

var microserviceHealthCheck = JsonConvert.DeserializeObject<MicroserviceHealthCheck>(json);

bool anyNotHealthy = microserviceHealthCheck.MicroserviceStatuses.Any(i => i.Status != "Healthy");

I wrote this straight into the editor so it may not be exactly correct, and you should already have the types available for the deserialization already, but hopefully this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM