Unit Testing Utility Methods
If I have a utility method such as below, how am I supposed to unit test it? It seems like if I wanted to determine that the output was correc开发者_C百科t I would have to build the code into the test method? I could see if there was conditional logic such as if the input string is empty return null, but testing for correct output seems tricky.
public static string EncodeTo64(string input)
{
byte[] b = System.Text.ASCIIEncoding.ASCII.GetBytes(input);
string returnValue = System.Convert.ToBase64String(b);
return returnValue;
}
I would test it by inputting a value I knew the correct output from. Either by calculating it beforehand, or by comparing it to a known value. You are probably able to compute the output for a short string yourself.
Further I would test the methods behavior for border conditions like null values and empty strings.
With a few exceptions, you wouldn't test the output at all, because that's implemented by another unit - the System.Convert
class, and it's already well-tested.
It would make sense to to write tests that document what the method does when you pass it unusual inputs: null, string.Empty
, strings with non-ASCII encodings, etc..
It depends on what the meaning of "correctness" for this function is to you, the developer. I would convert a known string to the output, verify that that is correct according to whatever criteria matters to me, and then compare that the result of the function matches the result I've produced. Something like this:
const string expectedBase64String = "abc123$$%++";
const string testString = "Not the base 64 source of above";
Assert.AreEqual(expected, Utility.EncodeTo64(testString));
You are correct essentially...you'll need to rely on some other definition of correctness other than the behavior of your code, unless all you need to test is "this is still producing what it did the first time I ran it".
Use pre-determined input and the resulting correct output and compare against what your method produces. Do this for several input/output pairs to test the overall correctness of your method.
精彩评论