Skip to content

Instantly share code, notes, and snippets.

@LockTar
Created September 11, 2015 15:09
Show Gist options
  • Save LockTar/294161a60957e7d43c2e to your computer and use it in GitHub Desktop.
Save LockTar/294161a60957e7d43c2e to your computer and use it in GitHub Desktop.
A JSON extraction rule for Visual Studio webtest that extracts a value from a JSON response
using Microsoft.VisualStudio.TestTools.WebTesting;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.ComponentModel;
namespace Extensions.ExtractionRules
{
/// <summary>
/// A JSON extraction rule for Visual Studio webtest that extracts a value from a JSON response.
/// </summary>
[DisplayName("JSON Property Extraction Rule")]
[Description("Extracts the value from a JSON property out of the response")]
public class JsonPropertyExtractionRule : ExtractionRule
{
/// <summary>
/// The name of the JSON property to extract from the JSON result.
/// </summary>
[DisplayName("Property name")]
[Description("The name of the JSON property to extract from the JSON result")]
public string JSonPropertyName { get; set; }
/// <summary>
/// Extract a JSON value from the response.
/// </summary>
public override void Extract(object sender, ExtractionEventArgs e)
{
var jsonBody = JsonConvert.DeserializeObject(e.Response.BodyString);
var o = JObject.FromObject(jsonBody);
string value = (string)o.SelectToken(JSonPropertyName);
if (!string.IsNullOrWhiteSpace(value))
{
e.WebTest.Context.Add(ContextParameterName, value);
e.Message = $"Property '{JSonPropertyName}' has the value '{value}'";
e.Success = true;
}
else
{
e.Message = $"Property '{JSonPropertyName}' not found in response";
e.Success = false;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment