Behaviour Driven DevelopmentWith NBehaveLinking User Stories and Domain Driven Design to TestingDavid RossW: www.pebblesteps.comE: willmation@gmail.com
Behavior Driven DevelopmentTools and techniquesTalk overviewWhat is BDD and how to use NBehave Topics What are high quality requirements?
Top down and Bottom up Testing
NBehaveUsing libraryUsing the test runnerTop down design with Rhino.Mocks and Nbehave
Acceptance testingBehavior Driven DevelopmentAnalysis/Design Methodology by Dan NorthResponse to:confusion about Test Driven Development and Test First DevelopmentLack of rigor around User Stories (Requirements)Projects that generate documentation out of Unit testsCulminated in:the BDD method for writing User StoriesJBehave unit testing framework
Behavior Driven DevelopmentBDD is not:a testing framework or style of testinga method for writing testsBDD is:A formalised template for User StoriesAble to create testable User Stories since they are defined in a formal mannerPromotes “security” to a first call citizen in the analysis process
Simple Trading applicationExcel spreadsheet replacement
Allow Portfolio Manager to decide the percentage split between Cash, Property and Stock within the PortfolioInform the Trader when the Portfolio needs to be rebalanced (ie split in the pie has changed significantly)Allow Operations to standardise Portfolio namesSimple Trading applicationRequirements
Test First DevelopmentSmall stepsRed - Analysis/Design HatCreate a test that defines the expected outcome
Asking "What I want is...“Green - Creative Hat (Fun part)Experiment/Prototype/Build until the test passesRefactor- EngineeringRefactor, refactor, refactorRedGreenRefactor
Test First DevelopmentHow easy is it to use TFD for the followingRequirement/StoryValue = Units * Market PriceIncrease the performance of the User Security module by automatically caching the user’s manager IdThe system must email the Portfolio manager when the Portfolio needs to be rebalancedBuild a web site so that customers can see the performance of the portfolio
Test First DevelopmentDo you feel guilty??	Do you write a Failing unit test before every piece of code?Do you write a line of Unit Test code for EVERY line of production code?
Behavior DrivenHow do you write a test when you don’t know where you are going? Maybe we need requirements that are easy to write tests for?
RequirementsWhat are theyDescribes what a system should do but not how it will be doneContract between the implementation team and the analysis teamAudience is typically the stake holders and not the development team
RequirementsPrecise and clear over verboseWe want requirements that  Can be tested!!!
Are attainable!!! 
Are traceable into code!!!Requirements GatheringBDD merges two different approachesUser StoriesShort one or two line statement that maps to a few days of development workHighly focusedDomain Driven DesignUbiquitous language – Ensure business terminology permeates into codeClear single definition (within the project) for each business concept - Account has a single meaning
BDD User StoriesFormal template for User StoriesStory TemplateAs a [User/Role]I want [Behaviour]so that [I receive benefit]ExampleAs a “Operations staff member”I want “To create a Portfolio”so that“So that it can be traded”
BDD User StoriesFormal template for User StoriesScenario TemplateGiven some initial context (the givens),When an event occurs,then ensure some outcomes.ExampleGiven “New portfolio is called Balanced Fund”When “Portfolio already exists”then “Portfolio can no be created”
.NET Library for writing automated BDD style testsFluent syntax for building up a BDD Style User StoriesTest runner that executes the stories and generates a report listing the contents of the storiesNBehaveWhat is it?
Creating a BDD ThemeCollection of related stories[Theme("Portfolio Maintenance")]public class PortfolioMaintenanceStory{[Story]public void portfolio_create_story () { ... }[Story]public void portfolio_delete_story() { ... }}Reference:NBehave.Narrator.Framework.dll
Creating a Story Fluent interface to define the storyvar story = new Story("Create portfolio");story.AsA(“Operations team member")	.IWant("To create a new portfolio on behalf of a portfolio manager")	.SoThat("the portfolio manager can configure the portfolio and the front office can trade");
Creating a ScenarioFluent interface to define the storystory.WithScenario("portfolio does not exist").Given("portfolio name is $name", "Aggressive Fund").When("portfolio does not exist in the database").Then("new portfolio should be created");story.WithScenario("portfolio already exists")	.Given("portfolio name is $name", "Aggressive Fund")	.When("portfolio already exists in database")	.Then("an error should occur");
Executing the testWithNBehave runner or mbUnitOuch we get an error???The scenario throws an exception – NBehave isn’t validating any codeUse Pendingstory.WithScenario("portfolio does not exist")	.Pending("In progress")	.Given("portfolio name is $name", "Aggressive Fund")	.When("portfolio does not exist in the database")	.Then("new portfolio should be created");
Behavior Driven DevelopmentAcross the Project (Story) Life CycleStoryPending ScenarioStubbed Behavior Cycle (Red, Green, Refactor)Real Behavior Cycle (Red, Green, Refactor)Acceptance Test
Stubbing out the behaviorWithNBehave and Rhino.MocksSteps to generate an APIGo through the User story and find all the domain objectsCreate a class for each domain object but don’t add stateGo through the User story and create a find all the services that are required (Repositories etc)Create an interface for each service but don’t add any methods
Steps to generate the API continued...Slowly implement the storyAdd domain object properties as requiredAdd methods signatures as requiredUse Stubs to explore Inputs/Outputsto the methodsStubbing out the behaviorWithNBehave and Mocking
Stubbing exampleCreate a new portfolio storystringportfolioName = "";Portfoliop = null;varportfolioRepository = MockRepository.GenerateStub<IPortfolioRepository>();varportfolioService = MockRepository.GenerateStub<IPortfolioService>();s.WithScenario("portfolio already exists")	.Given("portfolio name is $name", "Aggressive Fund",   n => {portfolioName= n;		p = new Portfolio { Name = portfolioName };portfolioRepository.			Stub(x => x.FindPortfolioByName(portfolioName)).Return(p);portfolioService.			Stub(X => X.CreatePortfolio(p)).Throw(new ItemExistsException());		})
Stubbing exampleCreate a new portfolio story.When("portfolio already exists in database",	 () => Assert.IsNotNull(portfolioRepository.FindPortfolioByName(portfolioName))	).Then("new portfolio create should fail",	() => Assert.Throws<ItemExistsException>(() => portfolioService.CreatePortfolio(p))	);
TFD/BDD ComparisonBehavior DrivenTop down approach
Design starting with interfaces (using stubs)
Back fill with code later  OutputAPI creationTest FirstBottom Up approach
Lots of little steps working towards a solution   Output TestsUser Acceptance TestNBehavetest cases are compiledMust be created by developers or technical testersAre created at the start of the projectFitnesseUser Acceptance tests are Wiki based and so are dynamicCan be created by end users and business analystsCan be created at the start of the projectBut are only “implemented” by the development late in the SDLC
Test Driven DevelopmentDevelopment/Testing PhasesStubsDomain ModelUser StoriesBehaviour Driven DevelopmentGUI TestingFitnessUser AcceptanceTestUnit & Component TestMocksImplemented BehaviourSystemIntegration TestNo Mocks/StubsDeployment Verification Test

Behaviour Driven Development V 0.1

  • 1.
    Behaviour Driven DevelopmentWithNBehaveLinking User Stories and Domain Driven Design to TestingDavid RossW: www.pebblesteps.comE: willmation@gmail.com
  • 2.
    Behavior Driven DevelopmentToolsand techniquesTalk overviewWhat is BDD and how to use NBehave Topics What are high quality requirements?
  • 3.
    Top down andBottom up Testing
  • 4.
    NBehaveUsing libraryUsing thetest runnerTop down design with Rhino.Mocks and Nbehave
  • 5.
    Acceptance testingBehavior DrivenDevelopmentAnalysis/Design Methodology by Dan NorthResponse to:confusion about Test Driven Development and Test First DevelopmentLack of rigor around User Stories (Requirements)Projects that generate documentation out of Unit testsCulminated in:the BDD method for writing User StoriesJBehave unit testing framework
  • 6.
    Behavior Driven DevelopmentBDDis not:a testing framework or style of testinga method for writing testsBDD is:A formalised template for User StoriesAble to create testable User Stories since they are defined in a formal mannerPromotes “security” to a first call citizen in the analysis process
  • 7.
    Simple Trading applicationExcelspreadsheet replacement
  • 8.
    Allow Portfolio Managerto decide the percentage split between Cash, Property and Stock within the PortfolioInform the Trader when the Portfolio needs to be rebalanced (ie split in the pie has changed significantly)Allow Operations to standardise Portfolio namesSimple Trading applicationRequirements
  • 9.
    Test First DevelopmentSmallstepsRed - Analysis/Design HatCreate a test that defines the expected outcome
  • 10.
    Asking "What Iwant is...“Green - Creative Hat (Fun part)Experiment/Prototype/Build until the test passesRefactor- EngineeringRefactor, refactor, refactorRedGreenRefactor
  • 11.
    Test First DevelopmentHoweasy is it to use TFD for the followingRequirement/StoryValue = Units * Market PriceIncrease the performance of the User Security module by automatically caching the user’s manager IdThe system must email the Portfolio manager when the Portfolio needs to be rebalancedBuild a web site so that customers can see the performance of the portfolio
  • 12.
    Test First DevelopmentDoyou feel guilty?? Do you write a Failing unit test before every piece of code?Do you write a line of Unit Test code for EVERY line of production code?
  • 13.
    Behavior DrivenHow doyou write a test when you don’t know where you are going? Maybe we need requirements that are easy to write tests for?
  • 14.
    RequirementsWhat are theyDescribeswhat a system should do but not how it will be doneContract between the implementation team and the analysis teamAudience is typically the stake holders and not the development team
  • 15.
    RequirementsPrecise and clearover verboseWe want requirements that  Can be tested!!!
  • 16.
  • 17.
    Are traceable intocode!!!Requirements GatheringBDD merges two different approachesUser StoriesShort one or two line statement that maps to a few days of development workHighly focusedDomain Driven DesignUbiquitous language – Ensure business terminology permeates into codeClear single definition (within the project) for each business concept - Account has a single meaning
  • 18.
    BDD User StoriesFormaltemplate for User StoriesStory TemplateAs a [User/Role]I want [Behaviour]so that [I receive benefit]ExampleAs a “Operations staff member”I want “To create a Portfolio”so that“So that it can be traded”
  • 19.
    BDD User StoriesFormaltemplate for User StoriesScenario TemplateGiven some initial context (the givens),When an event occurs,then ensure some outcomes.ExampleGiven “New portfolio is called Balanced Fund”When “Portfolio already exists”then “Portfolio can no be created”
  • 20.
    .NET Library forwriting automated BDD style testsFluent syntax for building up a BDD Style User StoriesTest runner that executes the stories and generates a report listing the contents of the storiesNBehaveWhat is it?
  • 21.
    Creating a BDDThemeCollection of related stories[Theme("Portfolio Maintenance")]public class PortfolioMaintenanceStory{[Story]public void portfolio_create_story () { ... }[Story]public void portfolio_delete_story() { ... }}Reference:NBehave.Narrator.Framework.dll
  • 22.
    Creating a StoryFluent interface to define the storyvar story = new Story("Create portfolio");story.AsA(“Operations team member") .IWant("To create a new portfolio on behalf of a portfolio manager") .SoThat("the portfolio manager can configure the portfolio and the front office can trade");
  • 23.
    Creating a ScenarioFluentinterface to define the storystory.WithScenario("portfolio does not exist").Given("portfolio name is $name", "Aggressive Fund").When("portfolio does not exist in the database").Then("new portfolio should be created");story.WithScenario("portfolio already exists") .Given("portfolio name is $name", "Aggressive Fund") .When("portfolio already exists in database") .Then("an error should occur");
  • 24.
    Executing the testWithNBehaverunner or mbUnitOuch we get an error???The scenario throws an exception – NBehave isn’t validating any codeUse Pendingstory.WithScenario("portfolio does not exist") .Pending("In progress") .Given("portfolio name is $name", "Aggressive Fund") .When("portfolio does not exist in the database") .Then("new portfolio should be created");
  • 25.
    Behavior Driven DevelopmentAcrossthe Project (Story) Life CycleStoryPending ScenarioStubbed Behavior Cycle (Red, Green, Refactor)Real Behavior Cycle (Red, Green, Refactor)Acceptance Test
  • 26.
    Stubbing out thebehaviorWithNBehave and Rhino.MocksSteps to generate an APIGo through the User story and find all the domain objectsCreate a class for each domain object but don’t add stateGo through the User story and create a find all the services that are required (Repositories etc)Create an interface for each service but don’t add any methods
  • 27.
    Steps to generatethe API continued...Slowly implement the storyAdd domain object properties as requiredAdd methods signatures as requiredUse Stubs to explore Inputs/Outputsto the methodsStubbing out the behaviorWithNBehave and Mocking
  • 28.
    Stubbing exampleCreate anew portfolio storystringportfolioName = "";Portfoliop = null;varportfolioRepository = MockRepository.GenerateStub<IPortfolioRepository>();varportfolioService = MockRepository.GenerateStub<IPortfolioService>();s.WithScenario("portfolio already exists") .Given("portfolio name is $name", "Aggressive Fund", n => {portfolioName= n; p = new Portfolio { Name = portfolioName };portfolioRepository. Stub(x => x.FindPortfolioByName(portfolioName)).Return(p);portfolioService. Stub(X => X.CreatePortfolio(p)).Throw(new ItemExistsException()); })
  • 29.
    Stubbing exampleCreate anew portfolio story.When("portfolio already exists in database", () => Assert.IsNotNull(portfolioRepository.FindPortfolioByName(portfolioName)) ).Then("new portfolio create should fail", () => Assert.Throws<ItemExistsException>(() => portfolioService.CreatePortfolio(p)) );
  • 30.
  • 31.
    Design starting withinterfaces (using stubs)
  • 32.
    Back fill withcode later  OutputAPI creationTest FirstBottom Up approach
  • 33.
    Lots of littlesteps working towards a solution   Output TestsUser Acceptance TestNBehavetest cases are compiledMust be created by developers or technical testersAre created at the start of the projectFitnesseUser Acceptance tests are Wiki based and so are dynamicCan be created by end users and business analystsCan be created at the start of the projectBut are only “implemented” by the development late in the SDLC
  • 34.
    Test Driven DevelopmentDevelopment/TestingPhasesStubsDomain ModelUser StoriesBehaviour Driven DevelopmentGUI TestingFitnessUser AcceptanceTestUnit & Component TestMocksImplemented BehaviourSystemIntegration TestNo Mocks/StubsDeployment Verification Test
  • 35.
    Fixtures to SpecificationsLoosingAssert from tests. Easier to read? For BAs, yes...Assert.IsTrue(component.IsValid) component.IsValid.ShouldBeTrue()Assert.Contains(s, “hello world”);s.ShouldContains(“hello world”);NBehave contains extension methods for NUnit, mbUnit, xUnit
  • 36.
    Fixtures to SpecificationsIsit necessary? [TestFixture] [Context][Test] [Specification] [Context]public class When_using_tokenized_stories{[Specification]public void should_replace_token_with_value(){}Stories for BDD. Specifications for focussed tests. The word Test has become a dirty word...
  • 37.
    Stories to documentationNBehave-Console.exePebbleSteps.NBehave.Stories.dll /o stories.txtTheme: Trade Compliance Story: Pretrade compliance check As a Trader I want verify a trade against the portfolio before I call the broker So that the portfolio does not move out of compliance Scenario: trade will move portfolio out of compliance Given portfolio with name Balanced Fund And asset allocation pie contains segments Cash 0.4, Stock 0.3, Property 0.3 And allocation pie 0.05 And portfolio contains Stock IBM 1, Cash GBP 1, Property SW5 1Hb 1, Stock BHP 1 When market prices are IBM 1, GBP 1, SW5 1Hb 1, BHP 1 Then portfolio value is 4 And portfolio constituents are Stock totalValue:2 percentOfPie:0.5 lower:0.25 upper:0.35, Cash totalValue:1 percentOfPie:0.25 lower:0.35 upper:0.45, Property totalValue:1 percentOfPie:0.25 lower:0.25 upper:0.35, And portfolio is balanced
  • 38.
  • 39.
    Still in beta…What’sleft to do?The parameter regular expression is on [a-z][A-Z]$example0, $example1 – In story output first parameter is printed twiceGallio integration/replacement of current story runnerCurrent story runner text output formatting is poorHTML or a XSLT for current XML outputOccassional crash in the parsing engine that links text to delegate parameters
  • 40.

Editor's Notes

  • #8 Lets dive into TDD and TFD. The famous Red, Green, Green...
  • #14 Welcome everyone on this cold winter night. This is my first Winter in London so you will have to excuse my scarf and gloves...My name is David Ross and I will be presenting with Chris Roff.Tonight we will be introducing Test Driven Development.
  • #22 Lets dive into TDD and TFD. The famous Red, Green, Green...
  • #29 Lets dive into TDD and TFD. The famous Red, Green, Green...