Here is my solution when I apply TDD on FizzBuzz using C# :
class FizzBuzz
{
private readonly List<Tuple<int, string>> rules;
public FizzBuzz()
: this(new Tuple<int, string>[0])
{
}
public FizzBuzz(IEnumerable<Tuple<int, string>> rules)
{
this.rules = rules.ToList();
}
public string Convert(int i)
{
var label = string.Join("", rules.Where(r => i % r.Item1 == 0).Select(r => r.Item2));
return label.Length > 0 ? label : i.ToString();
}
}
[TestFixture]
public class FizzBuzzTest
{
[TestCase(1, "1")]
[TestCase(2, "2")]
[TestCase(3, "3")]
public void TestNoRule(int i, string value)
{
Assert.AreEqual(value, new FizzBuzz().Convert(i));
}
[TestCase(1, "1")]
[TestCase(2, "2")]
[TestCase(3, "Fizz")]
public void TestFizz(int i, string value)
{
Assert.AreEqual(value, new FizzBuzz(new[] { new Tuple<int, string>(3, "Fizz") }).Convert(i));
}
[TestCase(1, "1")]
[TestCase(2, "2")]
[TestCase(3, "3")]
[TestCase(4, "4")]
[TestCase(5, "Buzz")]
public void TestBuzz(int i, string value)
{
Assert.AreEqual(value, new FizzBuzz(new[] { new Tuple<int, string>(5, "Buzz") }).Convert(i));
}
[TestCase(15, "FizzBuzz")]
public void TestFizzBuzz(int i, string value)
{
var rules = new[] {
new Tuple<int, string>(3, "Fizz"),
new Tuple<int, string>(5, "Buzz"),
};
Assert.AreEqual(value, new FizzBuzz(rules).Convert(i));
}
[Test] public void TestFizzBuzz1_100()
{
var rules = new[] {
new Tuple<int, string>(3, "Fizz"),
new Tuple<int, string>(5, "Buzz"),
};
var fizzBuzz = new FizzBuzz(rules);
for (int i = 1; i < 100; i++)
Console.WriteLine(fizzBuzz.Convert(i));
}
}
See also :