• Save
Behavior Driven Development - WPC 2011
Upcoming SlideShare
Loading in...5
×
 

Behavior Driven Development - WPC 2011

on

  • 1,098 views

Behavior Driven Development presentation held during WPC 2011 by Fabio Armani

Behavior Driven Development presentation held during WPC 2011 by Fabio Armani

Statistics

Views

Total Views
1,098
Views on SlideShare
1,084
Embed Views
14

Actions

Likes
5
Downloads
4
Comments
0

2 Embeds 14

http://www.linkedin.com 13
https://www.linkedin.com 1

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Behavior Driven Development - WPC 2011 Behavior Driven Development - WPC 2011 Presentation Transcript

  • BDDAn Agile Approach to New Development Fabio ArmaniTechnologies Certified Scrum Professional Professional ScrumMaster
  • Agenda What is BDD? _1 BDD Practices _2 Gherkin _3 Using Mocks _4 RSpec _5
  • Agenda What is BDD? _1 BDD Practices _2 Gherkin _3 Using Mocks _4 RSpec _5
  • What is BDD?
  • Behavior driven development• Behavior driven development (or BDD) is an agile software development technique that encourages collaboration between developers, QA and non-technical or business participants in a software project. – It was originally named in 2003 by Dan North as a response to Test Driven Development, including Acceptance Test or Customer Test Driven Development practices as found in Extreme Programming. – It has evolved over the last few years
  • BDD definition Behaviour-driven development is an “outside-in”methodology. It starts at the outside by identifying businessoutcomes, and then drills down into the feature set that will achieve those outcomes. Each feature is captured as a “story”, which defines the scope of the feature along with its acceptance criteria.
  • BDD definition• BDD is a second-generation, outside-in, pull-based, multiple- stakeholder, multiple-scale, high-automation, agile methodology.• It describes a cycle of interactions with well-defined outputs, resulting in the delivery of working, tested software that matters.
  • BDD definition• BDD focuses on obtaining a clear understanding of desired software behavior• It extends TDD by writing test cases in a natural language that non-programmers can read, through discussion with stakeholders.
  • Timeline UnitTest Test code automatically
  • TDD Write test firstTimeline UnitTest Test code automatically
  • BDD Dan North TDD Write test firstTimeline UnitTest Test code automatically
  • TDD Mantra 1. Write a failing test red TDD refactor green 3. Eliminate redundancy 2. Made the code work
  • Acceptance Test
  • How to use BDD in an iteration? Before we do something, we need to agree upon what we should deliver = before stories are accepted into the iteration, we define the acceptance criteria for the story Based on the acceptance criteria and our estimations, we include X number of stories to deliver in the iteration Important: we can’t commit to deliver something unless we know what to deliver = be thorough in splitting a story in acceptance criteria
  • BDD » Vocabulary * Focus on vocabulary - user stories - acceptance criteria Ubiquitous language!
  • BDD » Outside-in • Outside-in - onion - use the words of the user, not the programmer • Connection DDD - BDD: use ubiquitous language when specifying the user words • Unit-level tests are still needed
  • BDD » No silver bullet This is a tool in your toolbox. Use as needed.
  • BDD » The Holy Grail As said previously: The Holy Grail :) This is what I find the most interesting with the whole discussion about BDD. • executable specifications • focus on requirements • everything builds upon user stories/acceptance criteria
  • BDD » Tools Ruby: Cucumber, RSpec Java: JBehave, cuke4duke .NET: NBehave, cuke4nuke
  • “Behaviour” is a more useful word than “test”
  • BDD provides a “ubiquitous language” for analysis
  • Behavior Driven
  • Verify
  • Confidence
  • Design
  • Behavior
  • Characteristics of a good story• The title should describe an activity• The narrative should include a role, a feature and a benefit• The scenario title should say what’s different• The scenario should be described in terms of Givens, Events and Outcomes• The givens should define all of, and no more than, the required context• The event should describe the feature• The story should be small enough to fit in an iteration
  • User story template• In common use within the Dan North company there was already a story template that looked like this: As a [X] I want [Y] so that [Z] where Y is some feature, Z is the benefit or value of the feature, and X is the person (or role) who will benefit.
  • Acceptance Criteria• Answer the question: How will know when we are done?• High level criteria from the perspective of the user or stakeholder• There are Positive and Negative criteria• Collaborate with tester to create good acceptance criteria
  • Given-when-than Given some initial context (the givens), when an event occurs, then ensure some outcomes.
  • ATM user storyTitle: Customer withdraws cash As a customer, I want to withdraw cash from an ATM, so that I don’t have to wait in line at the bank
  • ATM user storyTitle: Customer withdraws cash BDD builds upon the conversation As a customer, taking place in user stories and acceptance criteria. I want to withdraw cash from an ATM, Context: comments for e.g. so that I don’t have to wait in line at the bankarticles on a news site
  • Scenarios• So how do we know when we have delivered this story?• There are several scenarios to consider: • the account may be in credit, • the account may be overdrawn but within the overdraft limit, • the account may be overdrawn beyond the overdraft limit.• Of course, there will be other scenarios, such as if the account is in credit but this withdrawal makes it overdrawn, or if the dispenser has insufficient cash.
  • Scenario 1• Using the given-when-then template, the first two scenarios might look like this: Scenario 1: Account is in credit Given the account is in credit And the card is valid And the dispenser contains cash When the customer requests cash Then ensure the account is debited And ensure cash is dispensed And ensure the card is returned
  • Scenario 2 Scenario 2: Account is overdrawn past the overdraft limit Acceptance criteria defines if the Given the account is overdrawn software is done And the card is valid One story – Many acceptance criteria When the customer requests cash Then ensure a rejection message is displayed This are only 2 of the possible And ensure cash is not dispensed acceptance criteria for the story And ensure the card is returned
  • Acceptance criteria should be executable
  • JBehave• The fragments of the scenario – the givens, event, and outcomes – are fine-grained enough to be represented directly in code.• JBehave defines an object model that enables us to directly map the scenario fragments to Java classes.
  • JBehave• You write a class representing each given: public class AccountIsInCredit implements Given { public void setup(World world) { … } } public class CardIsValid implements Given { public void setup(World world) { … } }
  • JBehave• And one for the event: public class CustomerRequestsCash implements Event { public void occurIn(World world) { … } }• And so on for the outcomes.
  • JBehave• JBehave then wires these all together and executes them.• It creates a “world,” which is just somewhere to store your objects, and passes it to each of the givens in turn so they can populate the world with known state.• JBehave then tells the event to “occur in” the world, which carries out the actual behaviour of the scenario.• Finally it passes control to any outcomes we have defined for the story.
  • JBehave• Having a class to represent each fragment enables us to reuse fragments in other scenarios or stories.• At first, the fragments are implemented using mocks to set an account to be in credit or a card to be valid.• These form the starting points for implementing behaviour.• As you implement the application, the givens and outcomes are changed to use the actual classes you have implemented, so that by the time the scenario is completed, they have become proper end- to-end functional tests.
  • BDD frameworks• Dan North created the first ever BDD framework, JBehave, followed by a story-level BDD framework for Ruby called RBehave which was later integrated into the RSpec project.• He also worked with David Chelimsky, Aslak Hellesøy and others to develop RSpec and also to write "The RSpec Book: Behaviour Driven Development with RSpec, Cucumber, and Friends".
  • BDD frameworks• The first story-based framework in RSpec was later replaced by Cucumber mainly developed by Aslak Hellesøy.• In 2008, Chris Matts, who was involved in the first discussions around BDD, came up with the idea of Feature Injection, allowing BDD to cover the analysis space and provide a full treatment of the software lifecycle from vision through to code and release.
  • Agenda What is BDD? _1 BDD Practices _2 Gherkin _3 Using Mocks _4 RSpec _5
  • Agenda What is BDD? _1 BDD Practices _2 Gherkin _3 Using Mocks _4 RSpec _5
  • BDD Practices
  • The practices of BDD• Establishing the goals of different stakeholders required for a vision to be implemented• Drawing out features which will achieve those goals using feature injection• Involving stakeholders in the implementation process through outside-in software development• Using examples to describe the behavior of the application, or of units of code• Automating those examples to provide quick feedback and regression testing• Using should when describing the behavior of software to help clarify responsibility and allow the softwares functionality to be questioned• Using ensure when describing responsibilities of software to differentiate outcomes in the scope of the code in question from side-effects of other elements of code.• Using mocks to stand-in for collaborating modules of code which have not yet been written
  • “Enough up-front thinking”
  • Outside-in 1/3• BDD is driven by business value; that is, the benefit to the business which accrues once the application is in production.• The only way in which this benefit can be realized is through the user interface(s) to the application, usually (but not always) a GUI.
  • Outside-in 2/3• In the same way, each piece of code, starting with the UI, can be considered a stakeholder of the other modules of code which it uses.• Each element of code provides some aspect of behavior which, in collaboration with the other elements, provides the application behavior.
  • Outside-in 3/3• The first piece of production code that BDD developers implement is the UI.• Developers can then benefit from quick feedback as to whether the UI looks and behaves appropriately.• Through code, and using principles of good design and refactoring, developers discover collaborators of the UI, and of every unit of code thereafter.• This helps them adhere to the principle of YAGNI, since each piece of production code is required either by the business, or by another piece of code already written.
  • Agenda What is BDD? _1 BDD Practices _2 Gherkin _3 Using Mocks _4 RSpec _5
  • Agenda What is BDD? _1 BDD Practices _2 Gherkin _3 Using Mocks _4 RSpec _5
  • GerkingApplication examples in the Gerking language
  • Gherkin• The requirements of a retail application might be, "Refunded or exchanged items should be returned to stock."• In BDD, a developer or QA engineer might clarify the requirements by breaking this down into specific examples.• The language of the following examples is called Gherkin and is used in cucumber for ruby, lettuce for python, specflow for dotnet and behat for php.
  • Scenario 1: Refunded items should be returned to stockGiven a customer previously bought a black sweater from meand I currently have three black sweaters left in stockwhen he returns the sweater for a refundthen I should have four black sweaters in stock
  • Scenario 2: Replaced items should be returned to stockGiven that a customer buys a blue garmentand I have two blue garments in stockand three black garments in stock.When he returns the garment for a replacement in black,Then I should have three blue garments in stockand two black garments in stock
  • Scenarios as exemplars• Each scenario is an exemplar, designed to illustrate a specific aspect of behavior of the application.• An exemplar, in the sense developed by philosopher of science Thomas Kuhn, is a well known usage of a scientific theory.
  • Scenarios as exemplars• When discussing the scenarios, participants question whether the outcomes described always result from those events occurring in the given context.• This can help to uncover further scenarios which clarify the requirements.• For instance, a domain expert noticing that refunded items are not always returned to stock might reword the requirements as "Refunded or replaced items should be returned to stock, unless faulty."
  • Given, when … then• This in turn helps participants to pin down the scope of requirements, which leads to better estimates of how long those requirements will take to implement.• The words Given, When and Then are often used to help drive out the scenarios, but are not mandated.• These scenarios can also be automated, if an appropriate tool exists to allow automation at the UI level.• If no such tool exists then it may be possible to automate at the next level in, i.e.: if an MVC design pattern has been used, the level of the Controller.
  • Programmer-domain examples and behavior• The same principles of examples, using contexts, events and outcomes are used to drive development at the level of abstraction of the programmer, as opposed to the business level.• For instance, the following examples describe an aspect of behavior of a list: Example 1: New lists are empty Given a new list Then the list should be empty. Example 2: Lists with things in them are not empty. Given a new list When we add an object Then the list should not be empty.
  • TDD Frameworks• Both these examples are required to describe the behavior of the list.isEmpty() method, and to derive the benefit of the method.• These examples are usually automated using TDD frameworks.• In BDD these examples are often encapsulated in a single method, with the name of the method being a complete description of the behavior.• Both examples are required for the code to be valuable, and encapsulating them in this way makes it easy to question, remove or change the behavior.
  • JUnit• For instance, using Java and JUnit 4, the above examples might become: public class ListTest { @Test public void shouldKnowWhetherItIsEmpty() { List list1 = new List(); assertTrue(list1.isEmpty()); List list2 = new List(); list2.add(new Object()); assertFalse(list2.isEmpty()); } }
  • Splitting• Other practitioners, particularly in the Ruby community, prefer to split these into two separate examples, based on separate contexts for when the list is empty or has items in.• This technique is based on Dave Astels practice, "One assertion per test".
  • • Sometimes the difference between the context, events and outcomes is made more explicit. For instance: public class WindowControlBehavior { @Test public void shouldCloseWindows() { // Given WindowControl control = new WindowControl("My AFrame"); AFrame frame = new AFrame(); // When control.closeWindow(); // Then ensureThat(!frame.isShowing()); } }
  • • However the example is phrased, the effect describes the behavior of the code in question.• For instance, from the examples above one can derive: • List should know when it is empty • WindowControl should close windows
  • Regression tests• The description is intended to be useful if the test fails, and to provide documentation of the codes behavior.• Once the examples have been written they are then run and the code implemented to make them work in the same way as TDD.• The examples then become part of the suite of regression tests.
  • Agenda What is BDD? _1 BDD Practices _2 Gherkin _3 Using Mocks _4 RSpec _5
  • Agenda What is BDD? _1 BDD Practices _2 Gherkin _3 Using Mocks _4 RSpec
  • Using Mocks A BDD framework
  • Using Mocks• BDD proponents claim that the use of "should" and "ensureThat" in BDD examples encourages developers to question whether the responsibilities theyre assigning to their classes are appropriate, or whether they can be delegated or moved to another class entirely.
  • Using Mocks• Practitioners use an object which is simpler than the collaborating code, and provides the same interface but more predictable behavior.• This is injected into the code which needs it, and examples of that codes behavior are written using this object instead of the production version.
  • Using Mocks• These objects can either be created by hand, or created using a mocking framework such as Mockito, Moq, NMock, Rhino Mocks, JMock or EasyMock.• Questioning responsibilities in this way, and using mocks to fulfill the required roles of collaborating classes, encourages the use of Role-based Interfaces.• It also helps to keep the classes small and loosely coupled.
  • Agenda What is BDD? _1 BDD Practices _2 Gherkin _3 Using Mocks _4 RSpec _5
  • Agenda What is BDD? _1 BDD Practices _2 Gherkin _3 Using Mocks _4 RSpec _5
  • RSpecA BDD framework
  • What are User Stories?• Acceptance Tests for RSpec• Describe the functionality of your application in terms your customer will understand• Prove that the application does what it is supposed to.
  • A Simple Authentication System• Write the feature• Write verification code for the feature• Specify the controller• Implement the controller• Specify the models• Implement the models• Verify the feature works as required• Refactor
  • Write our Feature• Write our feature and save it as features/allow-a-user-to- login.feature• Show it to the customer and have it approved• Run rake features
  • Feature: Allow a User to log in• As a user,• I want to log in,• So I can see my stuff• Scenario: Successful login • Given a user called Fabio with a password of secret • And 15 items of stuff • When I log in as Fabio with password secret • Then I should see the Dashboard page • And it should list my 15 items of stuff• Scenario: Unsuccessful login • Given a user called Fabio with a password of secret • When I log in as Fabio with password potato • Then I should see the Login page • And I should see a message saying “an incorrect username or password was supplied”
  • rake features• When we run ‘rake features’ it tells us that none of the features are implemented• So we start with the first step and implement that
  • Steps - proving a feature works• Create Ruby files, registration-steps.rb and session- steps.rb, in features/steps• These contain the code verifying that the feature works as expected
  • registration and session stepsGiven /^a user called (.*) with a password of (.*)$/ do | username, password | user = User.find_by_username username user.destroy unless user.nil? visits /registrations/new fills_in User name, :with => username fills_in Password, :with => password fills_in Password Confirmation, :with => password clicks_button RegisterendWhen /^I log in as (.*) with password (.*)$/ do | username, password | visits /sessions/new fills_in User name, :with => username fills_in Password, :with => password clicks_button Log inendThen /^I should see the Dashboard page$/ do response.should redirect_to(/dashboard)end
  • • ‘rake features’ fails• So we need to start writing some code to make it pass• But before we write any code, we need a specification• So we run… ruby script/generate rspec_controller Registrations …to build a blank controller and specification• Now to implement the RegistrationsController.• Similar work needs to be done with the SessionsController for actually logging in.
  • Which framework?
  • Conclusions• Behaviour-driven development uses a story as the basic unit of functionality, and therefore of delivery.• The acceptance criteria are an intrinsic part of the story – in effect they define the scope of its behaviour, and give us a shared definition of “done”.• They are also used as the basis for estimation when we come to do our planning.
  • Conclusions• Most importantly, the stories are the result of conversations between the project stakeholders, business analysts, testers and developers.• BDD is as much about the interactions between the various people in the project as it is about the outputs of the development process.
  • Future of BDD• The vision is to have a round-trip editor so that BAs and testers can capture stories in a regular text editor that can generate stubs for the behaviour classes, all in the language of the business domain.
  • Q&A
  • OverNet Education Contacts http://OverNetEducation.it Info@OverNetEducation.it Tel. +39 02 365738
  • Thanks!