Reputation: 3265
I am writing a unit test to test the following method.
public void MyMethod(string parm1)
{
// Validate parm1.
string[] invalidTokens = new string[] { "/", "{", "}", ".", "--", ";", " ", ",", "=", "(", ")", "\"", "'", "?" };
foreach (string token in invalidTableTokens)
{
if (parm1.Contains(token))
throw new ArgumentException("Parameter cannot contain \"" + token + "\".");
}
// No invalid characters so continue processing...
}
The unit test should verify that passing a string that contains an invalid character results in an exception. I want my unit test to be data driven with an XML (or CSV) datasource.
[TestMethod()]
[DeploymentItem("\\path\my_data.xml")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\my_data.xml", "Token", DataAccessMethod.Sequential)]
public void MyMethod_Parm1ContainsInvalidCharacters_ThowsException()
{
// Arrange
string invalidToken = TestContext.DataRow["Token_Text"].ToString();
MyClass sut = new MyClass ();
// Act
string errorMessage = "";
try
{
sut.MyMethod(invalidToken);
}
catch (ArgumentException ex)
{
errorMessage = ex.Message;
}
// Assert
Assert.AreEqual(errorMessage, "Parameter cannot contain \"" + invalidToken + "\".");
}
This works except when the tests needs to pass a single space character " ". Unfortunately, the value for Token_Text
is always "" when I need it to be a space.
<?xml version="1.0" encoding="utf-8" ?>
<InvalidTokens>
<Token>/</Token>
<Token>{</Token>
<Token>}</Token>
<Token>.</Token>
<Token>--</Token>
<Token>;</Token>
<Token> </Token> <!-- Fails here-->
<Token Token_Text=" "/> <!-- Also fail here -->
<Token>,</Token>
<Token>=</Token>
<Token>(</Token>
<Token>)</Token>
<Token>"</Token>
<Token>'</Token>
<Token>?</Token>
</InvalidTokens>
I have also tried this with the following CSV file and get the same results.
Token
"/"
"{"
"}"
"."
"--"
";"
" " <-- Fails here
","
"="
"("
")"
""""
"'"
"?"
How can I represent a single space character for use in a data driven unit test?
Upvotes: 2
Views: 450
Reputation: 3265
I was able to represent a space by using special character decimal encoding.
<Token> </Token>
Upvotes: 2