Showing posts with label BDD. Show all posts
Showing posts with label BDD. Show all posts

Monday, August 4, 2014

Leaveraging BDD with Microsoft Azure and Visual Studio Online

 

BDD (Behavior Development Driven) and TDD are topics that are not new (my first post was in 2011).

Now that we have VSO, Visual Studio Online and Microsoft Azure, we can be even more Agile !

Without debating weather or not one should use BDD or TDD, this post focuses on how to do it the BDD way, and show that SpecFlow could handle easily French.

   

OBJECTIVE: From a “regular” specification (waterfall way) we are going to:

  1. Convert it into BDD,
  2. Write it down into Microsoft TFS / VSO, via Excel
  3. Implementer the Unit tests (helped by the BDD auto-generated code),
  4. The Dev is naturally going to ask questions to the PO (Product Owner) and one of the aim of BDD is to force them to talk ! and have a common language without having any misleading specification.
  5. Implements the code
  6. Performing Refactoring
  7. Prove the PO that the « Definition Of Done » based on the « Given-When-Then » of the BDD is compliant
  8. Il our case, I chose to implement with a 100%Code Coverage, since this is a sensitive and critical functionality
  9. With 100% of Code Coverage, even a slightest modification of the specs will be detected by the test harnesses and the Build machine.

Here is the “regular” Specification

Screen

Role

Profile

Visiteur

Manager

Utilisateur central

Admin

Ecran d 'accueil

Navigation

x

x

x

x

Activité prévisionnelle

Lecture

x

x

x

x

Saisie

x

x

x

Export csv

x

x

x

x

Performance

Lecture

x

x

x

x

Import & Export

Lecture

 

x

x

Lancement import

x

x

Lancement export

x

Utilisateurs

Lecture

x

x

x

Création / Modification

 

x

Paramètres

Lecture

x

x

Saisie alertes

x

x

Saisie paramètres généraux

x

Saisie paramètres généraux

x

 

STEP 1: Convert this table into BDD (In Order To – As a – I want ; and Given-When-Then)
as well as other Product Backlog Items directly into EXCEL (with a 2-way connection to Microsoft TFS / VSO)

If you are irritated with EXCEL, just use MS Project, Word or the TFS Web portal (below).

STEP 2: Let focus on one specific PBI
(displayed with IntelliSense within Visual Studio with the SpecFlow Add-on. Hence, one cannot write any specification since it is going to be compiled by MS Build or Visual Studio)

ETAPE 3: Let SpecFlow autogenerate the test harnesses from the BDD specification

According the the methodology « Red, Green, Refactor » (the you MUST ALWAYS follow in this order else you’ll end-up having tests that returns always True or you’ll forget to « refactor », …),

  1. I write the tests within the BDD auto-generated test hanesses. I run the tests that should fail (Red) {which is normal since I don’t have any code yet !}.
  2. I start implementing my 1rst code so that the tests becomes Green (with refactoring yet, so that if it’s wrong… you should fail fast)
  3. Once green, it’s time to Refactor which is great, since my code is so ugly that TFS refuses to archive my code.

 

BENEFIT N°1 : Refactoring

The refactoring forces me to have few iterations :

-          with ugly code: Maintainability Index = 20 and cyclomatic complexity = 105  (i.e. so complex that no one will want to maintain my code!! where one would say “Yes, but you know, this is a very complex use case, and I had to code 106 line of code! Which is obviously a bad excuse to produce bad code)

-          with less ugly code (Maintenability Index = 59 ; cyclomatic complexity = 63)

-          with maintainable code that fits into half-a-screen (Maintenability Index = 72 i.e. very maintainable; cyclomatic complexity = 28 i.e. not complex).
Rappel:  « Red, Green, Refactor » reminds me that my code can still be refactored to be even better… but at some point we have to deliver the code !

BENEFIT N°2 :

The code is centralized, which seams to be so obvious BUT the fact is that I can still find numerous projects with logic hardcoded into the GUI.

 

BENEFIT N°3 :

The code is protected by 100% of Code Coverage . i.e the slightest modification of the spec will be detected by VSO / TFS.

To cover the 100% of the needs, a hundred of tests are needed (since initially a hundred of line of code). They are wrapped up into only 2 BDD tests that represents 95+5 = 100 ms to execute automatically everytime a check-in is performed.
In the contrary, a “manual test” would have been boring to perform during hours.

image

The 100% of code coverage highlighted in blue ; even Throw Exceptions are tested to reach the 100%

BENEFIT N°4 : Everything is integrated to Visual Studio and Microsoft Team Foundation Server (TFS) or Visual Studio Online (VSO), with Continuous Deployment on Microsoft Azure

BENEFIT N°5: Have you ever read the specification ??

Now with BDD, the Spec becomes part of the « Definition Of Done » (DoD) and most importantly the specification are “bare bone” (i.e. you don’t write unnecessary text) and things that contradicts themselves are sometimes detected by the compiler.

That’s the end of the era where Product Owner would spend days and months to write specifications that are never read, or best are out of date and never synched with the code. Here the Word document is automatically generated by the Given-When-Then acceptance criteria.

      Saturday, July 27, 2013

      Book review : StyleCop Code Analysis How-to

      StyleCop Code Analysis How-to

      http://bit.ly/19mPNkQ

      I am a real fan of StyleCop and FxCop for the last 4 years or so (see how many rules FxCop+StyleCop).

      Up until now, I have been only build up my knowledge from my own experience and reading blogs.

      The small size of this book allows a broader vision rapidly, and covers things that I never had the time to implement on real projects (such as VS Templates, or files headers).

      I also finally understood why my Resharper did not work with my StyleCop, which was an easy thing to fix.

      It is worth reading !

      Thursday, June 23, 2011

      [ALM, Unit Tests, SpecFlow] Magically generate your Unit Tests from the Specifications !!


      (Sorry not translated from my French Blog : http://blogs.codes-sources.com/thavo/. Google Translation will help you)
      Ce serait le rêve de générer par magie ses tests unitaires à partir des specs avant même d’avoir écrit son_code ?
      • A la fois on serait en TDD, qui est déjà un rêve pour une majorité d’entre nous. Vous avez déjà entendu d’un Directeur/Chef de projet “Oui, c’est super les TU… mais on n’a pas le budget, le temps, il y a plus prioritaire, etc…”
      • A la fois nos TU pourraient être “écrits” par le “Business Analyst” ou Chef de projet, si c’était le cas.
      BDD existe déjà depuis un bout de temps, mais je voulais parler d’un outil particulier que nous allons découvrir ci-dessous.
      PS: Dans ce cas BDD pas comme “Base De Données”, mais comme Behaviour Development Driven).

      Comment cela peut fonctionner dans une ALM TFS en mode Agile ??
      1.  Le Chef de projet ou Business Analyst écrit les specs dans TFS en tant que User Story. Voici un exemple : image
      2. Toujours le Chef de projet ou Business Analyst écrit les scénarii de validation de tests d’acceptance afin de valider la User Story précédente.
      Pour cela, écrit dans un fichier texte *.feature (compatible avec le standard Cucumber-Gherkin syntax) sous Visual Studio 2010 pour disposer de l’IntelliSense !!.
      PS1: il y aurait moyen de créer cela en tant que WorkItem puis générer ce fichier texte.
      PS2:  Pour faire le lien avec Scrum, on peut comparer cela à la “Definition Of Done”, qui doit être composé d’éléments mesurables, donc vérifiable (pas du genre… lorsque l’on clic sur le bouton “OK”, l’écran doit s’afficher rapidement).
      image

      3. Ensuite, toute la magie intervient dès que l’on fait Ctrl-S pour “enregistrer” ce fichier.

      Cela génère près de 100 lignes de code de tests unitaires C# (de type MsTest, mais cela pourrait être aussi xUnit, NUnit, MbUnit).

      ”La magie” s’appelle SpecFlow !!
      image

      image
      4. Enfin, on peut compiler le tout et lancer les Tests Unitaires. Ne pas paniquer, si cela ne passe pas, puisque cela respecte bien le principe de TDD se basant sur le “RGR” (Red GreenRefactor). “Red”… enfin, techniquement, ci-dessous c’est Orange, car Inconclusive.
      image

      5. Comme c’est en “Red”, le développeur doit coder le code Business (ou bien le connecter ou bien injecter des objets existants) afin de le faire passer au Green. Pour cela, il suffit de copier / coller le code en bleu ci-dessous généré par TeamSpec (il y a probablement un autre moyen).

      On colle cela dans un autre fichier; bon, pour faire passer au Green, j’ai mis partout des Assert True à titre d’exemple.

      image  image
      Lorsque tout est Green, on connecte le tout à la TeamBuild TFS afin d’être certain qu’il n’y ait pas de régression à chaque Check-in (si Gated Check in), ou bien tous les soirs.

      Ensuite, on “Refactor” la partie Business, voir ses TU afin de faire plus propre. Puis, le CDP réitère en rajoutant des nouvelles “Definition Of Done”, donc cas recasse et nous voila reparti pour le cycle Red Green Refactor.

      Pour aller plus loin dans les tests : Utiliser SpecFlow avec Coded-UI de VS2010 :
      https://github.com/techtalk/SpecFlow/wiki/Using-SpecFlow-with-CodedUI-API

      PS: Suite à l’installation de SpecFlow, ne comptez pas sur l’aide fournie pour vous donner un coup de main, mais votre moteur de recherche préféré (car l’aide PDF est en mode Brouillon et pas complet) ==> Il faut rajouter au crproj de test une référence vers l’assembly SpecFlow et un fichier App.Config contenant les informations suivantes (MsTest, mais vous pouvez choisir les autres types).