You cannot write Test-Driven Code from existing code, because tests should be written before you write implementation.
Simplest way of testing your code is providing TextWriter
mock to Console.Out
and verifying generated output.
UPDATE: If you want to use TDD, then you should modify your code to make it testable. Here your Program
class does to many things - it is responsible both for presentation (output results to console) and business logic (calculating of values). For testing business logic you should move this functionality to separate class.
Lets start. First test:
[Test]
public void ShoulReturnHoonWhenValueDivisibleOnlyBy3()
{
var hoonGroup = new HoonGroup();
string result = hoonGroup.Calculate(3);
Assert.AreEqual("HOON", result);
}
It fails to compile, because you don't have HoonGroup
class. Create class, create method Calculate
. Make code compilable:
public class HoonGroup
{
public string Calculate(int value)
{
return "";
}
}
Now your test fails because you are returning empty string. Just hard-code "HOON" to make test pass. Thats OK with TDD.
public class HoonGroup
{
public string Calculate(int value)
{
return "HOON";
}
}
Next test:
[Test]
public void ShoulReturnGroupWhenValueDivisibleOnlyBy5()
{
var hoonGroup = new HoonGroup();
string result = hoonGroup.Calculate(5);
Assert.AreEqual("Group", result);
}
Of course, test fails. Update implementation:
public class HoonGroup
{
public string Calculate(int value)
{
return (value == 5) ? "Group" : "HOON";
}
}
Looks stupid. But it implements all requirements of your code. Another test:
[Test]
public void ShoulReturnNullWhenValueIsNotDivisibleBy3Or5()
{
var hoonGroup = new HoonGroup();
string result = hoonGroup.Calculate(5);
Assert.IsNull(result);
}
No problem - add another condition:
public class HoonGroup
{
public string Calculate(int value)
{
if (value == 3)
return "HOON";
if (value == 5)
return "Group";
return null;
}
}
Tests pass. We need more test cases. It's easy to do with NUnit - just decorate first test with TestCase
attributes (MSTest also has similar feature):
[TestCase(3)]
[TestCase(6)]
[TestCase(99)]
public void ShoulReturnHoonWhenValueDivisibleOnlyBy3(int value)
{
var hoonGroup = new HoonGroup();
string result = hoonGroup.Calculate(value);
Assert.AreEqual("HOON", result);
}
And now its easier to create code which checks if value is divisible by 3 then listing all possible values:
public class HoonGroup
{
public string Calculate(int value)
{
if (value % 3 == 0)
return "HOON";
if (value == 5)
return "Group";
return null;
}
}
I think you get the point and rithm of TDD. Create more test cases for values divisible by 5 and write test for values divisible both by 3 and 5.