I don't know and I don't like the most common naming conventions. I find them hard to read and understand. Based on few other naming conventions (which I cannot tell which one now) I developed my own, here it is:
Let's say I have the following class to test:
public class ColorParser {
public static bool TryParseHex(string value, out Color color) {
// Code to parse the hex color value.
}
}
My unit tests for this particular method look like the following:
public class ColorParserTests
{
public class TryParseHexTests
{
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void TestNullValue()
{
Color color = Color.Empty;
ColorParser.TryParseHex(null, out color);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void TestEmptyValue()
{
Color color = Color.Empty;
ColorParser.TryParseHex(string.Empty, out color);
}
[TestMethod]
public void TestInvalidValues()
{
string[] invalidValues = new string[]
{
"#",
"FF",
"#FF",
"#FFAA",
"asdf"
};
foreach (var invalidValue in invalidValues)
{
Color color = Color.Empty;
bool result = ColorParser.TryParseHex(invalidValue, out color);
Assert.IsFalse(result, string.Format("Value '{0}' must not pass the test!", invalidValue));
}
}
[TestMethod]
public void TestValidValues()
{
// Spaces are intended and a part of the test!
Dictionary<string, Color> validValues = new Dictionary<string, Color>()
{
{" #000000", Color.FromArgb(0,0,0)},
{" #010203 ", Color.FromArgb(1,2,3)},
{"#00FFFF", Color.FromArgb(0,255,255)},
{"#FF00FFFF", Color.FromArgb(255,0,255,255)},
};
foreach (var validValue in validValues)
{
Color color = Color.Empty;
bool result = ColorParser.TryParseHex(validValue.Key, out color);
Assert.IsTrue(result, string.Format("Value '{0}' must pass the test!", validValue.Key));
Assert.AreEqual(validValue.Value, color, "Parsed color must be the same.");
}
}
}
}
The idea behind this is that the particualr tests are groupped (in classes) which allows me to test them separately. There is no need to repeat the method name being tested each time. The test method begins with a verb like a method name should and and it just contains a short information about what exacly is being tested. Everything else is inside the test.
This way I very quickly know what I'm testing and the results should be defined inside the tests themselves beacause what I'm testing is the behaviour for some values that either are correct or incorrect.
Nulls and Emptys and other special cases that throw exceptions deserve they own tests.
You could broke the tests up and write more tests like TestValuesWithSpaces
or TestNegativeDeposit
or TestUserNameWithInvalidCharacters
etc. It always depends how much to test there is and how precise you want to do it. In this case I thought it's sufficient. Anyway I think this is very descriptive.