Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save felickz/302db809034b039f8f342a035ae8aab8 to your computer and use it in GitHub Desktop.
Save felickz/302db809034b039f8f342a035ae8aab8 to your computer and use it in GitHub Desktop.
An RFC 6901 JSON Pointer 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;
using Tavis;
namespace Extensions.ExtractionRules
{
/// <summary>
/// A JSON extraction rule for Visual Studio webtest that extracts a value from a JSON response using RFC 6901 JSON Pointer.
/// </summary>
[DisplayName("JSON Pointer Property Extraction Rule")]
[Description("Extracts the value from an RFC 6901 JSON pointer out of the response")]
public class JsonPointerPropertyExtractionRule : ExtractionRule
{
/// <summary>
/// The name of the JSON pointer to extract from the JSON result.
/// </summary>
[DisplayName("JSON Pointer name")]
[Description("The RFC 6901 JSON pointer to extract from the JSON result")]
public string JSonPointerName { get; set; }
/// <summary>
/// Extract a JSON value from the response.
/// </summary>
public override void Extract(object sender, ExtractionEventArgs e)
{
var jsonBody = JsonConvert.DeserializeObject<JToken>(e.Response.BodyString);
var pointer = new JsonPointer(JSonPointerName);
var value = pointer.Find(jsonBody).ToString();
if (!string.IsNullOrWhiteSpace(value))
{
e.WebTest.Context.Add(ContextParameterName, value);
e.Message = $"Property '{JSonPointerName}' has the value '{value}'";
e.Success = true;
}
else
{
e.Message = $"Property '{JSonPointerName}' not found in response";
e.Success = false;
}
}
}
}
@felickz
Copy link
Author

felickz commented Oct 12, 2016

packages.config

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Newtonsoft.Json" version="5.0.8" targetFramework="net452" />
  <package id="Tavis.JsonPointer" version="0.5.0" targetFramework="net452" />
</packages>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment