Automated tests Specflow读取Json响应

Automated tests Specflow读取Json响应,automated-tests,cucumber,specflow,gherkin,Automated Tests,Cucumber,Specflow,Gherkin,需要测试以Json作为响应的GET。我在官方文件中没有找到有用的信息 Feature: API_Retrieving_Platforms As an authorized user... @mytag Scenario: Perform Get request Given I am an authorized user When I perform GET request "/api/hotels/lists/platforms", Then I receive

需要测试以Json作为响应的GET。我在官方文件中没有找到有用的信息

Feature: API_Retrieving_Platforms
    As an authorized user...
 @mytag
Scenario: Perform Get request
    Given I am an authorized user
    When I perform GET request "/api/hotels/lists/platforms",
    Then I receive a JSON in response:
    """
    [
        {
            "refId": 1,
            "label": "Mobile"
        },
        {
            "refId": 2,
            "label": "Desktop"
        }
    ]
    """
检索Json的步骤是:

[Then(@"I receive a JSON in response:")]
    public void ThenIReceiveAJSONInResponse(string JSON)
    {
        Assert.Equal(HttpStatusCode.OK, _responseMessage.StatusCode);
    }
如何解析这个?

改进这一点的一种方法是不在Specflow步骤中使用确切的JSON。 我建议使用类似的方法

Then I receive a response that looks like 'myResponsefile.json'
然后,您可以创建一个步骤来处理响应,并查看repo中的一个文件以与之进行比较

[Then(@"I receive a response that looks like '(.*)'")]
public void IreceiveAJsonResponse(string responsefilenametocompare)
{
        string receivedjson = GetMyReceivedjsonObject();
        string filePathAndName = "myfile.json";
        string json = File.ReadAllText(filePathAndName); 

        JToken expected = JToken.Parse(json);
        JToken actual = JToken.Parse(receivedjson);

        actual.Should().BeEquivalentTo(expected);
}
简而言之:

较长的答案是,您需要以不同的方式编写步骤,以便从中删除技术术语,并专注于业务价值

场景:检索平台列表
假设我是授权用户
当我检索酒店站台列表时
然后我将收到以下酒店平台:
|平台|
|流动的|
|桌面|
步骤:检索酒店平台列表时

此步骤应以C#代码发出GET请求。在场景上下文中保存该GET请求的响应

步骤:然后我将收到以下酒店平台:

做出一个简单的断言,并省略诸如“Ref Id”之类的技术信息。平台名称是您真正关心的

这些步骤的粗略开始是:

使用TechTalk.SpecFlow;
使用TechTalk.SpecFlow.Assist;
[有约束力]
公共类平台步骤
{
私有只读场景上下文场景;
/// 
///获取或设置场景上下文中的酒店平台
/// 
私人IEnumerable酒店
{
get=>(IEnumerable)场景[“HotelPlatformsResponse”];
设置=>场景[“HotelPlatformsResponse”]=值;
}
公共平台步骤(场景上下文场景)
{
this.scenario=scenario;
}
[当(@“^当我检索酒店平台列表时”)]
酒店平台()的注册时的公共无效
{
HotelPlatforms=api.GetHotelPlatforms();//或api调用的任何内容
}
[然后(@“^我将收到以下酒店平台:”)]
公共空间应包括以下酒店平台(表)
{
var actualPlatforms=HotelPlatforms.Select(r=>r.PlatformName);
表.比较集(实际平台);
}
}

这并不是小黄瓜的真正用途。老实说,我只会用C语言编写这些测试,而忘记了小黄瓜语言。