Just Did the String Calculator Kata
I just did the [string calculator kata](the string calculator kata ), here is the output, first the test code:
[TestFixture]
public class CalculatorTests
{
readonly Calculator _calc = new Calculator();
[Test]
public void Add_WhenGiven1_ShouldReturn1()
{
int result = _calc.Add("1");
Assert.That(result, Is.EqualTo(1));
}
[Test]
public void Add_WhenGiven15_ShouldReturn15()
{
int result = _calc.Add("15");
Assert.That(result, Is.EqualTo(15));
}
[Test]
public void Add_WhenGiven1comma5_ShouldReturn6()
{
int result = _calc.Add("1,5");
Assert.That(result, Is.EqualTo(6));
}
[Test]
public void Add_WhenGiven115comma23_ShouldReturn138()
{
int result = _calc.Add("115,23");
Assert.That(result, Is.EqualTo(138));
}
[Test]
public void Add_WhenGivenAlphaCharacter_ShouldThrowArgumentException()
{
Assert.Throws<ArgumentException>(() => _calc.Add("jens"));
}
[Test]
public void Add_WhenGivenAlphaNumericCharacterWithNumericAtTheEnd_ShouldThrowArgumentException()
{
Assert.Throws<ArgumentException>(() => _calc.Add("jens1"));
}
[Test]
public void Add_WhenGivenAlphaNumericCharacterWithNumericAtTheBeginning_ShouldThrowArgumentException()
{
Assert.Throws<ArgumentException>(() => _calc.Add("1jens"));
}
}
And here is the implementation:
public class Calculator
{
public int Add(string s)
{
if(!Regex.IsMatch(s, @"^\d+(,\d+)?$"))
throw new ArgumentException("s");
var numbers = s.Split(',');
int returnValue = 0;
foreach (var number in numbers)
{
returnValue += int.Parse(number);
}
return returnValue;
}
}