Created
June 9, 2022 10:38
-
-
Save kek-Sec/6638ec939b7abb89d16f33fe91c8097d to your computer and use it in GitHub Desktop.
Utilities for testing JsonResult in .net
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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