SlideShare a Scribd company logo
Behaviour Driven Development
  and thinking about testing



           Malcolm Tredinnick
      malcolm.tredinnick@gmail.com
Why have I asked you here today?


     1) Testing landscape
     2) A different way to think about this
     3) Code
Chapter I: The Testing Landscape
Isolated   Integrated
Isolated                           Integrated


        Testing unit            External service
           size?                  availability
Mocks
                       Running time?
Mocks
●   Substitute for external systems & components
●   Need to be injected into the tests
    ●   “Monkey patching”
    ●   Dependency injection
Monkey patching


import socket

def setUp(...):
   socket.socket = DummySocketObject
   ...
Mocks
●   Substitute for external systems & components
●   Need to be injected into the tests
    ●   “Monkey patching”
    ●   Dependency injection
●   Need to be kept in synch with reality!
Isolated                    Integrated




           Infrastructure
ce
                                     n
                                e na
                             nt
                             ai
                            M
Isolated                           Integrated




           Infrastructure
Testing Strategies




   Some of many...
Testing Strategies
●   Formal verification
Testing Strategies
●   Formal verification
●   Test everything you can think of
Testing Strategies
●   Formal verification
●   Test everything you can think of
●   Anti-regression suite
      No bug fix without a test
Testing Strategies
●   Formal verification
●   Test everything you can think of
●   Anti-regression suite
●   Test driven development (TDD)
TDD


1.Write a (failing) test for next method or class
2.Write minimal code to make test pass
3.Rinse, wash, repeat.
Testing Strategies
●   Formal verification
●   Test everything you can think of
●   Anti-regression suite
●   Test driven development (TDD)
      “Specification, not verification”
Testing Strategies
●   Formal verification
●   Test everything you can think of
●   Anti-regression suite
●   Test driven development (TDD)
●   Documentation driven development (DDD?)
Testing Strategies
●   Formal verification
●   Test everything you can think of
●   Anti-regression suite
●   Test driven development (TDD)
●   Documentation driven development (DDD?)
●   Behaviour driven development (BDD)
Chapter II: A different way of thinking
Interlude: Creating systems...
Interlude: Creating systems...



          Specification
Interlude: Creating systems...

        Specification




                    Implementation

         Testing
Specification

●   On (e-)paper?
    ●   quick sketch
    ●   formal requirements document
    ●   mailing list discussion
●   In your head?
Specification



●   Capturing the idea is probably good
●   “What was I thinking smoking when...?”
Specification


As a [user or role],

I want [feature]

so that [something happens]
Specification


As a maze creator,

I want to be able to specify dimensions

so that a new maze of the given size is created.
BDD



What is the next most important
thing the code should do?
BDD



     What is the next most important
     thing the code should do?



Be able to
test this...              ... then implement it.
Scenario


Given that [initial context],

if and when [some event occurs]

then [ensure some outcomes]
Use case versus scenario


As a [user or role],          Given that [initial context],

I want [feature]              if and when [some event occurs]

so that [something happens]   then [ensure some outcomes]
Chapter III: Concrete code
Interlude: Naming things


 Language helps guide our brain.
 Focuses the mind.
 Perhaps too exclusively.
Interlude: Naming things


The Sapir-Whorf Hypothesis:
“[...] the structure of a language affects the ways in
which its speakers are able to conceptualise their
world [view].”
Example #1: Python's unittest module
Test titles
class BasicFieldTests (TestCase):
  def test_field_name (self):
    ...


  def test_show_hidden_initial (self):
    ...
Test titles
class Fields (TestCase):
  def should_allow_name_override (self):
     ...


class ChoiceFields (TestCase):
  def should_permit_initial_values_in_hidden_widgets (self):
     ...
Run new test titles


Write a load_test() method to pull out
all the “should” methods.

(Easy enough, but a few lines of code.)
Matching to scenarios
●   Typically, end up creating more classes than
    unittests (not a bad thing; classes are “free”).
    ●   Thinking about test names helps with class names
        and roles.
●   Context setup is done in setUp() method.
●   Normal unittest assertions work fairly cleanly.
Example #2: Doctests
Narrative style testing
Jane created a new maze with a small (5 x 5) size.

>>> from maze import Maze
>>> maze = Maze(5, 5)

Spot, her dog, did not think the new maze was the right size, but
Jane was able to convince him like this:

>>> maze.x_size
5
>>> maze.y_size
5

They found the entry and exit locations in their new maze:

>>>maze.entry_cell
(0, 0, “left”)

(etc)
Narrative style testing
●   Excellent if you are truly writing a narrative.
●   Can be difficult to maintain (but not always).
●   Avoid if large amounts of setup required.
●   Use with caution. Do use. Do not abuse.
Example #3: Domain specific languages
DSL packages



●   Lettuce
●   Freshen


                  Both available through PyPI
Freshen example


Scenario: Divide regular numbers
  Given I have entered 3 into the calculator
  And I have entered 2 into the calculator
  When I press divide
  Then the result should be 1.5 on the screen




                        (Code samples from Freshen documentation)
Backing code

from freshen import *

import calculator

@Before
def before(unused):
    scc.calc = calculator.Calculator()
    scc.result = None

@Given("I have entered (d+) into the calculator")
def enter(num):
    scc.calc.push(int(num))


                         (Code samples from Freshen documentation)
Backing code


@When("I press (w+)")
def press(button):
    op = getattr(scc.calc, button)
    scc.result = op()

@Then("the result should be (.*) on the screen")
def check_result(value):
    assert_equal(str(scc.result), value)




                        (Code samples from Freshen documentation)
Freshen templated example
Scenario Outline: Add two numbers
  Given I have entered <input_1> into the calculator
  And I have entered <input_2> into the calculator
  When I press <button>
  Then the result should be <output> on the screen


Examples:
  | input_1 | input_2 | button | output |
  | 20      | 30      | add    | 50         |
  | 2       | 5       | add    | 7          |
  | 0       | 40      | add    | 40         |


                          (Code samples from Freshen documentation)
Conclusions(?)
●   Behavioural tests are worth trying
●   Question the way you think from time to time
●   Are your tests' purpose clear to future you?
https://github.com/malcolmt/bdd-and-testing-talk




            malcolm.tredinnick@gmail.com
                     @malcolmt

More Related Content

PDF
Test Driven Development
Valerio Maggio
 
PDF
Unit testing and scaffolding
Valerio Maggio
 
PDF
Unit testing with Junit
Valerio Maggio
 
PDF
How and what to unit test
Eugenio Lentini
 
PPTX
Junit 4.0
pallavikhandekar212
 
PDF
Working With Legacy Code
Andrea Polci
 
PDF
Unit Testing Best Practices
Tomaš Maconko
 
PPTX
Java Unit Test and Coverage Introduction
Alex Su
 
Test Driven Development
Valerio Maggio
 
Unit testing and scaffolding
Valerio Maggio
 
Unit testing with Junit
Valerio Maggio
 
How and what to unit test
Eugenio Lentini
 
Working With Legacy Code
Andrea Polci
 
Unit Testing Best Practices
Tomaš Maconko
 
Java Unit Test and Coverage Introduction
Alex Su
 

What's hot (20)

PPTX
JUNit Presentation
Animesh Kumar
 
PPTX
Benefit From Unit Testing In The Real World
Dror Helper
 
PPTX
Unit testing
Panos Pnevmatikatos
 
PPTX
Working Effectively with Legacy Code
Orbit One - We create coherence
 
PPTX
Java Unit Testing
Nayanda Haberty
 
PPT
05 junit
mha4
 
PPTX
Introduction To J unit
Olga Extone
 
PPTX
Tdd pecha kucha_v2
Paul Boos
 
PDF
Unit Testing Done Right
Brian Fenton
 
PDF
Unit testing, principles
Renato Primavera
 
PDF
Journey's diary developing a framework using tdd
eduardomg23
 
PPTX
Unit Testing in Java
Ahmed M. Gomaa
 
PDF
Clean Unit Test Patterns
Frank Appel
 
PPTX
Test Driven Development
Dennis van der Stelt
 
PDF
JUnit 5
Scott Leberknight
 
PPTX
Test driven development in .Net - 2010 + Eclipse
UTC Fire & Security
 
PPS
JUnit Presentation
priya_trivedi
 
PDF
Developer Tests - Things to Know (Vilnius JUG)
vilniusjug
 
PPTX
An Introduction to Unit Testing
Joe Tremblay
 
PPT
Xp Day 080506 Unit Tests And Mocks
guillaumecarre
 
JUNit Presentation
Animesh Kumar
 
Benefit From Unit Testing In The Real World
Dror Helper
 
Unit testing
Panos Pnevmatikatos
 
Working Effectively with Legacy Code
Orbit One - We create coherence
 
Java Unit Testing
Nayanda Haberty
 
05 junit
mha4
 
Introduction To J unit
Olga Extone
 
Tdd pecha kucha_v2
Paul Boos
 
Unit Testing Done Right
Brian Fenton
 
Unit testing, principles
Renato Primavera
 
Journey's diary developing a framework using tdd
eduardomg23
 
Unit Testing in Java
Ahmed M. Gomaa
 
Clean Unit Test Patterns
Frank Appel
 
Test Driven Development
Dennis van der Stelt
 
Test driven development in .Net - 2010 + Eclipse
UTC Fire & Security
 
JUnit Presentation
priya_trivedi
 
Developer Tests - Things to Know (Vilnius JUG)
vilniusjug
 
An Introduction to Unit Testing
Joe Tremblay
 
Xp Day 080506 Unit Tests And Mocks
guillaumecarre
 
Ad

Similar to Behaviour Driven Development and Thinking About Testing (20)

PDF
Writing Tests with the Unity Test Framework
Peter Kofler
 
PPTX
Tdd is not about testing (OOP)
Gianluca Padovani
 
PPTX
TDD Best Practices
Attila Bertók
 
PDF
PresentationqwertyuiopasdfghUnittest.pdf
kndemo34
 
PDF
TDD in Python With Pytest
Eddy Reyes
 
PPTX
Tdd is not about testing (C++ version)
Gianluca Padovani
 
PDF
Tdd in practice
Andrew Meredith
 
PDF
Unit Testing like a Pro - The Circle of Purity
Victor Rentea
 
PDF
TDD and Simple Design Workshop - Session 1 - March 2019
Paulo Clavijo
 
PPTX
Unit Testing and TDD 2017
Xavi Hidalgo
 
PDF
Python and test
Micron Technology
 
PDF
TDD reloaded - JUGTAA 24 Ottobre 2012
Pietro Di Bello
 
PDF
Testing Django Applications
Honza Král
 
PDF
Test Driven Development en Go con Ginkgo y Gomega
Software Guru
 
PPT
Unit testing
Murugesan Nataraj
 
PDF
TDD Flow: The Mantra in Action
Dionatan default
 
PDF
Tdd is not about testing
Gianluca Padovani
 
PDF
It's all about behaviour, also in php - phpspec
Giulio De Donato
 
ODP
Debugging
Olivier Teytaud
 
PDF
[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...
DevDay Da Nang
 
Writing Tests with the Unity Test Framework
Peter Kofler
 
Tdd is not about testing (OOP)
Gianluca Padovani
 
TDD Best Practices
Attila Bertók
 
PresentationqwertyuiopasdfghUnittest.pdf
kndemo34
 
TDD in Python With Pytest
Eddy Reyes
 
Tdd is not about testing (C++ version)
Gianluca Padovani
 
Tdd in practice
Andrew Meredith
 
Unit Testing like a Pro - The Circle of Purity
Victor Rentea
 
TDD and Simple Design Workshop - Session 1 - March 2019
Paulo Clavijo
 
Unit Testing and TDD 2017
Xavi Hidalgo
 
Python and test
Micron Technology
 
TDD reloaded - JUGTAA 24 Ottobre 2012
Pietro Di Bello
 
Testing Django Applications
Honza Král
 
Test Driven Development en Go con Ginkgo y Gomega
Software Guru
 
Unit testing
Murugesan Nataraj
 
TDD Flow: The Mantra in Action
Dionatan default
 
Tdd is not about testing
Gianluca Padovani
 
It's all about behaviour, also in php - phpspec
Giulio De Donato
 
Debugging
Olivier Teytaud
 
[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...
DevDay Da Nang
 
Ad

More from dn (8)

PDF
Code quality; patch quality
dn
 
PDF
How does this code work?
dn
 
PDF
Python worst practices
dn
 
ODP
Struggling to find an open source business model
dn
 
PDF
Testing in those hard to reach places
dn
 
ODP
Automated testing in Python and beyond
dn
 
ODP
Patterns in Python
dn
 
PDF
Spotlight on Python
dn
 
Code quality; patch quality
dn
 
How does this code work?
dn
 
Python worst practices
dn
 
Struggling to find an open source business model
dn
 
Testing in those hard to reach places
dn
 
Automated testing in Python and beyond
dn
 
Patterns in Python
dn
 
Spotlight on Python
dn
 

Recently uploaded (20)

PDF
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
PDF
Get More from Fiori Automation - What’s New, What Works, and What’s Next.pdf
Precisely
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PDF
AI-Cloud-Business-Management-Platforms-The-Key-to-Efficiency-Growth.pdf
Artjoker Software Development Company
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
PDF
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
PDF
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PPTX
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
PDF
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
PDF
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
PDF
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
PDF
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
PDF
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
PPTX
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
PDF
Brief History of Internet - Early Days of Internet
sutharharshit158
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
Get More from Fiori Automation - What’s New, What Works, and What’s Next.pdf
Precisely
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
AI-Cloud-Business-Management-Platforms-The-Key-to-Efficiency-Growth.pdf
Artjoker Software Development Company
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
Brief History of Internet - Early Days of Internet
sutharharshit158
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 

Behaviour Driven Development and Thinking About Testing

  • 1. Behaviour Driven Development and thinking about testing Malcolm Tredinnick [email protected]
  • 2. Why have I asked you here today? 1) Testing landscape 2) A different way to think about this 3) Code
  • 3. Chapter I: The Testing Landscape
  • 4. Isolated Integrated
  • 5. Isolated Integrated Testing unit External service size? availability Mocks Running time?
  • 6. Mocks ● Substitute for external systems & components ● Need to be injected into the tests ● “Monkey patching” ● Dependency injection
  • 7. Monkey patching import socket def setUp(...): socket.socket = DummySocketObject ...
  • 8. Mocks ● Substitute for external systems & components ● Need to be injected into the tests ● “Monkey patching” ● Dependency injection ● Need to be kept in synch with reality!
  • 9. Isolated Integrated Infrastructure
  • 10. ce n e na nt ai M Isolated Integrated Infrastructure
  • 11. Testing Strategies Some of many...
  • 12. Testing Strategies ● Formal verification
  • 13. Testing Strategies ● Formal verification ● Test everything you can think of
  • 14. Testing Strategies ● Formal verification ● Test everything you can think of ● Anti-regression suite No bug fix without a test
  • 15. Testing Strategies ● Formal verification ● Test everything you can think of ● Anti-regression suite ● Test driven development (TDD)
  • 16. TDD 1.Write a (failing) test for next method or class 2.Write minimal code to make test pass 3.Rinse, wash, repeat.
  • 17. Testing Strategies ● Formal verification ● Test everything you can think of ● Anti-regression suite ● Test driven development (TDD) “Specification, not verification”
  • 18. Testing Strategies ● Formal verification ● Test everything you can think of ● Anti-regression suite ● Test driven development (TDD) ● Documentation driven development (DDD?)
  • 19. Testing Strategies ● Formal verification ● Test everything you can think of ● Anti-regression suite ● Test driven development (TDD) ● Documentation driven development (DDD?) ● Behaviour driven development (BDD)
  • 20. Chapter II: A different way of thinking
  • 23. Interlude: Creating systems... Specification Implementation Testing
  • 24. Specification ● On (e-)paper? ● quick sketch ● formal requirements document ● mailing list discussion ● In your head?
  • 25. Specification ● Capturing the idea is probably good ● “What was I thinking smoking when...?”
  • 26. Specification As a [user or role], I want [feature] so that [something happens]
  • 27. Specification As a maze creator, I want to be able to specify dimensions so that a new maze of the given size is created.
  • 28. BDD What is the next most important thing the code should do?
  • 29. BDD What is the next most important thing the code should do? Be able to test this... ... then implement it.
  • 30. Scenario Given that [initial context], if and when [some event occurs] then [ensure some outcomes]
  • 31. Use case versus scenario As a [user or role], Given that [initial context], I want [feature] if and when [some event occurs] so that [something happens] then [ensure some outcomes]
  • 33. Interlude: Naming things Language helps guide our brain. Focuses the mind. Perhaps too exclusively.
  • 34. Interlude: Naming things The Sapir-Whorf Hypothesis: “[...] the structure of a language affects the ways in which its speakers are able to conceptualise their world [view].”
  • 35. Example #1: Python's unittest module
  • 36. Test titles class BasicFieldTests (TestCase): def test_field_name (self): ... def test_show_hidden_initial (self): ...
  • 37. Test titles class Fields (TestCase): def should_allow_name_override (self): ... class ChoiceFields (TestCase): def should_permit_initial_values_in_hidden_widgets (self): ...
  • 38. Run new test titles Write a load_test() method to pull out all the “should” methods. (Easy enough, but a few lines of code.)
  • 39. Matching to scenarios ● Typically, end up creating more classes than unittests (not a bad thing; classes are “free”). ● Thinking about test names helps with class names and roles. ● Context setup is done in setUp() method. ● Normal unittest assertions work fairly cleanly.
  • 41. Narrative style testing Jane created a new maze with a small (5 x 5) size. >>> from maze import Maze >>> maze = Maze(5, 5) Spot, her dog, did not think the new maze was the right size, but Jane was able to convince him like this: >>> maze.x_size 5 >>> maze.y_size 5 They found the entry and exit locations in their new maze: >>>maze.entry_cell (0, 0, “left”) (etc)
  • 42. Narrative style testing ● Excellent if you are truly writing a narrative. ● Can be difficult to maintain (but not always). ● Avoid if large amounts of setup required. ● Use with caution. Do use. Do not abuse.
  • 43. Example #3: Domain specific languages
  • 44. DSL packages ● Lettuce ● Freshen Both available through PyPI
  • 45. Freshen example Scenario: Divide regular numbers Given I have entered 3 into the calculator And I have entered 2 into the calculator When I press divide Then the result should be 1.5 on the screen (Code samples from Freshen documentation)
  • 46. Backing code from freshen import * import calculator @Before def before(unused): scc.calc = calculator.Calculator() scc.result = None @Given("I have entered (d+) into the calculator") def enter(num): scc.calc.push(int(num)) (Code samples from Freshen documentation)
  • 47. Backing code @When("I press (w+)") def press(button): op = getattr(scc.calc, button) scc.result = op() @Then("the result should be (.*) on the screen") def check_result(value): assert_equal(str(scc.result), value) (Code samples from Freshen documentation)
  • 48. Freshen templated example Scenario Outline: Add two numbers Given I have entered <input_1> into the calculator And I have entered <input_2> into the calculator When I press <button> Then the result should be <output> on the screen Examples: | input_1 | input_2 | button | output | | 20 | 30 | add | 50 | | 2 | 5 | add | 7 | | 0 | 40 | add | 40 | (Code samples from Freshen documentation)
  • 49. Conclusions(?) ● Behavioural tests are worth trying ● Question the way you think from time to time ● Are your tests' purpose clear to future you?