SlideShare uma empresa Scribd logo
1 de 29
Baixar para ler offline
Better Testing Through Behaviour
        Open Source Developers’ Conference
                  November 2007


                  Tom Adams
                  Workingmouse
“The act of writing a unit test is more an act of design than of
verification. It’s also more an act of documentation than of verification.
The act of writing a unit test closes a remarkable number of feedback
loops, the least of which is the one pertaining to verification of
function.”

Robert C. Martin
Why do I care?
I. Better process

  •Workflow is easier, IDE-a-bility, simpler
  •Supporting infrastructure & language that guides you down the correct path
II. Better results

  •Splitting of state into separate contexts means understanding
  •Nicer syntax, less code to mentally parse
  •Readable results
Test driven development
•Development practice, arising out of XP’s test first approach
•Incremental process - test, code, refactor, test code, refactor…
•Drives implementation - improved quality, low coupling, high cohesion
•Comprehensive regression test suite
•Focus on design?
•Focus on documentation?
•Focus on behaviour?
Problems?
•Too much time/money, optional extra
•Overlapping with traditional QA testers
•Developers require training
•Developer resistance
•Vocabulary difference
Problems?
•Test vocabulary affects thinking
•Intent not clear
•Design focus obscured
•Documentation
•1-1 mapping of test/production code
•Tight tests coupled to code
•Repetitive infrastructure setup
•Where to start?
BDD is just TDD
•Coined by Dan North - JBehave first BDD framework
•Development practice, arising out agile methodologies
•Refinement of TDD that shifts the emphasis from testing to specification
•Frameworks - JBehave, RSpec, Instinct, JDave, NSpec, GSpec, beanSpec, JSSpec, DSpec,
   MissingBDD, PHPSpec, Specs, Specipy
class ACsvFileReaderWithNothingToRead {
  @Subject CsvFileReader csvFileReader;
  @Mock CsvFile csvFile;
  @Stub CsvLine[] noLines;

    @Specification
    void returnsNoLines() {
      expect.that(new Expectations() {{
        one(csvFile).hasMoreLines(); will(returnValue(false));
        ignoring(csvFile).close();
      }});
      expect.that(csvFileReader.readLines()).equalTo(noLines);
    }
}
class AnEmptyStack {
  @Subject Stack<Object> stack;
  @Dummy Object object;

    @Specification
    void isEmpty() {
      expect.that(stack.isEmpty()).isTrue();
    }

    @Specification
    void isNoLongerBeEmptyAfterPush() {
      stack.push(object);
      expect.that(stack.isEmpty()).isFalse();
    }

    @Specification(expectedException = IllegalStateException.class,
        withMessage = quot;Cannot pop an empty stackquot;)
    void throwsExceptionWhenPopped() {
      stack.pop();
    }
}
AnEmptyStack
 - isEmpty
 - isNoLongerBeEmptyAfterPush
 - throwsExceptionWhenPopped
ANonEmptyStack
 - isNotEmpty
 - isNoLongerFullAfterPoppingAllElements
 - throwsExceptionWhenANullIsPushed
 - popsPushedValue
 - shouldPopSecondPushedValueFirst
 - leavesValueOnStackAfterPeek
Ubiquitous language
•Language has an impact on how you think about something
•Known in linguistics as the Sapir-Whorf hypothesis
•There is “a systematic relationship between the grammatical categories of the language
     a person speaks and how that person both understands the world and behaves in it”

•The language used to describe software constructs has an impact on how we create those
   constructs, e.g. good APIs, well named variables
Ubiquitous language
•Getting the words right - naming of classes, methods and variables
•Borrows from domain driven development (DDD)
•Bridges gap between technical and business artefacts
•Captures the behaviour of the domain using clear and concise syntax
•Forms consensus around domain artefacts and run-time behaviour
private void testRunnerSendsSpecifiationResultsToOutput() {
  assertTrue(quot;Expected to find context namequot;,
      runnerOutput.contains(className));
}


private void sendsSpecifiationResultsToOutput() {
  expect.that(runnerOutput).containsString(className);
}
assertEquals(1, map.size());
assertTrue(map.containsKey(1000));
assertEquals(fileNames, map.get(1000));


expect.that(map).hasSize(1);
expect.that(map).containsKey(1000);
expect.that(map).containsEntry(1000, fileNames);
public void testMethodIsAnnotated() {
  checkIsAnnotated(WithRuntimeAnnotations.class, Context.class, true);
  checkIsAnnotated(WithoutRuntimeAnnotations.class,
    Context.class, false);
}

private void checkIsAnnotated(AnnotatedElement element,
      Class<?> expectedAnnotation, boolean expectingAnnotation) {
  AnnotationChecker annotationChecker = new AnnotationCheckerImpl();
  assertEquals(expectingAnnotation,
      annotationChecker.isAnnotated(element, expectedAnnotation));
}
public void testClassIsAnnotated() {
  expect.that(annotationChecker.isAnnotated(
      WithRuntimeAnnotations.class, Context.class)).isTrue();
  expect.that(annotationChecker.isAnnotated(
      WithoutRuntimeAnnotations.class, Context.class)).isFalse();
}
Design focus
•Design is one of the most important aspect of TDD
•TDD’d code is (usually of) higher quality that non-TDD’d code
•Bugs, coupling, cohesion, maintainability, understandable, smaller, etc.
•Emphasis on testing limits TDD’s uptake & effectiveness
•Organisational, technical, process
•Encourages you to think about design
•Design is documented through ubiquitous language, contexts
Behaviour focus
•Focused specifications
•One context per “state” of subject
•Minimal expectations per specification method
Behaviour focus
•1-to-1 test-to-prod code mapping broken
•“Units” gone, what’s important is the behaviour
•Specification code is less coupled to production code
•Easier refactoring
•M-to-N mapping encouraged
class AnEmptyStack {
  void isEmpty() {}
  void isNoLongerBeEmptyAfterPush() {}
  void throwsExceptionWhenPopped() {}
}

class ANonEmptyStack {
  void isNotEmpty() {}
  void throwsExceptionWhenANullIsPushed() {}
  void popsPushedValue() {}
  void shouldPopSecondPushedValueFirst() {}
  void leavesValueOnStackAfterPeek() {}
}
Process
•Works best top-down/outside-in
•Specify at the highest level first
•Use top-level objects to discover the services needed from the next level down
•Rinse, repeat
Levels
•Story-level
•Code-level
•Mostly historical, frameworks are now adopting both approaches
•Both levels are legitimate, use one or the other depending on audience
Scenario quot;transfer from savings account to cheque acountquot; do
  Given quot;my savings account balance isquot;, 100 do |balance|
    @savings_account = Accounts::AccountFactory.create(:savings)
    @savings_account.add(balance)
  end
  And quot;my cheque account balance isquot;, 50 do |balance|
    @cheque_account = Accounts::AccountFactory.create(:cheque)
    @cheque_account.add(balance)
  end
  When quot;I transferquot;, 20 do |amount|
    @savings_account.transfer(amount.to_i).to(@cheque_account)
  end
  Then quot;my savings account balance should bequot;, 80 do |balance|
    @savings_account.balance.should == balance
  end
  And quot;my cheque account balance should bequot;, 70 do |balance|
    @cheque_account.balance.should == balance
  end
end
describe quot;non-empty Stackquot; do
  it quot;should return the top item when sent #peekquot; do
    @stack.peek.should == @last_item_added
  end
end

class ANonEmptyStack {
  void shouldReturnTheTopItemWhenSentPeek() {
    expect.that(stack.peek()).equalTo(lastItemAdded);
  }
}
Instinct
•Goals - explicitness, simplicity and flexibility
•Code-level (currently) framework
•Unified state and behaviour (mocking) expectation API (c.f. xUnit Assert)
•Built in infrastructure - mocks, stubs, dummies, subjects
•Formalised nomenclature
•Integration - JUnit, Ant, Clover, IntelliJ IDEA
Instinct examples
Summary
•Shifts the emphasis from testing to specification
•Provides a ubiquitous language
•Strong focus on design
•Emphasises system behaviour, independent of where the behaviour resides
Take home
I. Better process

  •Workflow is easier, IDE-a-bility, simpler
  •Supporting infrastructure & language that guides you down the correct path
II. Better results

  •Splitting of state into separate contexts means understanding
  •Nicer syntax, less code to mentally parse
  •Readable results
References
•http://en.wikipedia.org/wiki/Behavior_driven_development
•http://blog.daveastels.com/2005/07/05/a-new-look-at-test-driven-development
•http://blog.davidchelimsky.net/files/BDDWithRspec.RubyConf.2007.pdf
•http://code.google.com/p/instinct/
•http://rspec.rubyforge.org/

Mais conteúdo relacionado

Semelhante a Better Testing Through Behaviour

Measuring Your Code
Measuring Your CodeMeasuring Your Code
Measuring Your CodeNate Abele
 
Measuring Your Code 2.0
Measuring Your Code 2.0Measuring Your Code 2.0
Measuring Your Code 2.0Nate Abele
 
Testing Sap: Modern Methodology
Testing Sap: Modern MethodologyTesting Sap: Modern Methodology
Testing Sap: Modern MethodologyEthan Jewett
 
What have the annotations done to us?
What have the annotations done to us?What have the annotations done to us?
What have the annotations done to us?Adam Warski
 
PHX Session #1: Development Best Practices And How Microsoft Helps
PHX Session #1: Development  Best  Practices And  How  Microsoft  HelpsPHX Session #1: Development  Best  Practices And  How  Microsoft  Helps
PHX Session #1: Development Best Practices And How Microsoft HelpsSteve Lange
 
PVS-Studio and static code analysis technique
PVS-Studio and static code analysis techniquePVS-Studio and static code analysis technique
PVS-Studio and static code analysis techniqueAndrey Karpov
 
resolvendo problemas de comunicação em equipes distribuídas com bdd
resolvendo problemas de comunicação em equipes distribuídas com bddresolvendo problemas de comunicação em equipes distribuídas com bdd
resolvendo problemas de comunicação em equipes distribuídas com bddRodrigo Urubatan
 
Smart Client Development
Smart Client DevelopmentSmart Client Development
Smart Client DevelopmentTamir Khason
 
Just Java2007 - Daniel Wildt - Tools For Java Test Automation
Just Java2007 - Daniel Wildt - Tools For Java Test AutomationJust Java2007 - Daniel Wildt - Tools For Java Test Automation
Just Java2007 - Daniel Wildt - Tools For Java Test AutomationDaniel Wildt
 
It's all about behaviour, also in php - phpspec
It's all about behaviour, also in php - phpspecIt's all about behaviour, also in php - phpspec
It's all about behaviour, also in php - phpspecGiulio De Donato
 
Language-Oriented Programming and Language Workbenches: Building Domain Langu...
Language-Oriented Programming and Language Workbenches: Building Domain Langu...Language-Oriented Programming and Language Workbenches: Building Domain Langu...
Language-Oriented Programming and Language Workbenches: Building Domain Langu...elliando dias
 
Topics in Verification: Reuse, Coverage, Regression Engineering, Planning, Qu...
Topics in Verification: Reuse, Coverage, Regression Engineering, Planning, Qu...Topics in Verification: Reuse, Coverage, Regression Engineering, Planning, Qu...
Topics in Verification: Reuse, Coverage, Regression Engineering, Planning, Qu...DVClub
 
Rubyconf2016 - Solving communication problems in distributed teams with BDD
Rubyconf2016 - Solving communication problems in distributed teams with BDDRubyconf2016 - Solving communication problems in distributed teams with BDD
Rubyconf2016 - Solving communication problems in distributed teams with BDDRodrigo Urubatan
 
Selected Sessions from RailsConf 2007
Selected Sessions from RailsConf 2007Selected Sessions from RailsConf 2007
Selected Sessions from RailsConf 2007Jerry Richardson
 
2022 - Delivering Powerful Technical Presentations.pdf
2022 - Delivering Powerful Technical Presentations.pdf2022 - Delivering Powerful Technical Presentations.pdf
2022 - Delivering Powerful Technical Presentations.pdfWesley Reisz
 
Programming Paradigms
Programming ParadigmsProgramming Paradigms
Programming ParadigmsJaneve George
 

Semelhante a Better Testing Through Behaviour (20)

Measuring Your Code
Measuring Your CodeMeasuring Your Code
Measuring Your Code
 
Measuring Your Code 2.0
Measuring Your Code 2.0Measuring Your Code 2.0
Measuring Your Code 2.0
 
Testing Sap: Modern Methodology
Testing Sap: Modern MethodologyTesting Sap: Modern Methodology
Testing Sap: Modern Methodology
 
What have the annotations done to us?
What have the annotations done to us?What have the annotations done to us?
What have the annotations done to us?
 
BDD in my team: how we do it
BDD in my team: how we do itBDD in my team: how we do it
BDD in my team: how we do it
 
PHX Session #1: Development Best Practices And How Microsoft Helps
PHX Session #1: Development  Best  Practices And  How  Microsoft  HelpsPHX Session #1: Development  Best  Practices And  How  Microsoft  Helps
PHX Session #1: Development Best Practices And How Microsoft Helps
 
PVS-Studio and static code analysis technique
PVS-Studio and static code analysis techniquePVS-Studio and static code analysis technique
PVS-Studio and static code analysis technique
 
resolvendo problemas de comunicação em equipes distribuídas com bdd
resolvendo problemas de comunicação em equipes distribuídas com bddresolvendo problemas de comunicação em equipes distribuídas com bdd
resolvendo problemas de comunicação em equipes distribuídas com bdd
 
Smart Client Development
Smart Client DevelopmentSmart Client Development
Smart Client Development
 
Just Java2007 - Daniel Wildt - Tools For Java Test Automation
Just Java2007 - Daniel Wildt - Tools For Java Test AutomationJust Java2007 - Daniel Wildt - Tools For Java Test Automation
Just Java2007 - Daniel Wildt - Tools For Java Test Automation
 
It's all about behaviour, also in php - phpspec
It's all about behaviour, also in php - phpspecIt's all about behaviour, also in php - phpspec
It's all about behaviour, also in php - phpspec
 
Practical Groovy DSL
Practical Groovy DSLPractical Groovy DSL
Practical Groovy DSL
 
Mpg Feb08 Gian Lorenzetto
Mpg Feb08 Gian Lorenzetto Mpg Feb08 Gian Lorenzetto
Mpg Feb08 Gian Lorenzetto
 
Language-Oriented Programming and Language Workbenches: Building Domain Langu...
Language-Oriented Programming and Language Workbenches: Building Domain Langu...Language-Oriented Programming and Language Workbenches: Building Domain Langu...
Language-Oriented Programming and Language Workbenches: Building Domain Langu...
 
Topics in Verification: Reuse, Coverage, Regression Engineering, Planning, Qu...
Topics in Verification: Reuse, Coverage, Regression Engineering, Planning, Qu...Topics in Verification: Reuse, Coverage, Regression Engineering, Planning, Qu...
Topics in Verification: Reuse, Coverage, Regression Engineering, Planning, Qu...
 
Rubyconf2016 - Solving communication problems in distributed teams with BDD
Rubyconf2016 - Solving communication problems in distributed teams with BDDRubyconf2016 - Solving communication problems in distributed teams with BDD
Rubyconf2016 - Solving communication problems in distributed teams with BDD
 
Selected Sessions from RailsConf 2007
Selected Sessions from RailsConf 2007Selected Sessions from RailsConf 2007
Selected Sessions from RailsConf 2007
 
2022 - Delivering Powerful Technical Presentations.pdf
2022 - Delivering Powerful Technical Presentations.pdf2022 - Delivering Powerful Technical Presentations.pdf
2022 - Delivering Powerful Technical Presentations.pdf
 
Programming Paradigms
Programming ParadigmsProgramming Paradigms
Programming Paradigms
 
Object
ObjectObject
Object
 

Último

0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdf0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdfRenandantas16
 
Catalogue ONG NUOC PPR DE NHAT .pdf
Catalogue ONG NUOC PPR DE NHAT      .pdfCatalogue ONG NUOC PPR DE NHAT      .pdf
Catalogue ONG NUOC PPR DE NHAT .pdfOrient Homes
 
Catalogue ONG NƯỚC uPVC - HDPE DE NHAT.pdf
Catalogue ONG NƯỚC uPVC - HDPE DE NHAT.pdfCatalogue ONG NƯỚC uPVC - HDPE DE NHAT.pdf
Catalogue ONG NƯỚC uPVC - HDPE DE NHAT.pdfOrient Homes
 
Creating Low-Code Loan Applications using the Trisotech Mortgage Feature Set
Creating Low-Code Loan Applications using the Trisotech Mortgage Feature SetCreating Low-Code Loan Applications using the Trisotech Mortgage Feature Set
Creating Low-Code Loan Applications using the Trisotech Mortgage Feature SetDenis Gagné
 
It will be International Nurses' Day on 12 May
It will be International Nurses' Day on 12 MayIt will be International Nurses' Day on 12 May
It will be International Nurses' Day on 12 MayNZSG
 
Vip Dewas Call Girls #9907093804 Contact Number Escorts Service Dewas
Vip Dewas Call Girls #9907093804 Contact Number Escorts Service DewasVip Dewas Call Girls #9907093804 Contact Number Escorts Service Dewas
Vip Dewas Call Girls #9907093804 Contact Number Escorts Service Dewasmakika9823
 
Mondelez State of Snacking and Future Trends 2023
Mondelez State of Snacking and Future Trends 2023Mondelez State of Snacking and Future Trends 2023
Mondelez State of Snacking and Future Trends 2023Neil Kimberley
 
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...anilsa9823
 
VIP Call Girls In Saharaganj ( Lucknow ) 🔝 8923113531 🔝 Cash Payment (COD) 👒
VIP Call Girls In Saharaganj ( Lucknow  ) 🔝 8923113531 🔝  Cash Payment (COD) 👒VIP Call Girls In Saharaganj ( Lucknow  ) 🔝 8923113531 🔝  Cash Payment (COD) 👒
VIP Call Girls In Saharaganj ( Lucknow ) 🔝 8923113531 🔝 Cash Payment (COD) 👒anilsa9823
 
The Coffee Bean & Tea Leaf(CBTL), Business strategy case study
The Coffee Bean & Tea Leaf(CBTL), Business strategy case studyThe Coffee Bean & Tea Leaf(CBTL), Business strategy case study
The Coffee Bean & Tea Leaf(CBTL), Business strategy case studyEthan lee
 
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...Dipal Arora
 
Pharma Works Profile of Karan Communications
Pharma Works Profile of Karan CommunicationsPharma Works Profile of Karan Communications
Pharma Works Profile of Karan Communicationskarancommunications
 
Ensure the security of your HCL environment by applying the Zero Trust princi...
Ensure the security of your HCL environment by applying the Zero Trust princi...Ensure the security of your HCL environment by applying the Zero Trust princi...
Ensure the security of your HCL environment by applying the Zero Trust princi...Roland Driesen
 
Monthly Social Media Update April 2024 pptx.pptx
Monthly Social Media Update April 2024 pptx.pptxMonthly Social Media Update April 2024 pptx.pptx
Monthly Social Media Update April 2024 pptx.pptxAndy Lambert
 
M.C Lodges -- Guest House in Jhang.
M.C Lodges --  Guest House in Jhang.M.C Lodges --  Guest House in Jhang.
M.C Lodges -- Guest House in Jhang.Aaiza Hassan
 
Russian Faridabad Call Girls(Badarpur) : ☎ 8168257667, @4999
Russian Faridabad Call Girls(Badarpur) : ☎ 8168257667, @4999Russian Faridabad Call Girls(Badarpur) : ☎ 8168257667, @4999
Russian Faridabad Call Girls(Badarpur) : ☎ 8168257667, @4999Tina Ji
 
Tech Startup Growth Hacking 101 - Basics on Growth Marketing
Tech Startup Growth Hacking 101  - Basics on Growth MarketingTech Startup Growth Hacking 101  - Basics on Growth Marketing
Tech Startup Growth Hacking 101 - Basics on Growth MarketingShawn Pang
 
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best ServicesMysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best ServicesDipal Arora
 

Último (20)

0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdf0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdf
 
Catalogue ONG NUOC PPR DE NHAT .pdf
Catalogue ONG NUOC PPR DE NHAT      .pdfCatalogue ONG NUOC PPR DE NHAT      .pdf
Catalogue ONG NUOC PPR DE NHAT .pdf
 
Catalogue ONG NƯỚC uPVC - HDPE DE NHAT.pdf
Catalogue ONG NƯỚC uPVC - HDPE DE NHAT.pdfCatalogue ONG NƯỚC uPVC - HDPE DE NHAT.pdf
Catalogue ONG NƯỚC uPVC - HDPE DE NHAT.pdf
 
Creating Low-Code Loan Applications using the Trisotech Mortgage Feature Set
Creating Low-Code Loan Applications using the Trisotech Mortgage Feature SetCreating Low-Code Loan Applications using the Trisotech Mortgage Feature Set
Creating Low-Code Loan Applications using the Trisotech Mortgage Feature Set
 
It will be International Nurses' Day on 12 May
It will be International Nurses' Day on 12 MayIt will be International Nurses' Day on 12 May
It will be International Nurses' Day on 12 May
 
Vip Dewas Call Girls #9907093804 Contact Number Escorts Service Dewas
Vip Dewas Call Girls #9907093804 Contact Number Escorts Service DewasVip Dewas Call Girls #9907093804 Contact Number Escorts Service Dewas
Vip Dewas Call Girls #9907093804 Contact Number Escorts Service Dewas
 
Mondelez State of Snacking and Future Trends 2023
Mondelez State of Snacking and Future Trends 2023Mondelez State of Snacking and Future Trends 2023
Mondelez State of Snacking and Future Trends 2023
 
Nepali Escort Girl Kakori \ 9548273370 Indian Call Girls Service Lucknow ₹,9517
Nepali Escort Girl Kakori \ 9548273370 Indian Call Girls Service Lucknow ₹,9517Nepali Escort Girl Kakori \ 9548273370 Indian Call Girls Service Lucknow ₹,9517
Nepali Escort Girl Kakori \ 9548273370 Indian Call Girls Service Lucknow ₹,9517
 
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
 
Forklift Operations: Safety through Cartoons
Forklift Operations: Safety through CartoonsForklift Operations: Safety through Cartoons
Forklift Operations: Safety through Cartoons
 
VIP Call Girls In Saharaganj ( Lucknow ) 🔝 8923113531 🔝 Cash Payment (COD) 👒
VIP Call Girls In Saharaganj ( Lucknow  ) 🔝 8923113531 🔝  Cash Payment (COD) 👒VIP Call Girls In Saharaganj ( Lucknow  ) 🔝 8923113531 🔝  Cash Payment (COD) 👒
VIP Call Girls In Saharaganj ( Lucknow ) 🔝 8923113531 🔝 Cash Payment (COD) 👒
 
The Coffee Bean & Tea Leaf(CBTL), Business strategy case study
The Coffee Bean & Tea Leaf(CBTL), Business strategy case studyThe Coffee Bean & Tea Leaf(CBTL), Business strategy case study
The Coffee Bean & Tea Leaf(CBTL), Business strategy case study
 
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
 
Pharma Works Profile of Karan Communications
Pharma Works Profile of Karan CommunicationsPharma Works Profile of Karan Communications
Pharma Works Profile of Karan Communications
 
Ensure the security of your HCL environment by applying the Zero Trust princi...
Ensure the security of your HCL environment by applying the Zero Trust princi...Ensure the security of your HCL environment by applying the Zero Trust princi...
Ensure the security of your HCL environment by applying the Zero Trust princi...
 
Monthly Social Media Update April 2024 pptx.pptx
Monthly Social Media Update April 2024 pptx.pptxMonthly Social Media Update April 2024 pptx.pptx
Monthly Social Media Update April 2024 pptx.pptx
 
M.C Lodges -- Guest House in Jhang.
M.C Lodges --  Guest House in Jhang.M.C Lodges --  Guest House in Jhang.
M.C Lodges -- Guest House in Jhang.
 
Russian Faridabad Call Girls(Badarpur) : ☎ 8168257667, @4999
Russian Faridabad Call Girls(Badarpur) : ☎ 8168257667, @4999Russian Faridabad Call Girls(Badarpur) : ☎ 8168257667, @4999
Russian Faridabad Call Girls(Badarpur) : ☎ 8168257667, @4999
 
Tech Startup Growth Hacking 101 - Basics on Growth Marketing
Tech Startup Growth Hacking 101  - Basics on Growth MarketingTech Startup Growth Hacking 101  - Basics on Growth Marketing
Tech Startup Growth Hacking 101 - Basics on Growth Marketing
 
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best ServicesMysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
 

Better Testing Through Behaviour

  • 1. Better Testing Through Behaviour Open Source Developers’ Conference November 2007 Tom Adams Workingmouse
  • 2. “The act of writing a unit test is more an act of design than of verification. It’s also more an act of documentation than of verification. The act of writing a unit test closes a remarkable number of feedback loops, the least of which is the one pertaining to verification of function.” Robert C. Martin
  • 3. Why do I care? I. Better process •Workflow is easier, IDE-a-bility, simpler •Supporting infrastructure & language that guides you down the correct path II. Better results •Splitting of state into separate contexts means understanding •Nicer syntax, less code to mentally parse •Readable results
  • 4. Test driven development •Development practice, arising out of XP’s test first approach •Incremental process - test, code, refactor, test code, refactor… •Drives implementation - improved quality, low coupling, high cohesion •Comprehensive regression test suite •Focus on design? •Focus on documentation? •Focus on behaviour?
  • 5. Problems? •Too much time/money, optional extra •Overlapping with traditional QA testers •Developers require training •Developer resistance •Vocabulary difference
  • 6. Problems? •Test vocabulary affects thinking •Intent not clear •Design focus obscured •Documentation •1-1 mapping of test/production code •Tight tests coupled to code •Repetitive infrastructure setup •Where to start?
  • 7. BDD is just TDD •Coined by Dan North - JBehave first BDD framework •Development practice, arising out agile methodologies •Refinement of TDD that shifts the emphasis from testing to specification •Frameworks - JBehave, RSpec, Instinct, JDave, NSpec, GSpec, beanSpec, JSSpec, DSpec, MissingBDD, PHPSpec, Specs, Specipy
  • 8. class ACsvFileReaderWithNothingToRead { @Subject CsvFileReader csvFileReader; @Mock CsvFile csvFile; @Stub CsvLine[] noLines; @Specification void returnsNoLines() { expect.that(new Expectations() {{ one(csvFile).hasMoreLines(); will(returnValue(false)); ignoring(csvFile).close(); }}); expect.that(csvFileReader.readLines()).equalTo(noLines); } }
  • 9. class AnEmptyStack { @Subject Stack<Object> stack; @Dummy Object object; @Specification void isEmpty() { expect.that(stack.isEmpty()).isTrue(); } @Specification void isNoLongerBeEmptyAfterPush() { stack.push(object); expect.that(stack.isEmpty()).isFalse(); } @Specification(expectedException = IllegalStateException.class, withMessage = quot;Cannot pop an empty stackquot;) void throwsExceptionWhenPopped() { stack.pop(); } }
  • 10. AnEmptyStack - isEmpty - isNoLongerBeEmptyAfterPush - throwsExceptionWhenPopped ANonEmptyStack - isNotEmpty - isNoLongerFullAfterPoppingAllElements - throwsExceptionWhenANullIsPushed - popsPushedValue - shouldPopSecondPushedValueFirst - leavesValueOnStackAfterPeek
  • 11. Ubiquitous language •Language has an impact on how you think about something •Known in linguistics as the Sapir-Whorf hypothesis •There is “a systematic relationship between the grammatical categories of the language a person speaks and how that person both understands the world and behaves in it” •The language used to describe software constructs has an impact on how we create those constructs, e.g. good APIs, well named variables
  • 12. Ubiquitous language •Getting the words right - naming of classes, methods and variables •Borrows from domain driven development (DDD) •Bridges gap between technical and business artefacts •Captures the behaviour of the domain using clear and concise syntax •Forms consensus around domain artefacts and run-time behaviour
  • 13. private void testRunnerSendsSpecifiationResultsToOutput() { assertTrue(quot;Expected to find context namequot;, runnerOutput.contains(className)); } private void sendsSpecifiationResultsToOutput() { expect.that(runnerOutput).containsString(className); }
  • 15. public void testMethodIsAnnotated() { checkIsAnnotated(WithRuntimeAnnotations.class, Context.class, true);   checkIsAnnotated(WithoutRuntimeAnnotations.class, Context.class, false); } private void checkIsAnnotated(AnnotatedElement element, Class<?> expectedAnnotation, boolean expectingAnnotation) { AnnotationChecker annotationChecker = new AnnotationCheckerImpl();   assertEquals(expectingAnnotation, annotationChecker.isAnnotated(element, expectedAnnotation)); }
  • 16. public void testClassIsAnnotated() { expect.that(annotationChecker.isAnnotated( WithRuntimeAnnotations.class, Context.class)).isTrue(); expect.that(annotationChecker.isAnnotated( WithoutRuntimeAnnotations.class, Context.class)).isFalse(); }
  • 17. Design focus •Design is one of the most important aspect of TDD •TDD’d code is (usually of) higher quality that non-TDD’d code •Bugs, coupling, cohesion, maintainability, understandable, smaller, etc. •Emphasis on testing limits TDD’s uptake & effectiveness •Organisational, technical, process •Encourages you to think about design •Design is documented through ubiquitous language, contexts
  • 18. Behaviour focus •Focused specifications •One context per “state” of subject •Minimal expectations per specification method
  • 19. Behaviour focus •1-to-1 test-to-prod code mapping broken •“Units” gone, what’s important is the behaviour •Specification code is less coupled to production code •Easier refactoring •M-to-N mapping encouraged
  • 20. class AnEmptyStack { void isEmpty() {} void isNoLongerBeEmptyAfterPush() {} void throwsExceptionWhenPopped() {} } class ANonEmptyStack { void isNotEmpty() {} void throwsExceptionWhenANullIsPushed() {} void popsPushedValue() {} void shouldPopSecondPushedValueFirst() {} void leavesValueOnStackAfterPeek() {} }
  • 21. Process •Works best top-down/outside-in •Specify at the highest level first •Use top-level objects to discover the services needed from the next level down •Rinse, repeat
  • 22. Levels •Story-level •Code-level •Mostly historical, frameworks are now adopting both approaches •Both levels are legitimate, use one or the other depending on audience
  • 23. Scenario quot;transfer from savings account to cheque acountquot; do Given quot;my savings account balance isquot;, 100 do |balance| @savings_account = Accounts::AccountFactory.create(:savings) @savings_account.add(balance) end And quot;my cheque account balance isquot;, 50 do |balance| @cheque_account = Accounts::AccountFactory.create(:cheque) @cheque_account.add(balance) end When quot;I transferquot;, 20 do |amount| @savings_account.transfer(amount.to_i).to(@cheque_account) end Then quot;my savings account balance should bequot;, 80 do |balance| @savings_account.balance.should == balance end And quot;my cheque account balance should bequot;, 70 do |balance| @cheque_account.balance.should == balance end end
  • 24. describe quot;non-empty Stackquot; do it quot;should return the top item when sent #peekquot; do @stack.peek.should == @last_item_added end end class ANonEmptyStack { void shouldReturnTheTopItemWhenSentPeek() { expect.that(stack.peek()).equalTo(lastItemAdded); } }
  • 25. Instinct •Goals - explicitness, simplicity and flexibility •Code-level (currently) framework •Unified state and behaviour (mocking) expectation API (c.f. xUnit Assert) •Built in infrastructure - mocks, stubs, dummies, subjects •Formalised nomenclature •Integration - JUnit, Ant, Clover, IntelliJ IDEA
  • 27. Summary •Shifts the emphasis from testing to specification •Provides a ubiquitous language •Strong focus on design •Emphasises system behaviour, independent of where the behaviour resides
  • 28. Take home I. Better process •Workflow is easier, IDE-a-bility, simpler •Supporting infrastructure & language that guides you down the correct path II. Better results •Splitting of state into separate contexts means understanding •Nicer syntax, less code to mentally parse •Readable results