refining the battle parsing

I've been writing an acceptance testing framework for my robocode Robot and I had previously got everything working.
As with most things though, a bug cropped up - when using the sitting duck robot and my own, that did nothing at the time, there were occasions when the sitting duck did not see my robot and was not scanning.
Therefore the scores came out at zero like this:

result0

My parsing code is expecting there to be a percentage total score in brackets (such as "120 (88%)" ), but because all scores are zero, it seems this is missing from the file.

Now this is where I'm glad I wrote the framework specification-first and why I'm writing this post- all I need is a new specification to handle this situation and I can ensure I can parse this file and not regress my previous parsing behaviour.
Here's a new specification:

    public class when_creating_a_battle_result_from_a_result_line_where_there_was_
                                       zero_score_for_all_robots
    {
        Establish context = () => battleResultLine = 
            "2nd: sample.SittingDuck\t0\t0\t0\t0\t0\t0\t0\t1\t0\t0\t";

        Because of = () => battleResult = new BattleResult(battleResultLine);

        It should_have_the_total_score_percentage_of_zero = () => 
             battleResult.TotalScorePercentage.ShouldEqual(0);

        static string battleResultLine;
        static BattleResult battleResult;
    }

Currently, this fails with an IndexOutOfRange exception when my parsing code tries to split by the bracket character, then access the array for the percentage.
Here's the bug fix:

    int GetTotalScorePercentageFrom(string result)
    {
        //comes in as "3600 (88%)", but not if all results were zero
        if (!result.Contains("("))
            return 0;

        return Convert.ToInt32(result.Split('(')[1].Split(')')[0].Replace("%", ""));
    }

This is why I love context specification first development - writing failing descriptive specifications before writing the code.
Not only do they assist with your immediate development, but they allow you to add new specifications in at a later date and modify code with a high level of confidence that you have not regressed any of the behaviour described by your previous expectations.



0 comments: