Last active
July 12, 2018 23:16
-
-
Save GeorgeTsiokos/45daf3f8c55cb08af8c07ffd6561eab7 to your computer and use it in GitHub Desktop.
ToXUnitAssertion(): verbosely assert a dictionary's contents
This file contains 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 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