Skip to content

Instantly share code, notes, and snippets.

@kek-Sec
Created June 9, 2022 10:38
Show Gist options
  • Select an option

  • Save kek-Sec/6638ec939b7abb89d16f33fe91c8097d to your computer and use it in GitHub Desktop.

Select an option

Save kek-Sec/6638ec939b7abb89d16f33fe91c8097d to your computer and use it in GitHub Desktop.
Utilities for testing JsonResult in .net
public static class JsonResultTestingUtils
{
///<summary>
/// Helper function that parses a given JsonResult and validates that the content is of the expected type
/// </summary>
/// <typeparam name="T">The expected type of the content</typeparam>
/// <param name="result">The JsonResult to be parsed</param>
/// <returns>True if the content is of the expected type, false otherwise</returns>
public static bool ValidateJsonResult<T>(JsonResult result)
{
if (result.StatusCode != 200)
{
return false;
}
var content = result.Value;
if (content == null)
{
return false;
}
if (!(content is T))
{
return false;
}
return true;
}
///<summary>
/// Helper function that parses a given JsonResult and validates that the json contains the given list of keys
/// </summary>
/// <param name="result">The JsonResult to be parsed</param>
/// <param name="keys">The list of keys to be validated</param>
/// <returns>True if the json contains the given keys, false otherwise</returns>
public static bool ValidateJsonResultKeys(JsonResult result, params string[] keys)
{
var content = result.Value;
//loop keys and use result.Value?.GetType().GetProperty(key)?.GetValue(result.Value) to get the value
foreach (var key in keys)
{
if (content?.GetType().GetProperty(key,BindingFlags.Instance | BindingFlags.Public) == null)
{
return false;
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment