SlideShare uma empresa Scribd logo
1 de 46
Baixar para ler offline
Test-
Behaviour-   } Driven Development
              Kerry Buckley
Clearing up some
 Misconceptions
TDD is not about
    testing
TDD does not mean
 handing acceptance
 tests to developers
TDD is a design activity
Software design is
emergent, and happens
 during development
Why TDD?

• Makes you think about required behaviour
• Reduces speculative code
• Provides documentation
• Improves quality
Evolution
Dirty Hacking
Automated Testing
Automated Testing
 class Adder
   def add a, b
     a + b
   end
 end

 class AdderTest < Test::Unit::TestCase
   def test_add
     adder = Adder.new
     assert_equal 4, adder.add(2, 2)
     assert_equal 2, adder.add(4, -2)
   end
 end
Are You Really Testing
     Your Code?
  class Adder
    def add a, b
      a + b
    end
  end

  class AdderTest < Test::Unit::TestCase
    def test_add
      assert_equal 4, 2 + 2
    end
  end
Test-First Development
Test-First Development

         Write             Write
         tests             code



 Start           Failing           Done
                  tests
Test-Driven
Development
Test-Driven
        Development
Clean                           Failing
code                             test



    Refactor



               All tests pass
State-Based
class DongleTest < Test::Unit::TestCase
  def test_wibble
    # Set up test inputs
    dongle = Dongle.new
    dongle.addString(quot;fooquot;)
    dongle.addRemoteResource(quot;http://foo.com/barquot;)

   # Exercise functionality under test
   dongle.wibble!

    # Verify results are as expected
    assert_equal(42, dongle.answer)
  end
end
Bottom-Up
Behaviour-Driven
 Development
Behaviour-Driven
      Development
Verification    Specification

State-based    Interaction-based

Bottom-up      Outside-in

Testing tool   Design tool

  Invention    Discovery
More Descriptive Test
       Names
class AdderTest < Test::Unit::TestCase
  def test_should_add_two_positive_numbers
    assert_equal 4, Adder.new.add(2, 2)
  end

  def test_should_add_a_positive_and_a_negative_number
    assert_equal 2, Adder.new.add(4, -2)
  end
end
RSpec

describe quot;An adderquot; do
  it quot;should add two positive numbersquot; do
    Adder.new.add(2, 2).should == 4
  end

  it quot;should add a positive and a negative numberquot; do
    Adder.new.add(4, -2).should == 2
  end
end
Generated
         Documentation
$ spec -f s adder_spec.rb

An adder
- should add two positive numbers
- should add a positive and a negative number

Finished in 0.005493 seconds

2 examples, 0 failures
Matchers (RSpec)

@string.should == quot;fooquot;

@array.should_not be_empty

@hash.should have_key(:foo)

@object.should be_an_instance_of String

lambda { @stack.pop }.should raise_error(StackUnderflowError)
Matchers (HamCrest)

assertThat(string, equalTo(quot;fooquot;));

assertThat(array, hasItem(quot;barquot;));

assertThat(obj, instanceOf(String.class));

assertThat(number, greaterThan(42));
Outside-In
Integration Testing
Describing Features

Feature: Transferring money between two accounts

  Scenario: Simple transfer
    Given an account called 'source' containing £100
    And an account called 'destination' containing £50
    When I transfer £20 from source to destination
    Then the 'source' account should contain £80
    And the 'destination' account should contain £70
Describing Features
Given /^an account called '(w*)' containing £(d*)$/ do |name, amount|
  @@accounts ||= {}
  @@accounts[name] = Account.new(amount.to_i)
end

When /^I transfer £(d*) from (w*) to (w*)$/ do |amount, from, to|
  AccountController.new.transfer @@accounts[from], @@accounts[to], amount.to_i
end

Then /^the '(w*)' account should contain £(d*)$/ do |name, amount|
  @@accounts[name].balance.should == amount.to_i
end
Unit Testing
Interaction-Based
Mock Objects


 Mock   Mock
Classicists v Mockists
Mock Objects

• Stand-ins for collaborating objects
• Mock the interface, not a specific object
• Verify that expected calls are made
• Not stubs!
• For your code only!
Boundary Objects
Mocking Patterns

• Record and playback
• Specify expectations before running
• Check expectations after running
Mocking Patterns
class AccountController {
  public void transfer(Account from, Account to, int amount) {
    from.debit(amount);
    to.credit(amount);
  }
}


class AccountController
  def transfer from, to, amount
    from.debit amount
    to.credit amount
  end
end
EasyMock
public void testTransferShouldDebitSourceAccount() {
  AccountController controller = new AccountController();

    Account from = createMock(Account.class);
    Account to = createNiceMock(Account.class);
    from.debit(42);

    replay(from);
    replay(to);

    controller.transfer(from, to, 42);

    verify(from);
}
JMock
Mockery context = new Mockery();

public void testTransferShouldDebitSourceAccount() {
  AccountController controller = new AccountController();

    Account from = context.mock(Account.class);
    Account to = context.mock(Account.class);

    context.checking(new Expectations() {{
      oneOf(from).debit(42);
    }});

    controller.transfer(from, to, 42);

    context.assertIsSatisfied();
}
Mockito
public void testTransferShouldDebitSourceAccount() {
  AccountController controller = new AccountController();

    Account from = mock(Account.class);
    Account to = mock(Account.class);

    controller.transfer(from, to, 42);

    verify(from).debit(42);
}
RSpec
describe 'Making a transfer' do
  it 'should debit the source account' do
    controller = AccountController.new

   from = stub_everything 'from'
   to = stub_everything 'to'

   from.should_receive(:debit).with 42

    controller.transfer from, to, 42
  end
end
Not-a-Mock
describe 'Making a transfer' do
  it 'should debit the source account' do
    controller = AccountController.new
    from = Account.new
    to = Account.new

   from.stub_method :debit => nil
   to.stub_method :credit => nil

   controller.transfer from, to, 42

    from.should_have_received(:debit).with(42)
  end
end
Other Mock Features
• Stubs (for when you don’t care)
• Mock class/static methods
• Specify return values
• Specify expected number of calls
• Specify method ordering
• Raise exceptions on method calls
Good Practices
• Test behaviour, not implementation
• One expectation per test
• Don’t test private methods
• Don’t mock everything
• Stub queries; mock actions
• Tell, don’t ask
• Listen to test smells!
TDD/BDD Summary
• Never write any code without a failing test
• Start from the outside, with acceptance tests
• Drive design inwards using mock objects
• Tests should be descriptive specifications
• Red – Green – Refactor
• YAGNI
• TATFT!
Further Reading
Introducing BDD (Dan North)
  http://dannorth.net/introducing-bdd

BDD Introduction
 http://behaviour-driven.org/Introduction

Mock Roles, Not Objects
(Freeman, Mackinnon, Pryce, Walnes)
  http://www.jmock.org/oopsla2004.pdf

BDD in Ruby (Dave Astels)
 http://blog.daveastels.com/files/BDD_Intro.pdf

Test all the F***in Time (Brian Liles, video)
 http://www.icanhaz.com/tatft

Mais conteúdo relacionado

Mais procurados

iOS Unit Testing
iOS Unit TestingiOS Unit Testing
iOS Unit Testingsgleadow
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSIntro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSJim Lynch
 
Quick Tour to Front-End Unit Testing Using Jasmine
Quick Tour to Front-End Unit Testing Using JasmineQuick Tour to Front-End Unit Testing Using Jasmine
Quick Tour to Front-End Unit Testing Using JasmineGil Fink
 
Front end unit testing using jasmine
Front end unit testing using jasmineFront end unit testing using jasmine
Front end unit testing using jasmineGil Fink
 
Unit Testing in iOS - Ninjava Talk
Unit Testing in iOS - Ninjava TalkUnit Testing in iOS - Ninjava Talk
Unit Testing in iOS - Ninjava TalkLong Weekend LLC
 
Testing the Untestable
Testing the UntestableTesting the Untestable
Testing the UntestableMark Baker
 
Testing in AngularJS
Testing in AngularJSTesting in AngularJS
Testing in AngularJSPeter Drinnan
 
Unit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and HowsUnit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and Howsatesgoral
 
Refactoring legacy code driven by tests - ENG
Refactoring legacy code driven by tests - ENGRefactoring legacy code driven by tests - ENG
Refactoring legacy code driven by tests - ENGLuca Minudel
 
Ruby onrails cucumber-rspec-capybara
Ruby onrails cucumber-rspec-capybaraRuby onrails cucumber-rspec-capybara
Ruby onrails cucumber-rspec-capybaraBindesh Vijayan
 
Unit Testing in SilverStripe
Unit Testing in SilverStripeUnit Testing in SilverStripe
Unit Testing in SilverStripeIngo Schommer
 
Client side unit tests - using jasmine & karma
Client side unit tests - using jasmine & karmaClient side unit tests - using jasmine & karma
Client side unit tests - using jasmine & karmaAdam Klein
 
Unit testing legacy code
Unit testing legacy codeUnit testing legacy code
Unit testing legacy codeLars Thorup
 
Karate - powerful and simple framework for REST API automation testing
Karate - powerful and simple framework for REST API automation testingKarate - powerful and simple framework for REST API automation testing
Karate - powerful and simple framework for REST API automation testingRoman Liubun
 
Karate - Web-Service API Testing Made Simple
Karate - Web-Service API Testing Made SimpleKarate - Web-Service API Testing Made Simple
Karate - Web-Service API Testing Made SimpleVodqaBLR
 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsFITC
 

Mais procurados (20)

iOS Unit Testing
iOS Unit TestingiOS Unit Testing
iOS Unit Testing
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSIntro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJS
 
Quick Tour to Front-End Unit Testing Using Jasmine
Quick Tour to Front-End Unit Testing Using JasmineQuick Tour to Front-End Unit Testing Using Jasmine
Quick Tour to Front-End Unit Testing Using Jasmine
 
Front end unit testing using jasmine
Front end unit testing using jasmineFront end unit testing using jasmine
Front end unit testing using jasmine
 
TDD
TDDTDD
TDD
 
Unit Testing in iOS - Ninjava Talk
Unit Testing in iOS - Ninjava TalkUnit Testing in iOS - Ninjava Talk
Unit Testing in iOS - Ninjava Talk
 
Unit Testing in iOS
Unit Testing in iOSUnit Testing in iOS
Unit Testing in iOS
 
Testing the Untestable
Testing the UntestableTesting the Untestable
Testing the Untestable
 
Angular Unit Testing
Angular Unit TestingAngular Unit Testing
Angular Unit Testing
 
Testing in AngularJS
Testing in AngularJSTesting in AngularJS
Testing in AngularJS
 
Unit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and HowsUnit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and Hows
 
Refactoring legacy code driven by tests - ENG
Refactoring legacy code driven by tests - ENGRefactoring legacy code driven by tests - ENG
Refactoring legacy code driven by tests - ENG
 
Ruby onrails cucumber-rspec-capybara
Ruby onrails cucumber-rspec-capybaraRuby onrails cucumber-rspec-capybara
Ruby onrails cucumber-rspec-capybara
 
Unit Testing in SilverStripe
Unit Testing in SilverStripeUnit Testing in SilverStripe
Unit Testing in SilverStripe
 
Client side unit tests - using jasmine & karma
Client side unit tests - using jasmine & karmaClient side unit tests - using jasmine & karma
Client side unit tests - using jasmine & karma
 
Unit testing legacy code
Unit testing legacy codeUnit testing legacy code
Unit testing legacy code
 
Angular testing
Angular testingAngular testing
Angular testing
 
Karate - powerful and simple framework for REST API automation testing
Karate - powerful and simple framework for REST API automation testingKarate - powerful and simple framework for REST API automation testing
Karate - powerful and simple framework for REST API automation testing
 
Karate - Web-Service API Testing Made Simple
Karate - Web-Service API Testing Made SimpleKarate - Web-Service API Testing Made Simple
Karate - Web-Service API Testing Made Simple
 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS Applications
 

Destaque

Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)Lars Thorup
 
Principles and patterns for test driven development
Principles and patterns for test driven developmentPrinciples and patterns for test driven development
Principles and patterns for test driven developmentStephen Fuqua
 
BDD presentation
BDD presentationBDD presentation
BDD presentationtemebele
 
The WHY behind TDD/BDD and the HOW with RSpec
The WHY behind TDD/BDD and the HOW with RSpecThe WHY behind TDD/BDD and the HOW with RSpec
The WHY behind TDD/BDD and the HOW with RSpecBen Mabey
 
Introduction to Acceptance Test Driven Development
Introduction to Acceptance Test Driven DevelopmentIntroduction to Acceptance Test Driven Development
Introduction to Acceptance Test Driven DevelopmentElisabeth Hendrickson
 
Shallow Depth of Tests Scallable BDD and TDD
Shallow Depth of Tests Scallable BDD and TDDShallow Depth of Tests Scallable BDD and TDD
Shallow Depth of Tests Scallable BDD and TDDfabiopereirame
 
Sequential file programming patterns and performance with .net
Sequential  file programming patterns and performance with .netSequential  file programming patterns and performance with .net
Sequential file programming patterns and performance with .netMichael Pavlovsky
 
Test-Driven Development In Action
Test-Driven Development In ActionTest-Driven Development In Action
Test-Driven Development In ActionJon Kruger
 
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in FlexassertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flexmichael.labriola
 
Test Driven Development for Embedded C
Test Driven Development for Embedded CTest Driven Development for Embedded C
Test Driven Development for Embedded CJames Grenning
 
Moq Presentation
Moq PresentationMoq Presentation
Moq PresentationLynxStar
 
Mock driven development using .NET
Mock driven development using .NETMock driven development using .NET
Mock driven development using .NETPuneet Ghanshani
 
Les outils d’automatisation de tests (scripting) : Adoption et enjeux (comple...
Les outils d’automatisation de tests (scripting) : Adoption et enjeux (comple...Les outils d’automatisation de tests (scripting) : Adoption et enjeux (comple...
Les outils d’automatisation de tests (scripting) : Adoption et enjeux (comple...AQT-presentations
 
Double Loop: TDD & BDD Done Right!
Double Loop: TDD & BDD Done Right!Double Loop: TDD & BDD Done Right!
Double Loop: TDD & BDD Done Right!Jessica Mauerhan
 
TDD with BDD in PHP and Symfony
TDD with BDD in PHP and SymfonyTDD with BDD in PHP and Symfony
TDD with BDD in PHP and SymfonyKamil Adryjanek
 
Getting Comfortable with BDD
Getting Comfortable with BDDGetting Comfortable with BDD
Getting Comfortable with BDDAlex Sharp
 

Destaque (20)

Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)
 
Principles and patterns for test driven development
Principles and patterns for test driven developmentPrinciples and patterns for test driven development
Principles and patterns for test driven development
 
TDD, BDD, RSpec
TDD, BDD, RSpecTDD, BDD, RSpec
TDD, BDD, RSpec
 
BDD presentation
BDD presentationBDD presentation
BDD presentation
 
The WHY behind TDD/BDD and the HOW with RSpec
The WHY behind TDD/BDD and the HOW with RSpecThe WHY behind TDD/BDD and the HOW with RSpec
The WHY behind TDD/BDD and the HOW with RSpec
 
Introduction to Acceptance Test Driven Development
Introduction to Acceptance Test Driven DevelopmentIntroduction to Acceptance Test Driven Development
Introduction to Acceptance Test Driven Development
 
Shallow Depth of Tests Scallable BDD and TDD
Shallow Depth of Tests Scallable BDD and TDDShallow Depth of Tests Scallable BDD and TDD
Shallow Depth of Tests Scallable BDD and TDD
 
Sequential file programming patterns and performance with .net
Sequential  file programming patterns and performance with .netSequential  file programming patterns and performance with .net
Sequential file programming patterns and performance with .net
 
Test-Driven Development In Action
Test-Driven Development In ActionTest-Driven Development In Action
Test-Driven Development In Action
 
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in FlexassertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
 
Test Driven Development for Embedded C
Test Driven Development for Embedded CTest Driven Development for Embedded C
Test Driven Development for Embedded C
 
Bdd Introduction
Bdd IntroductionBdd Introduction
Bdd Introduction
 
Les tests en PHP
Les tests en PHPLes tests en PHP
Les tests en PHP
 
Moq Presentation
Moq PresentationMoq Presentation
Moq Presentation
 
BDD - Collaborate like you mean it!
BDD - Collaborate like you mean it!BDD - Collaborate like you mean it!
BDD - Collaborate like you mean it!
 
Mock driven development using .NET
Mock driven development using .NETMock driven development using .NET
Mock driven development using .NET
 
Les outils d’automatisation de tests (scripting) : Adoption et enjeux (comple...
Les outils d’automatisation de tests (scripting) : Adoption et enjeux (comple...Les outils d’automatisation de tests (scripting) : Adoption et enjeux (comple...
Les outils d’automatisation de tests (scripting) : Adoption et enjeux (comple...
 
Double Loop: TDD & BDD Done Right!
Double Loop: TDD & BDD Done Right!Double Loop: TDD & BDD Done Right!
Double Loop: TDD & BDD Done Right!
 
TDD with BDD in PHP and Symfony
TDD with BDD in PHP and SymfonyTDD with BDD in PHP and Symfony
TDD with BDD in PHP and Symfony
 
Getting Comfortable with BDD
Getting Comfortable with BDDGetting Comfortable with BDD
Getting Comfortable with BDD
 

Semelhante a TDD, BDD and mocks

Bdd for-dso-1227123516572504-8
Bdd for-dso-1227123516572504-8Bdd for-dso-1227123516572504-8
Bdd for-dso-1227123516572504-8Frédéric Delorme
 
Behaviour-Driven Development
Behaviour-Driven DevelopmentBehaviour-Driven Development
Behaviour-Driven DevelopmentKerry Buckley
 
Tdd for BT E2E test community
Tdd for BT E2E test communityTdd for BT E2E test community
Tdd for BT E2E test communityKerry Buckley
 
Unit test candidate solutions
Unit test candidate solutionsUnit test candidate solutions
Unit test candidate solutionsbenewu
 
ruby on rails pitfalls
ruby on rails pitfallsruby on rails pitfalls
ruby on rails pitfallsRobbin Fan
 
Quality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStormQuality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStormMichelangelo van Dam
 
Test-driven Development no Rails
Test-driven Development no RailsTest-driven Development no Rails
Test-driven Development no Railselliando dias
 
Verilog Tasks & Functions
Verilog Tasks & FunctionsVerilog Tasks & Functions
Verilog Tasks & Functionsanand hd
 
Acceptance Testing With Selenium
Acceptance Testing With SeleniumAcceptance Testing With Selenium
Acceptance Testing With Seleniumelliando dias
 
Beijing Perl Workshop 2008 Hiveminder Secret Sauce
Beijing Perl Workshop 2008 Hiveminder Secret SauceBeijing Perl Workshop 2008 Hiveminder Secret Sauce
Beijing Perl Workshop 2008 Hiveminder Secret SauceJesse Vincent
 
Very basic functional design patterns
Very basic functional design patternsVery basic functional design patterns
Very basic functional design patternsTomasz Kowal
 
Leveling Up With Unit Testing - php[tek] 2023
Leveling Up With Unit Testing - php[tek] 2023Leveling Up With Unit Testing - php[tek] 2023
Leveling Up With Unit Testing - php[tek] 2023Mark Niebergall
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdfHans Jones
 
Java: Class Design Examples
Java: Class Design ExamplesJava: Class Design Examples
Java: Class Design ExamplesTareq Hasan
 

Semelhante a TDD, BDD and mocks (20)

Bdd for-dso-1227123516572504-8
Bdd for-dso-1227123516572504-8Bdd for-dso-1227123516572504-8
Bdd for-dso-1227123516572504-8
 
Behaviour-Driven Development
Behaviour-Driven DevelopmentBehaviour-Driven Development
Behaviour-Driven Development
 
Tdd for BT E2E test community
Tdd for BT E2E test communityTdd for BT E2E test community
Tdd for BT E2E test community
 
Unit test candidate solutions
Unit test candidate solutionsUnit test candidate solutions
Unit test candidate solutions
 
Testing
TestingTesting
Testing
 
ruby on rails pitfalls
ruby on rails pitfallsruby on rails pitfalls
ruby on rails pitfalls
 
PHPSpec BDD Framework
PHPSpec BDD FrameworkPHPSpec BDD Framework
PHPSpec BDD Framework
 
Headless Js Testing
Headless Js TestingHeadless Js Testing
Headless Js Testing
 
Rspec
RspecRspec
Rspec
 
PHPUnit testing to Zend_Test
PHPUnit testing to Zend_TestPHPUnit testing to Zend_Test
PHPUnit testing to Zend_Test
 
Quality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStormQuality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStorm
 
Test-driven Development no Rails
Test-driven Development no RailsTest-driven Development no Rails
Test-driven Development no Rails
 
Verilog Tasks & Functions
Verilog Tasks & FunctionsVerilog Tasks & Functions
Verilog Tasks & Functions
 
Acceptance Testing With Selenium
Acceptance Testing With SeleniumAcceptance Testing With Selenium
Acceptance Testing With Selenium
 
Beijing Perl Workshop 2008 Hiveminder Secret Sauce
Beijing Perl Workshop 2008 Hiveminder Secret SauceBeijing Perl Workshop 2008 Hiveminder Secret Sauce
Beijing Perl Workshop 2008 Hiveminder Secret Sauce
 
Very basic functional design patterns
Very basic functional design patternsVery basic functional design patterns
Very basic functional design patterns
 
Leveling Up With Unit Testing - php[tek] 2023
Leveling Up With Unit Testing - php[tek] 2023Leveling Up With Unit Testing - php[tek] 2023
Leveling Up With Unit Testing - php[tek] 2023
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdf
 
Why ruby
Why rubyWhy ruby
Why ruby
 
Java: Class Design Examples
Java: Class Design ExamplesJava: Class Design Examples
Java: Class Design Examples
 

Mais de Kerry Buckley

Testing http calls with Webmock and VCR
Testing http calls with Webmock and VCRTesting http calls with Webmock and VCR
Testing http calls with Webmock and VCRKerry Buckley
 
Ruby nooks & crannies
Ruby nooks & cranniesRuby nooks & crannies
Ruby nooks & cranniesKerry Buckley
 
Javasccript MV* frameworks
Javasccript MV* frameworksJavasccript MV* frameworks
Javasccript MV* frameworksKerry Buckley
 
What I learned from Seven Languages in Seven Weeks (IPRUG)
What I learned from Seven Languages in Seven Weeks (IPRUG)What I learned from Seven Languages in Seven Weeks (IPRUG)
What I learned from Seven Languages in Seven Weeks (IPRUG)Kerry Buckley
 
Adastral Park code retreat introduction
Adastral Park code retreat introductionAdastral Park code retreat introduction
Adastral Park code retreat introductionKerry Buckley
 
MongoMapper lightning talk
MongoMapper lightning talkMongoMapper lightning talk
MongoMapper lightning talkKerry Buckley
 
The secret life of bees
The secret life of beesThe secret life of bees
The secret life of beesKerry Buckley
 
Background processing
Background processingBackground processing
Background processingKerry Buckley
 
Katas, Contests and Coding Dojos
Katas, Contests and Coding DojosKatas, Contests and Coding Dojos
Katas, Contests and Coding DojosKerry Buckley
 
Kanban and Iterationless Working
Kanban and Iterationless WorkingKanban and Iterationless Working
Kanban and Iterationless WorkingKerry Buckley
 
Software Development Trends
Software Development TrendsSoftware Development Trends
Software Development TrendsKerry Buckley
 

Mais de Kerry Buckley (20)

Jasmine
JasmineJasmine
Jasmine
 
Testing http calls with Webmock and VCR
Testing http calls with Webmock and VCRTesting http calls with Webmock and VCR
Testing http calls with Webmock and VCR
 
BDD with cucumber
BDD with cucumberBDD with cucumber
BDD with cucumber
 
Ruby nooks & crannies
Ruby nooks & cranniesRuby nooks & crannies
Ruby nooks & crannies
 
TDD refresher
TDD refresherTDD refresher
TDD refresher
 
Javasccript MV* frameworks
Javasccript MV* frameworksJavasccript MV* frameworks
Javasccript MV* frameworks
 
7li7w devcon5
7li7w devcon57li7w devcon5
7li7w devcon5
 
What I learned from Seven Languages in Seven Weeks (IPRUG)
What I learned from Seven Languages in Seven Weeks (IPRUG)What I learned from Seven Languages in Seven Weeks (IPRUG)
What I learned from Seven Languages in Seven Weeks (IPRUG)
 
Functional ruby
Functional rubyFunctional ruby
Functional ruby
 
Adastral Park code retreat introduction
Adastral Park code retreat introductionAdastral Park code retreat introduction
Adastral Park code retreat introduction
 
MongoMapper lightning talk
MongoMapper lightning talkMongoMapper lightning talk
MongoMapper lightning talk
 
Ruby
RubyRuby
Ruby
 
Cloud
CloudCloud
Cloud
 
The secret life of bees
The secret life of beesThe secret life of bees
The secret life of bees
 
Background processing
Background processingBackground processing
Background processing
 
Katas, Contests and Coding Dojos
Katas, Contests and Coding DojosKatas, Contests and Coding Dojos
Katas, Contests and Coding Dojos
 
Rack
RackRack
Rack
 
Doing REST Right
Doing REST RightDoing REST Right
Doing REST Right
 
Kanban and Iterationless Working
Kanban and Iterationless WorkingKanban and Iterationless Working
Kanban and Iterationless Working
 
Software Development Trends
Software Development TrendsSoftware Development Trends
Software Development Trends
 

Último

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 

Último (20)

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

TDD, BDD and mocks

  • 1. Test- Behaviour- } Driven Development Kerry Buckley
  • 2. Clearing up some Misconceptions
  • 3. TDD is not about testing
  • 4. TDD does not mean handing acceptance tests to developers
  • 5. TDD is a design activity
  • 6. Software design is emergent, and happens during development
  • 7. Why TDD? • Makes you think about required behaviour • Reduces speculative code • Provides documentation • Improves quality
  • 11. Automated Testing class Adder def add a, b a + b end end class AdderTest < Test::Unit::TestCase def test_add adder = Adder.new assert_equal 4, adder.add(2, 2) assert_equal 2, adder.add(4, -2) end end
  • 12. Are You Really Testing Your Code? class Adder def add a, b a + b end end class AdderTest < Test::Unit::TestCase def test_add assert_equal 4, 2 + 2 end end
  • 14. Test-First Development Write Write tests code Start Failing Done tests
  • 16. Test-Driven Development Clean Failing code test Refactor All tests pass
  • 17. State-Based class DongleTest < Test::Unit::TestCase def test_wibble # Set up test inputs dongle = Dongle.new dongle.addString(quot;fooquot;) dongle.addRemoteResource(quot;http://foo.com/barquot;) # Exercise functionality under test dongle.wibble! # Verify results are as expected assert_equal(42, dongle.answer) end end
  • 20. Behaviour-Driven Development Verification Specification State-based Interaction-based Bottom-up Outside-in Testing tool Design tool Invention Discovery
  • 21. More Descriptive Test Names class AdderTest < Test::Unit::TestCase def test_should_add_two_positive_numbers assert_equal 4, Adder.new.add(2, 2) end def test_should_add_a_positive_and_a_negative_number assert_equal 2, Adder.new.add(4, -2) end end
  • 22. RSpec describe quot;An adderquot; do it quot;should add two positive numbersquot; do Adder.new.add(2, 2).should == 4 end it quot;should add a positive and a negative numberquot; do Adder.new.add(4, -2).should == 2 end end
  • 23. Generated Documentation $ spec -f s adder_spec.rb An adder - should add two positive numbers - should add a positive and a negative number Finished in 0.005493 seconds 2 examples, 0 failures
  • 24. Matchers (RSpec) @string.should == quot;fooquot; @array.should_not be_empty @hash.should have_key(:foo) @object.should be_an_instance_of String lambda { @stack.pop }.should raise_error(StackUnderflowError)
  • 25. Matchers (HamCrest) assertThat(string, equalTo(quot;fooquot;)); assertThat(array, hasItem(quot;barquot;)); assertThat(obj, instanceOf(String.class)); assertThat(number, greaterThan(42));
  • 28. Describing Features Feature: Transferring money between two accounts Scenario: Simple transfer Given an account called 'source' containing £100 And an account called 'destination' containing £50 When I transfer £20 from source to destination Then the 'source' account should contain £80 And the 'destination' account should contain £70
  • 29. Describing Features Given /^an account called '(w*)' containing £(d*)$/ do |name, amount| @@accounts ||= {} @@accounts[name] = Account.new(amount.to_i) end When /^I transfer £(d*) from (w*) to (w*)$/ do |amount, from, to| AccountController.new.transfer @@accounts[from], @@accounts[to], amount.to_i end Then /^the '(w*)' account should contain £(d*)$/ do |name, amount| @@accounts[name].balance.should == amount.to_i end
  • 34. Mock Objects • Stand-ins for collaborating objects • Mock the interface, not a specific object • Verify that expected calls are made • Not stubs! • For your code only!
  • 36. Mocking Patterns • Record and playback • Specify expectations before running • Check expectations after running
  • 37. Mocking Patterns class AccountController { public void transfer(Account from, Account to, int amount) { from.debit(amount); to.credit(amount); } } class AccountController def transfer from, to, amount from.debit amount to.credit amount end end
  • 38. EasyMock public void testTransferShouldDebitSourceAccount() { AccountController controller = new AccountController(); Account from = createMock(Account.class); Account to = createNiceMock(Account.class); from.debit(42); replay(from); replay(to); controller.transfer(from, to, 42); verify(from); }
  • 39. JMock Mockery context = new Mockery(); public void testTransferShouldDebitSourceAccount() { AccountController controller = new AccountController(); Account from = context.mock(Account.class); Account to = context.mock(Account.class); context.checking(new Expectations() {{ oneOf(from).debit(42); }}); controller.transfer(from, to, 42); context.assertIsSatisfied(); }
  • 40. Mockito public void testTransferShouldDebitSourceAccount() { AccountController controller = new AccountController(); Account from = mock(Account.class); Account to = mock(Account.class); controller.transfer(from, to, 42); verify(from).debit(42); }
  • 41. RSpec describe 'Making a transfer' do it 'should debit the source account' do controller = AccountController.new from = stub_everything 'from' to = stub_everything 'to' from.should_receive(:debit).with 42 controller.transfer from, to, 42 end end
  • 42. Not-a-Mock describe 'Making a transfer' do it 'should debit the source account' do controller = AccountController.new from = Account.new to = Account.new from.stub_method :debit => nil to.stub_method :credit => nil controller.transfer from, to, 42 from.should_have_received(:debit).with(42) end end
  • 43. Other Mock Features • Stubs (for when you don’t care) • Mock class/static methods • Specify return values • Specify expected number of calls • Specify method ordering • Raise exceptions on method calls
  • 44. Good Practices • Test behaviour, not implementation • One expectation per test • Don’t test private methods • Don’t mock everything • Stub queries; mock actions • Tell, don’t ask • Listen to test smells!
  • 45. TDD/BDD Summary • Never write any code without a failing test • Start from the outside, with acceptance tests • Drive design inwards using mock objects • Tests should be descriptive specifications • Red – Green – Refactor • YAGNI • TATFT!
  • 46. Further Reading Introducing BDD (Dan North) http://dannorth.net/introducing-bdd BDD Introduction http://behaviour-driven.org/Introduction Mock Roles, Not Objects (Freeman, Mackinnon, Pryce, Walnes) http://www.jmock.org/oopsla2004.pdf BDD in Ruby (Dave Astels) http://blog.daveastels.com/files/BDD_Intro.pdf Test all the F***in Time (Brian Liles, video) http://www.icanhaz.com/tatft