I want to be able to split a formatting string on the variables' position indicators. It will chop out the curly braces and the position indicating numbers in between them.
So, the string:
string format = "{0} field needs to be set to '{1}' when {2}, Fixit. NOW!";
Should resolve to 3 strings.
- " field needs to be set to '"
- "' when "
- ", Fixit. NOW!"
We use string like the above 'format' to build error messages. My goal is to add generic unit tests that can take in the format and verify that an error message was generated that matches the expected format. Since both the error generation code and the unit test reference the same formatting, the unit tests won't need to be updated when minor changes are made to the message.
In the above example, i'll be able to test for the expected results, via a call to a new method called SplitFormatString.
string fieldName = "UserName";
string expectedValue = "Bob";
string condition = "excellence is a must";
string errorMessage = TestFieldValueErrorCase( );
AssertStringContainsAllThese(errorMessage, SplitFormatString(format), fieldName, expectedValue,condition);
With validation
public static void AssertStringContainsAllThese(string msg, string[] formatChunks, params string[] thingsToFind)
{
foreach (var txt in formatChunks.Concat(thingsToFind))
{
Assert.IsTrue(msg.Contains(txt), "Could not find <<" + txt + ">> in msg >>> " + msg);
}
}
I'd rather use regex than an inelegant approach using substrings.
\n?