unit testing - How to refactor tests in tdd? -


i'm performing tdd kata excercise: http://osherove.com/tdd-kata-1

i produced following code (points 1 5 in excercise - have unit tests it):

public class stringcalculator {     private readonly string[] _defaultseparators = { ",", "\n" };      public int add(string numbers)     {         // parser section (string list of ints)         var separators = _defaultseparators;          var isseparatordefinitionspecified = numbers.startswith("//");         if (isseparatordefinitionspecified)         {             var endofseparatordefinition = numbers.indexof('\n');              var separator = numbers.substring(2, endofseparatordefinition - 2);              numbers = numbers.substring(endofseparatordefinition);             separators = new[] { separator };         }          var numbersarray = numbers.split(separators, stringsplitoptions.removeemptyentries);         var numbersarrayasints = numbersarray.select(int.parse).toarray();          // validator section         var negativenumbers = numbersarrayasints.where(c => c < 0).toarray();         if (negativenumbers.any())         {             throw new exception(string.format("negatives not allowed ({0})", string.join(", ", negativenumbers)));         }          return numbersarrayasints.sum();     } } 

now want refactor code this:

public int add(string numbers) {     var numbersasints = calculatornumbersparser.parse(numbers);      calculatornumbersvalidator.validate(numbersasints);      return numbersasints.sum(); } 

how should plan refactor refactor code , unit tests?

i think should move part of tests new created implementations classes tests (calculatornumbersparsertests , calculatornumbersvalidatortests), change existing tests , add tests parse , validate method execution.

but correct way without breaking tests?

i caution against moving tests if tests tied implementation, means brittle , have change tests every time want change implementation. can become expensive when have large code base , can become prohibiting factor in making changes.

your existing tests should specify behaviour of string calculator , can refactor implementation long keep desired behaviour.

i tend think of unit 'unit of behaviour' , may take few classes implement this.

things might change if place classes in different assembly, @ point want make new tests along side new assembly, ensure behaviour of components not changed unexpectedly, in case doubt doing this.

things might change if start reuse classes in several places, @ point may want separate tests specify behaviour of classes independently of use in places.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -