In this blog we will continue testing our Scorer class by adding some statistics.
Get the Number of Strikes and Spares
We need to keep track of the number of Strikes and Spares thrown in a game. Let’s write the tests.
[Test] public void Check10SparesWereThrown() { for (int _bowl = 1; _bowl <= 10; _bowl++) _scorer.FrameSpare(5); Assert.That(_scorer.Spares, Is.EqualTo(10)); } [Test] public void Check12StrikesWereThrown() { for (int _bowl = 1; _bowl <= 12; _bowl++) _scorer.FrameStrike(); Assert.That(_scorer.Strikes, Is.EqualTo(12)); }
There is nothing complicated for this. Create two properties initialised to zero and incremented when the FrameStrike or FrameSpare methods are called.
public void FrameSpare(int Bowl1) { Spares++; FrameScore(Bowl1, 10 - Bowl1); } public void FrameStrike() { Strikes++; FrameScore(10, 0); }
Run the tests and they all pass.
Get the Score Card for a Game
The score card will have the players name, each frame score and the running total for each frame. We need to define a new class called ScoreCard with all these properties and test they are populated correctly. Here is the test we can run.
[Test] public void GetPerfectGameScoreCard() { for (int _bowl = 1; _bowl <= 12; _bowl++) _scorer.FrameStrike(); var _scoreCard = _scorer.ScoreCard; Assert.That(_scoreCard.Player, Is.EqualTo(_player)); Assert.That(_scoreCard.Scores.Count, Is.EqualTo(10)); Assert.That(_scoreCard.Scores[9].Item3, Is.EqualTo(300)); Assert.That(_scoreCard.Strikes, Is.EqualTo(12)); Assert.That(_scoreCard.Spares, Is.EqualTo(0)); }
Let’s create a new class called ScoreCard.
public class ScoreCard { public string Player {private set; get;} public int Strikes { private set; get; } public int Spares { private set; get; } public List<Tuple<int, int, int>> Scores { private set; get; } public ScoreCard(string Player, int Strikes, int Spares, List<Tuple<int, int, int>> Scores) { this.Player = Player; this.Strikes = Strikes; this.Spares = Spares; this.Scores = Scores; } }
Create a property called ScoreCard
which use the Score
property to populate the scores into a temporary list.
public ScoreCard ScoreCard { get { _scoreCard = new List<Tuple<int, int, int>>(); var _score = Score; return new ScoreCard(Player, Strikes, Spares, _scoreCard); } }
Run the tests and they all pass.
Summary
This is just a taste of how you can do unit testing and some test driven development. It does end up with lots of code refactoring however; having all those tests which maybe were written by someone else, affirms that what you have done has not broken anything that has a unit test. If you do not have 100% code coverage then you may run the risk of introducing bugs.
Also this example did not include mocking objects which is a whole new subject.