Skip to content

Instantly share code, notes, and snippets.

@4E71
Created March 6, 2012 01:25
Show Gist options
  • Save 4E71/1982710 to your computer and use it in GitHub Desktop.
Save 4E71/1982710 to your computer and use it in GitHub Desktop.
TDD: A simple example
// 1. Create a simple test method.
// Example test harness calls:
// public static void AlgUtil_Harness() {
// Test_CountTwos(232);
// Test_CountTwos(-232);
// }
private static void Test_CountTwos(int n) {
Console.WriteLine("The number of twos in {0} are: {1}", n, AlgUtil.CountTwos(n));
}
// 2. Create a skeleton method/function and test.
using System;
namespace Dsa
{
public static class AlgUtil
{
// Counts the number of 2's in an integer.
public static int CountTwos(int n) {
return -1;
}
}
}
The number of twos in 232 are: -1
The number of twos in -232 are: -1
Press any key to continue...
// 3. Complete implementation and retest.
using System;
namespace Dsa
{
public static class AlgUtil
{
// Counts the number of 2's in an integer.
public static int CountTwos(int n) {
// I don't want to handle negative numbers atm.
// Note: We should use Code Contracts if using .NET 4.0
if (n < 0) return -1;
string number = n.ToString();
int count = 0;
for (int i = 0; i < number.Length; i++) {
if (number[i] == '2') count++;
}
return count;
}
}
}
The number of twos in 232 are: 2
The number of twos in -232 are: -1
Press any key to continue...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment