Search code examples
c#apiautomationrestsharpxunit

How to parse json file data as request parameter in RestSharp?


I am using RestSharp along with C# Xnuit to automate API testing.

Currently i am creating string for request parameters as below.

string jsonString = @"{""customerName"": ""George Smith"", ""date"": ""2019-12-04""}";
var restRequest = restAPI.CreatePostRequest(jsonString);

Now instead of this i want create separate testdata.json file to add request parameters and use that file to create request. How to do so?


Solution

  • I would suggest that you create a folder that is supposed to hold test data and then retrieve the file and read it into a string.

    The LocateScriptsFolder starts at the AppDomain.CurrentDomain.BaseDirectory and keeps walking up the path until it locates the script folder.

        public static DirectoryInfo LocateScriptsFolder(string baseDir)
        {
            var parent = Directory.GetParent(baseDir);
            if (parent.GetDirectories("DataFolder").Any())
            {
                return parent.GetDirectories("DataFolder").First();
            }
            return LocateScriptsFolder(parent.FullName);
        }
        var baseDir = AppDomain.CurrentDomain.BaseDirectory;
        var scripts = LocateScriptsFolder(baseDir);
        scripts.GetFiles("*.json").First();
        var json = File.ReadAllText(script.FullName);