Specflow读取Json响应

问题描述 投票:1回答:2

需要测试将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);
    }

如何解析这个? enter image description here

automated-tests cucumber specflow gherkin
2个回答
0
投票

改善这种情况的一种方法是不在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);
}

0
投票

简而言之:You're Cuking It Wrong

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

Scenario: Retriving a list of platforms
    Given I am an authorized user
    When I retrieve a list of hotel platforms
    Then I should receive the following hotel platforms:
        | Platform |
        | Mobile   |
        | Desktop  |

步骤:当我检索酒店平台列表时

此步骤应使用C#代码生成GET请求。在Scenario上下文中保存该GET请求的响应。

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

做一个简单的断言,并省略像“Ref Id”这样的技术信息。平台名称是您真正关心的。

这些步骤的粗略开端是:

using TechTalk.SpecFlow;
using TechTalk.SpecFlow.Assist;

[Binding]
public class PlatformSteps
{
    private readonly ScenarioContext scenario;

    public PlatformSteps(ScenarioContext scenario)
    {
        this.scenario = scenario;
    }

    [When(@"^When I retrieve a list of hotel platforms")]
    public void WhenIRetrieveAListOfHotelPlatforms()
    {
        var response = api.GetHotelPlatforms(); // Or whatever you API call looks like

        scenario["HotelPlatformsResponse"] = response;
    }

    [Then(@"^I should receive the following hotel platforms:")]
    public void IShouldReceiveTheFollowingHotelPlatforms(Table table)
    {
        var response = (IEnumerable<SomeJsonResponseType>)scenario["HotelPlatformsResponse"];
        var actualPlatforms = response.Select(r => r.PlatformName);

        table.CompareToSet(actualPlatforms);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.