Skip to content

Instantly share code, notes, and snippets.

@quexy
Created June 19, 2017 11:11
Show Gist options
  • Save quexy/14c6561ad9e715553511b06e43339dad to your computer and use it in GitHub Desktop.
Save quexy/14c6561ad9e715553511b06e43339dad to your computer and use it in GitHub Desktop.
WepAPI SpecFlow: checks if input string as JSON of given type matches input table
///<summary> Checks whether the JSON <paramref name="content"/> as <paramref name="resultType"/> contains the entities described in the given <paramref name="table"/> </summary>
private static string[] VerifyJsonContent(string content, string resultType, Table table)
{
var matchingTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetExportedTypes())
.Where(t => (t.Namespace + "." + t.Name).EndsWith(resultType)).ToArray();
if (matchingTypes.Length != 1) return new[] { string.Format("Cannot determine matching type by the name {0}; candidates: [{1}]",
resultType, string.Join(", ", matchingTypes.Select(t => t.Namespace + "." + t.Name))) };
object message = null;
if (!string.IsNullOrEmpty(content))
{
if (!content.StartsWith("[")) content = "[" + content + "]";
message = JsonConvert.DeserializeObject(content, matchingTypes.Single().MakeArrayType());
}
var verifier = typeof(CollectionVerifier).GetMethod("For", BindingFlags.Public | BindingFlags.Static)
.MakeGenericMethod(matchingTypes.Single()).Invoke(null, null);
Func<DateTime, DateTime, bool> dateCompare = (a, b) => a.Date == b.Date && a.Hour == b.Hour && a.Minute == b.Minute;
verifier.GetType().GetMethod("WithTypeEqualityComparer", BindingFlags.Public | BindingFlags.Instance)
.MakeGenericMethod(typeof(DateTime)).Invoke(verifier, new object[] { dateCompare });
var method = verifier.GetType().GetMethod("IsSubset", BindingFlags.Public | BindingFlags.Instance, null,
new[] { typeof(IEnumerable<IDictionary<string, string>>), typeof(IEnumerable<>).MakeGenericType(matchingTypes.Single()) }, null);
return (string[])method.Invoke(verifier, new object[] { table.Rows, message });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment