SlideShare una empresa de Scribd logo
1 de 24
Tests
                            Test




                           Paweł L. Lipiński



(or how to write tests so that they serve you well)
pawel@agileee:/etc$whoami



•       13 years as a developer

•       >10 years in Java

•       i did : development, consulting,
        trainings, audits, architecture, team leading

•       now:

    ‣     developer, coach & owner of      pragmatists

•       2nd time @ agileee
Agenda


• writing tests so that they’re reliable
• writing tests so that they document code
• writing tests so that they’re maintainable
• writing tests so that they’re readable
What do tests give?
                                                  Tests

•   awareness of what is supposed to be written

•   feeling of safety while refactoring

•   feeling of safety while changing code

•   increase in development speed

•   executable documentation
So whatʼs the problem?


•   Whenever you change something -
    they stop working
•   They become harder
    and harder to maintain
•   They soon start to look like this
•   If there’s many of them, it’s hard to know where to look to
    learn something about the system
Process


• Think First
• Trivial First
• Test specifies „what”,
  implementation says „how”
• Different levels of tests
Conventions
•   coherent naming of test classes

•   coherent naming of tests

•   test classes’ names describing behaviour not the
    class’ name

•   test methods’ names should describe test case,
    not method being tested

•   code conventions
Comments
•   if you feel you must comment, something’s
    wrong with your code

•   tests should document code, so they must be
    SUPERCOMPREHENSIBLE

•   though comments are useful sometimes...


           // given

           // when

           // then
Formatting
•   coherent formatting throughout the codebase

•   separation of logical fragments

•   eyes used to it = quicker understanding
Given (test setup)


•   DRY (setup methods should be business-like)

•   setup method COMPREHENSIBLE

•   @Before vs. explicite call
Error handling
•    One test, one exception

•    NEVER:
     @Test(expected = Exception.class)
     Use only CONCRETE, UNIQUE exception

•    try / catch


    @Rule
    public ExpectedException throwing =
                             ExpectedException.none();
    ...
    ...

    // when
    throwing.expect(ParseException.class);
    parser.parse(text);
    // then exception is thrown
Behaviour Driven Development
• define behaviours not tests
• behaviours constitute a functional spec of
  the application
• behaviours should be worked upon by
  business people together with developers
• focus on why the code should exist
• naming in code is the same as names used
  by the business people (ubiquitous language)
Defining behaviour
As a conference attendee I want to get a restration status after signing
up for a conference so that I know if the registration went fine:


     Given a conference „Agileee”
     When I try to register to it and the registration is successful
     Then I get a confirmation message: „You are registered to
     Agileee. An email with details has been sent to you.”


     Given a conference „Agileee”
     When I try to register to it but there are no free places
     Then I get a message: „Sorry. No free places left. Try the next
     year!”
Examples, not Tests
• BDD helps to think about objects from the
  perspective of their behaviours, so the code is
  more object-oriented
• examples help you create a „mental” model of
  the system
• test class shows examples of use of a
  functionality
• test code is an example of behaviour
• test code is also an example of use
BDD naming
                             Story, Scenario
public class AddingBooksToLibraryTest {
   @Mock
	 private BookRepository bookRepository;

	   @Test
	   public void shouldEnableAddingNewBooks() {
	   	 // given
	   	 Library library = new Library(bookRepository);
	   	 Book book = new Book("Children from Bullerbyn");

	   	   // when
	   	   library.add(book);

	   	   // then
	   	   assertThat(library.size()).is(1);
        verify(bookRepository).save(book);
	   }
}
BDD rules
• test names should be sentences
• simple constant template of the sentence
  helps you focus in the test on one thing
  public void shouldBeSearchedByName()

• understandable test name helps when the
  test fails
• test are examples - think about them not as
  a means for future verification, but as a
  documentation of behaviour
Tumbler




http://tumbler-glass.googlecode.com
A-TDD
• Acceptance tests may drive the development of scenarios.
• But the need to be:
  ‣   written by business people (or at least with them
      nearby)
  ‣   verify correctness of scenario accomplishment (be
      complete and fulfill acceptance criteria)
  ‣   be automatic
  ‣   be maintainable
• These are high-level tests, so changes to the application
  may force you to modify many of them
Whole system tests
  organisation
•   Tests in the same packages as SUT
    vs. separately

•   Tests named by the functionality
    vs. tests named by tested classes

•   Tests’ speed


•   Test levels       clicking


                      acceptance




                    integration


                      unit
Test smells
•   Long setup - lack of factory method, or perhaps
    a problem with the structure of created objects?

•   Long tests - perhaps you’re testing more than
    one behaviour at a time?

•   Many assertions - doesn’t the tested method
    have too many responsibilities?

•   Too many test methods in a test class - class
    under test has too many responsibilities? Or
    maybe you’re testing more than one
    functionality in a single class?
Maintainable tests
•   Reuse assertions, create „business” assertions
•   Reuse object construction methods - don’t be sensitive to
    changes of constructors
•   Reuse test setup
•   Tests should not depend on environment and order of execution
•   Avoid many assertions - when the first one fails, others are not
    executed (they could’ve give you a clue about possible reasons)
•   Separate assertion from the action to increase readability (or
    better use given/when/then pattern)
•   Use variables to pass and verify values in tests
•   Remove tests ONLY when you remove a functionality or when
    tests’ responsibilities overlap
TO WRITE READABLE TESTS
Thank you!
                      pawel.lipinski@pragmatists.pl

                          http://www.pragmatists.pl




All pictures were used exclusively to set the presentation context and advertise the original book.

Más contenido relacionado

La actualidad más candente

Regression Testing: Down the Rabbit Hole (MEWT 2014)
Regression Testing: Down the Rabbit Hole (MEWT 2014)Regression Testing: Down the Rabbit Hole (MEWT 2014)
Regression Testing: Down the Rabbit Hole (MEWT 2014)Neil Studd
 
Is Groovy better for testing than Java?
Is Groovy better for testing than Java?Is Groovy better for testing than Java?
Is Groovy better for testing than Java?Trisha Gee
 
Software testing with examples in Angular (and AngularJS)
Software testing with examples in Angular (and AngularJS)Software testing with examples in Angular (and AngularJS)
Software testing with examples in Angular (and AngularJS)Paweł Żurowski
 
Unit testing
Unit testingUnit testing
Unit testingAdam Birr
 
Type mock isolator
Type mock isolatorType mock isolator
Type mock isolatorMaslowB
 
Code Review Matters and Manners
Code Review Matters and MannersCode Review Matters and Manners
Code Review Matters and MannersTrisha Gee
 
Agile testing for mere mortals
Agile testing for mere mortalsAgile testing for mere mortals
Agile testing for mere mortalsDave Haeffner
 
Roy Osherove TDD From Scratch
Roy Osherove TDD From ScratchRoy Osherove TDD From Scratch
Roy Osherove TDD From ScratchRoy Osherove
 
How to structure testing within the Scrum Framework
How to structure testing within the Scrum FrameworkHow to structure testing within the Scrum Framework
How to structure testing within the Scrum FrameworkJohan Hoberg
 
Level Up Your Automated Tests
Level Up Your Automated TestsLevel Up Your Automated Tests
Level Up Your Automated TestsTrisha Gee
 
Adopting tdd in the workplace
Adopting tdd in the workplaceAdopting tdd in the workplace
Adopting tdd in the workplaceDonny Wals
 
Clean code - Getting your R&D on board
Clean code - Getting your R&D on boardClean code - Getting your R&D on board
Clean code - Getting your R&D on boardRuth Sperer
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing SoftwareSteven Smith
 
Exploratory testing
Exploratory testingExploratory testing
Exploratory testingHuib Schoots
 
Introduction to test programming
Introduction to test programmingIntroduction to test programming
Introduction to test programmingopenfinanceDev
 

La actualidad más candente (20)

Unit testing in PHP
Unit testing in PHPUnit testing in PHP
Unit testing in PHP
 
Regression Testing: Down the Rabbit Hole (MEWT 2014)
Regression Testing: Down the Rabbit Hole (MEWT 2014)Regression Testing: Down the Rabbit Hole (MEWT 2014)
Regression Testing: Down the Rabbit Hole (MEWT 2014)
 
Is Groovy better for testing than Java?
Is Groovy better for testing than Java?Is Groovy better for testing than Java?
Is Groovy better for testing than Java?
 
Software testing with examples in Angular (and AngularJS)
Software testing with examples in Angular (and AngularJS)Software testing with examples in Angular (and AngularJS)
Software testing with examples in Angular (and AngularJS)
 
Unit testing
Unit testingUnit testing
Unit testing
 
TDD Basics with Angular.js and Jasmine
TDD Basics with Angular.js and JasmineTDD Basics with Angular.js and Jasmine
TDD Basics with Angular.js and Jasmine
 
Type mock isolator
Type mock isolatorType mock isolator
Type mock isolator
 
Code Review Matters and Manners
Code Review Matters and MannersCode Review Matters and Manners
Code Review Matters and Manners
 
Agile testing for mere mortals
Agile testing for mere mortalsAgile testing for mere mortals
Agile testing for mere mortals
 
Roy Osherove TDD From Scratch
Roy Osherove TDD From ScratchRoy Osherove TDD From Scratch
Roy Osherove TDD From Scratch
 
Intro to TDD
Intro to TDDIntro to TDD
Intro to TDD
 
How to structure testing within the Scrum Framework
How to structure testing within the Scrum FrameworkHow to structure testing within the Scrum Framework
How to structure testing within the Scrum Framework
 
Level Up Your Automated Tests
Level Up Your Automated TestsLevel Up Your Automated Tests
Level Up Your Automated Tests
 
Adopting tdd in the workplace
Adopting tdd in the workplaceAdopting tdd in the workplace
Adopting tdd in the workplace
 
Clean code - Getting your R&D on board
Clean code - Getting your R&D on boardClean code - Getting your R&D on board
Clean code - Getting your R&D on board
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
Exploratory testing
Exploratory testingExploratory testing
Exploratory testing
 
Introduction to test programming
Introduction to test programmingIntroduction to test programming
Introduction to test programming
 
Unit Testing talk
Unit Testing talkUnit Testing talk
Unit Testing talk
 
10 qa and testing
10 qa and testing10 qa and testing
10 qa and testing
 

Similar a How to Write Tests that Serve You Well

Introduction to Testing and TDD
Introduction to Testing and TDDIntroduction to Testing and TDD
Introduction to Testing and TDDSarah Dutkiewicz
 
Tester Challenges in Agile ?
Tester Challenges in Agile ?Tester Challenges in Agile ?
Tester Challenges in Agile ?alind tiwari
 
Generalization in Auto-Testing. How we put what we had into new Technological...
Generalization in Auto-Testing. How we put what we had into new Technological...Generalization in Auto-Testing. How we put what we had into new Technological...
Generalization in Auto-Testing. How we put what we had into new Technological...SQALab
 
Introduction to Test Driven Development
Introduction to Test Driven DevelopmentIntroduction to Test Driven Development
Introduction to Test Driven DevelopmentSarah Dutkiewicz
 
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)Dinis Cruz
 
Test analysis & design good practices@TDT Iasi 17Oct2013
Test analysis & design   good practices@TDT Iasi 17Oct2013Test analysis & design   good practices@TDT Iasi 17Oct2013
Test analysis & design good practices@TDT Iasi 17Oct2013Tabăra de Testare
 
Unit Testing, TDD and the Walking Skeleton
Unit Testing, TDD and the Walking SkeletonUnit Testing, TDD and the Walking Skeleton
Unit Testing, TDD and the Walking SkeletonSeb Rose
 
Agile San Diego: Testing as Exploration (Continuous Delivery w/o Automation)
Agile San Diego: Testing as Exploration (Continuous Delivery w/o Automation)Agile San Diego: Testing as Exploration (Continuous Delivery w/o Automation)
Agile San Diego: Testing as Exploration (Continuous Delivery w/o Automation)Maaret Pyhäjärvi
 
TDD and the Legacy Code Black Hole
TDD and the Legacy Code Black HoleTDD and the Legacy Code Black Hole
TDD and the Legacy Code Black HoleNoam Kfir
 
Agile testingandautomation
Agile testingandautomationAgile testingandautomation
Agile testingandautomationjeisner
 
Test specifications and designs
Test specifications and designs  Test specifications and designs
Test specifications and designs ahfameri
 
An Introduction to unit testing
An Introduction to unit testingAn Introduction to unit testing
An Introduction to unit testingSteven Casey
 
A Brief Introduction to Test-Driven Development
A Brief Introduction to Test-Driven DevelopmentA Brief Introduction to Test-Driven Development
A Brief Introduction to Test-Driven DevelopmentShawn Jones
 
Best practices for writing good automated tests
Best practices for writing good automated testsBest practices for writing good automated tests
Best practices for writing good automated testsFelipe Lima
 
Mixing testing types to improve your testing results
Mixing testing types to improve your testing resultsMixing testing types to improve your testing results
Mixing testing types to improve your testing resultsPractiTest
 

Similar a How to Write Tests that Serve You Well (20)

Introduction to Testing and TDD
Introduction to Testing and TDDIntroduction to Testing and TDD
Introduction to Testing and TDD
 
Tester Challenges in Agile ?
Tester Challenges in Agile ?Tester Challenges in Agile ?
Tester Challenges in Agile ?
 
Agile process
Agile processAgile process
Agile process
 
Generalization in Auto-Testing. How we put what we had into new Technological...
Generalization in Auto-Testing. How we put what we had into new Technological...Generalization in Auto-Testing. How we put what we had into new Technological...
Generalization in Auto-Testing. How we put what we had into new Technological...
 
Introduction to Test Driven Development
Introduction to Test Driven DevelopmentIntroduction to Test Driven Development
Introduction to Test Driven Development
 
Specification by example
Specification by exampleSpecification by example
Specification by example
 
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)
 
Agile test practices
Agile test practicesAgile test practices
Agile test practices
 
Skillwise Unit Testing
Skillwise Unit TestingSkillwise Unit Testing
Skillwise Unit Testing
 
Test analysis & design good practices@TDT Iasi 17Oct2013
Test analysis & design   good practices@TDT Iasi 17Oct2013Test analysis & design   good practices@TDT Iasi 17Oct2013
Test analysis & design good practices@TDT Iasi 17Oct2013
 
Unit Testing, TDD and the Walking Skeleton
Unit Testing, TDD and the Walking SkeletonUnit Testing, TDD and the Walking Skeleton
Unit Testing, TDD and the Walking Skeleton
 
Agile San Diego: Testing as Exploration (Continuous Delivery w/o Automation)
Agile San Diego: Testing as Exploration (Continuous Delivery w/o Automation)Agile San Diego: Testing as Exploration (Continuous Delivery w/o Automation)
Agile San Diego: Testing as Exploration (Continuous Delivery w/o Automation)
 
TDD and the Legacy Code Black Hole
TDD and the Legacy Code Black HoleTDD and the Legacy Code Black Hole
TDD and the Legacy Code Black Hole
 
Agile testingandautomation
Agile testingandautomationAgile testingandautomation
Agile testingandautomation
 
Test specifications and designs session 4
Test specifications and designs  session 4Test specifications and designs  session 4
Test specifications and designs session 4
 
Test specifications and designs
Test specifications and designs  Test specifications and designs
Test specifications and designs
 
An Introduction to unit testing
An Introduction to unit testingAn Introduction to unit testing
An Introduction to unit testing
 
A Brief Introduction to Test-Driven Development
A Brief Introduction to Test-Driven DevelopmentA Brief Introduction to Test-Driven Development
A Brief Introduction to Test-Driven Development
 
Best practices for writing good automated tests
Best practices for writing good automated testsBest practices for writing good automated tests
Best practices for writing good automated tests
 
Mixing testing types to improve your testing results
Mixing testing types to improve your testing resultsMixing testing types to improve your testing results
Mixing testing types to improve your testing results
 

Más de Agileee

Robin Dymond: "Your Brain and Better Product Development"
Robin Dymond: "Your Brain and Better Product Development"Robin Dymond: "Your Brain and Better Product Development"
Robin Dymond: "Your Brain and Better Product Development"Agileee
 
Lyssa Adkins & Michael Spayd: The Essential Transformations: How Agile Calls ...
Lyssa Adkins & Michael Spayd: The Essential Transformations: How Agile Calls ...Lyssa Adkins & Michael Spayd: The Essential Transformations: How Agile Calls ...
Lyssa Adkins & Michael Spayd: The Essential Transformations: How Agile Calls ...Agileee
 
Piotr Burdylo: Managing developers is complex
Piotr Burdylo: Managing developers is complexPiotr Burdylo: Managing developers is complex
Piotr Burdylo: Managing developers is complexAgileee
 
Nick Oostvogels: 5 Arguments Against Kanban
Nick Oostvogels: 5 Arguments Against KanbanNick Oostvogels: 5 Arguments Against Kanban
Nick Oostvogels: 5 Arguments Against KanbanAgileee
 
Anthony Marchenko: Опыт внедрения Kanban
Anthony Marchenko: Опыт внедрения KanbanAnthony Marchenko: Опыт внедрения Kanban
Anthony Marchenko: Опыт внедрения KanbanAgileee
 
Nataliya Trenina: Office magic
Nataliya Trenina: Office magicNataliya Trenina: Office magic
Nataliya Trenina: Office magicAgileee
 
Henrik Kniberg: Agile at home
Henrik Kniberg: Agile at homeHenrik Kniberg: Agile at home
Henrik Kniberg: Agile at homeAgileee
 
Henrik Kniberg: Lean from the Trenches keynote @ AgileEE
Henrik Kniberg: Lean from the Trenches keynote @ AgileEEHenrik Kniberg: Lean from the Trenches keynote @ AgileEE
Henrik Kniberg: Lean from the Trenches keynote @ AgileEEAgileee
 
Nathaniel Cadwell: The Art of Facilitation
Nathaniel Cadwell: The Art of Facilitation Nathaniel Cadwell: The Art of Facilitation
Nathaniel Cadwell: The Art of Facilitation Agileee
 
Scrum and kanban
Scrum and kanbanScrum and kanban
Scrum and kanbanAgileee
 
How To Change The World
How To Change The WorldHow To Change The World
How To Change The WorldAgileee
 
The Extreme Decade
The Extreme DecadeThe Extreme Decade
The Extreme DecadeAgileee
 
Agile Testing. Risks, Uncertainty and Why It All Works
Agile Testing. Risks, Uncertainty and Why It All WorksAgile Testing. Risks, Uncertainty and Why It All Works
Agile Testing. Risks, Uncertainty and Why It All WorksAgileee
 
Movivation 3.0
Movivation 3.0Movivation 3.0
Movivation 3.0Agileee
 
Effective Software Development in the 21st Century
Effective Software Development in the 21st CenturyEffective Software Development in the 21st Century
Effective Software Development in the 21st CenturyAgileee
 
Myths, Legends and Monsters of Enterprise Agility
Myths, Legends and Monsters of Enterprise AgilityMyths, Legends and Monsters of Enterprise Agility
Myths, Legends and Monsters of Enterprise AgilityAgileee
 
Lightening Talk: Software craftsmanship
Lightening Talk: Software craftsmanshipLightening Talk: Software craftsmanship
Lightening Talk: Software craftsmanshipAgileee
 
Lightening Talk: Lean start up
Lightening Talk: Lean start upLightening Talk: Lean start up
Lightening Talk: Lean start upAgileee
 
Lightening Talk: lama sutra of retrospective
Lightening Talk: lama sutra of retrospectiveLightening Talk: lama sutra of retrospective
Lightening Talk: lama sutra of retrospectiveAgileee
 
Lightening Talk: Just do it eng
Lightening Talk: Just do it engLightening Talk: Just do it eng
Lightening Talk: Just do it engAgileee
 

Más de Agileee (20)

Robin Dymond: "Your Brain and Better Product Development"
Robin Dymond: "Your Brain and Better Product Development"Robin Dymond: "Your Brain and Better Product Development"
Robin Dymond: "Your Brain and Better Product Development"
 
Lyssa Adkins & Michael Spayd: The Essential Transformations: How Agile Calls ...
Lyssa Adkins & Michael Spayd: The Essential Transformations: How Agile Calls ...Lyssa Adkins & Michael Spayd: The Essential Transformations: How Agile Calls ...
Lyssa Adkins & Michael Spayd: The Essential Transformations: How Agile Calls ...
 
Piotr Burdylo: Managing developers is complex
Piotr Burdylo: Managing developers is complexPiotr Burdylo: Managing developers is complex
Piotr Burdylo: Managing developers is complex
 
Nick Oostvogels: 5 Arguments Against Kanban
Nick Oostvogels: 5 Arguments Against KanbanNick Oostvogels: 5 Arguments Against Kanban
Nick Oostvogels: 5 Arguments Against Kanban
 
Anthony Marchenko: Опыт внедрения Kanban
Anthony Marchenko: Опыт внедрения KanbanAnthony Marchenko: Опыт внедрения Kanban
Anthony Marchenko: Опыт внедрения Kanban
 
Nataliya Trenina: Office magic
Nataliya Trenina: Office magicNataliya Trenina: Office magic
Nataliya Trenina: Office magic
 
Henrik Kniberg: Agile at home
Henrik Kniberg: Agile at homeHenrik Kniberg: Agile at home
Henrik Kniberg: Agile at home
 
Henrik Kniberg: Lean from the Trenches keynote @ AgileEE
Henrik Kniberg: Lean from the Trenches keynote @ AgileEEHenrik Kniberg: Lean from the Trenches keynote @ AgileEE
Henrik Kniberg: Lean from the Trenches keynote @ AgileEE
 
Nathaniel Cadwell: The Art of Facilitation
Nathaniel Cadwell: The Art of Facilitation Nathaniel Cadwell: The Art of Facilitation
Nathaniel Cadwell: The Art of Facilitation
 
Scrum and kanban
Scrum and kanbanScrum and kanban
Scrum and kanban
 
How To Change The World
How To Change The WorldHow To Change The World
How To Change The World
 
The Extreme Decade
The Extreme DecadeThe Extreme Decade
The Extreme Decade
 
Agile Testing. Risks, Uncertainty and Why It All Works
Agile Testing. Risks, Uncertainty and Why It All WorksAgile Testing. Risks, Uncertainty and Why It All Works
Agile Testing. Risks, Uncertainty and Why It All Works
 
Movivation 3.0
Movivation 3.0Movivation 3.0
Movivation 3.0
 
Effective Software Development in the 21st Century
Effective Software Development in the 21st CenturyEffective Software Development in the 21st Century
Effective Software Development in the 21st Century
 
Myths, Legends and Monsters of Enterprise Agility
Myths, Legends and Monsters of Enterprise AgilityMyths, Legends and Monsters of Enterprise Agility
Myths, Legends and Monsters of Enterprise Agility
 
Lightening Talk: Software craftsmanship
Lightening Talk: Software craftsmanshipLightening Talk: Software craftsmanship
Lightening Talk: Software craftsmanship
 
Lightening Talk: Lean start up
Lightening Talk: Lean start upLightening Talk: Lean start up
Lightening Talk: Lean start up
 
Lightening Talk: lama sutra of retrospective
Lightening Talk: lama sutra of retrospectiveLightening Talk: lama sutra of retrospective
Lightening Talk: lama sutra of retrospective
 
Lightening Talk: Just do it eng
Lightening Talk: Just do it engLightening Talk: Just do it eng
Lightening Talk: Just do it eng
 

How to Write Tests that Serve You Well

  • 1. Tests Test Paweł L. Lipiński (or how to write tests so that they serve you well)
  • 2. pawel@agileee:/etc$whoami • 13 years as a developer • >10 years in Java • i did : development, consulting, trainings, audits, architecture, team leading • now: ‣ developer, coach & owner of pragmatists • 2nd time @ agileee
  • 3. Agenda • writing tests so that they’re reliable • writing tests so that they document code • writing tests so that they’re maintainable • writing tests so that they’re readable
  • 4. What do tests give? Tests • awareness of what is supposed to be written • feeling of safety while refactoring • feeling of safety while changing code • increase in development speed • executable documentation
  • 5. So whatʼs the problem? • Whenever you change something - they stop working • They become harder and harder to maintain • They soon start to look like this • If there’s many of them, it’s hard to know where to look to learn something about the system
  • 6. Process • Think First • Trivial First • Test specifies „what”, implementation says „how” • Different levels of tests
  • 7. Conventions • coherent naming of test classes • coherent naming of tests • test classes’ names describing behaviour not the class’ name • test methods’ names should describe test case, not method being tested • code conventions
  • 8. Comments • if you feel you must comment, something’s wrong with your code • tests should document code, so they must be SUPERCOMPREHENSIBLE • though comments are useful sometimes... // given // when // then
  • 9. Formatting • coherent formatting throughout the codebase • separation of logical fragments • eyes used to it = quicker understanding
  • 10. Given (test setup) • DRY (setup methods should be business-like) • setup method COMPREHENSIBLE • @Before vs. explicite call
  • 11. Error handling • One test, one exception • NEVER: @Test(expected = Exception.class) Use only CONCRETE, UNIQUE exception • try / catch @Rule public ExpectedException throwing = ExpectedException.none(); ... ... // when throwing.expect(ParseException.class); parser.parse(text); // then exception is thrown
  • 12. Behaviour Driven Development • define behaviours not tests • behaviours constitute a functional spec of the application • behaviours should be worked upon by business people together with developers • focus on why the code should exist • naming in code is the same as names used by the business people (ubiquitous language)
  • 13. Defining behaviour As a conference attendee I want to get a restration status after signing up for a conference so that I know if the registration went fine: Given a conference „Agileee” When I try to register to it and the registration is successful Then I get a confirmation message: „You are registered to Agileee. An email with details has been sent to you.” Given a conference „Agileee” When I try to register to it but there are no free places Then I get a message: „Sorry. No free places left. Try the next year!”
  • 14. Examples, not Tests • BDD helps to think about objects from the perspective of their behaviours, so the code is more object-oriented • examples help you create a „mental” model of the system • test class shows examples of use of a functionality • test code is an example of behaviour • test code is also an example of use
  • 15. BDD naming Story, Scenario public class AddingBooksToLibraryTest { @Mock private BookRepository bookRepository; @Test public void shouldEnableAddingNewBooks() { // given Library library = new Library(bookRepository); Book book = new Book("Children from Bullerbyn"); // when library.add(book); // then assertThat(library.size()).is(1); verify(bookRepository).save(book); } }
  • 16. BDD rules • test names should be sentences • simple constant template of the sentence helps you focus in the test on one thing public void shouldBeSearchedByName() • understandable test name helps when the test fails • test are examples - think about them not as a means for future verification, but as a documentation of behaviour
  • 18.
  • 19. A-TDD • Acceptance tests may drive the development of scenarios. • But the need to be: ‣ written by business people (or at least with them nearby) ‣ verify correctness of scenario accomplishment (be complete and fulfill acceptance criteria) ‣ be automatic ‣ be maintainable • These are high-level tests, so changes to the application may force you to modify many of them
  • 20. Whole system tests organisation • Tests in the same packages as SUT vs. separately • Tests named by the functionality vs. tests named by tested classes • Tests’ speed • Test levels clicking acceptance integration unit
  • 21. Test smells • Long setup - lack of factory method, or perhaps a problem with the structure of created objects? • Long tests - perhaps you’re testing more than one behaviour at a time? • Many assertions - doesn’t the tested method have too many responsibilities? • Too many test methods in a test class - class under test has too many responsibilities? Or maybe you’re testing more than one functionality in a single class?
  • 22. Maintainable tests • Reuse assertions, create „business” assertions • Reuse object construction methods - don’t be sensitive to changes of constructors • Reuse test setup • Tests should not depend on environment and order of execution • Avoid many assertions - when the first one fails, others are not executed (they could’ve give you a clue about possible reasons) • Separate assertion from the action to increase readability (or better use given/when/then pattern) • Use variables to pass and verify values in tests • Remove tests ONLY when you remove a functionality or when tests’ responsibilities overlap
  • 24. Thank you! pawel.lipinski@pragmatists.pl http://www.pragmatists.pl All pictures were used exclusively to set the presentation context and advertise the original book.