Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
TestAverageMethod()
void TestAverageMethod(Func<int, int, int> method)
{
string methodName = method.Method.Name;
List<string> failureText = new List<string>();
int passCount = 0;
int testCount = 0;
Action<int, int, int> test = (a, b, expected) =>
{
testCount++;
try
{
int actual = method(a, b);
if (actual != expected)
failureText.Add(String.Format("{0}({1}, {2}) returns {3}, but should return {4}", methodName, a, b, actual, expected));
else
passCount++;
}
catch (Exception ex)
{
failureText.Add(String.Format("{0}({1}, {2}) threw {3}", methodName, a, b, ex.GetType().FullName));
}
};
Console.WriteLine("Results for {0}():", methodName);
// low value tests
passCount = 0;
testCount = 0;
for (int a = -5; a <= 5; a++)
{
for (int b = -5; b <= 5; b++)
{
int expected = (a + b) / 2;
test(a, b, expected);
}
}
Console.WriteLine(" Near Zero: {0} of {1} passed.", passCount, testCount);
// end of range tests
passCount = 0;
testCount = 0;
test(Int32.MaxValue, Int32.MaxValue, Int32.MaxValue);
test(Int32.MinValue, Int32.MinValue, Int32.MinValue);
test(Int32.MaxValue, Int32.MaxValue - 2, Int32.MaxValue - 1);
Console.WriteLine(" End of Range: {0} of {1} passed.", passCount, testCount);
// write out any failures
if (failureText.Count > 0)
{
Console.WriteLine(" Failed Values:");
foreach (string text in failureText)
Console.WriteLine(" - {0}", text);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.