Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save GeorgeTsiokos/45daf3f8c55cb08af8c07ffd6561eab7 to your computer and use it in GitHub Desktop.
Save GeorgeTsiokos/45daf3f8c55cb08af8c07ffd6561eab7 to your computer and use it in GitHub Desktop.
ToXUnitAssertion(): verbosely assert a dictionary's contents
public static class DictionaryExtensions
{
public static string ToXUnitAssertion<TKey, TValue>([NotNull] this IDictionary<TKey, TValue> dictionary, string variableName = "dictionary")
{
var isKeyString = typeof(TKey) == typeof(string);
var isValueString = typeof(TValue) == typeof(string);
string GetKey(TKey key) => isKeyString ? $"\"{key}\"" : key.ToString();
string GetValue(TValue value) => isValueString ? $"\"{value}\"" : value.ToString();
var stringBuilder = new StringBuilder();
stringBuilder.Append($"Assert.Equal({dictionary.Count}, {variableName}.Count); ");
foreach (var keyValuePair in dictionary)
{
stringBuilder.Append($"Assert.True({variableName}.ContainsKey({GetKey(keyValuePair.Key)})); ");
stringBuilder.Append($"Assert.Equal({GetValue(dictionary[keyValuePair.Key])}, {variableName}[{GetKey(keyValuePair.Key)}]); ");
}
return stringBuilder.ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment