• 1. Behaviour Driven Development with Java
  • 2. ContentWhat BDD is? Jbehave JBehave and Selenium References 2
  • 3. BDD 3BDD is an evolution of test-driven development (TDD) and acceptance-test driven design, and is intended to make these practices more accessible and intuitive(直观的) to newcomers and experts alike. It shifts the vocabulary from being test-based to behaviour-based, and positions itself as a design philosophy.
  • 4. Test-Driven Development (TDD)Approach(方法和途径) for developing software by writing tests before writing the code being tested 4Write little testWatch test failGet test passRefactor
  • 5. Test-Driven Development (TDD) Facilitates(促进) Software Design Express Software Behaviour Documents the Code 5
  • 6. Unit TestingA form of TDD Meets developer’s expectations for the code behaviour Fragile(脆的) – Too coupled to the implementation Should meet user’s expectations 6
  • 7. User’s ExpectationsUse Cases User Stories preferred in Agile projects Both of them have no validating mechanisms(验证机制) that the code meets user’s expectations7
  • 8. Testing Types and Expectations8Application Levels Testing TypeExpectations UI / Presentation / …Controls / Services / …Classes / Models / …Code Meets Customer’s Expectations Code Meets Programmer’s Expectations Unit TestingBDDSelenium
  • 9. DDD and UbiquitousLanguageDomain Driven Design Approach to developing software for complex needs by deeply connecting the implementation to an evolving model of the core business concepts Ubiquitous (普遍) Language (UL) "A language structured around the domain model and used by all team members to connect all the activities of the team with the software" – Domain Driven Design by Eric Evans.9
  • 10. Executable DocumentationThe system requirements are usually expressed by textual documentation In the ideal world the documentation uses UL If this documentation was executable, it would be perfect! It would assure that the code continues to meet the expectations in long term10
  • 11. Behaviour Driven DesignA TDD approach It is an executable documentation Helps for UL development and usage Clears out the misunderstandings between customers, domain experts, developers, QA team etc. Can be used by everybody involved in a project11
  • 12. BDD as Stories and BehaviourBDD can be used to express Stories and Behaviour Stories Correspond to User Stories Express application behaviour at high level Stories framework needed (eventually) Behaviour (or Spec) Corresponds to expectations at class level Expresses behaviour at service/component level 12
  • 13. Stories and BehaviourUser Stories Series of acceptance criteria Called scenarios Each scenario has givens, events and outcomes Used in Agile projects Behaviour Expressed as a test method It defines what the application should / shouldn’t do13
  • 14. A Story StructureNarrative (叙述) As a [some_role_here] I want [some_feature_here] So that [behefit/value_of_the_feature_here] Scenario(s) (this is acceptance criteria) Given [some_initial_condition(s)] When [event(s)_occurs] Then [ensure_some_outcome(s)] 14
  • 15. BDD Process15StoriesBehaviourApplicationExercise expectations againstMatches toCustomerQADomain ExpertDeveloper
  • 16. BDD Process16
  • 17. BDD ProcessCreate scenarios for expected features Then follow the process: For each scenario describing a feature Run the scenario – it fails (go red) Define the first step – go red Write down the application code getting the step to pass – go green Refactor the code and repeat steps 4 & 5 for each step until 6 The scenario passes – go green Refactor the application code 17
  • 18. BDD ToolsC – Cspec C++ – CppSpec, Spec-CPP .Net – NBehave, NSpecify, SpecFlow Groovy – GSpec, easyb, Cuke4Duke PHP – PHPSpec Python – Specipy Ruby – RSpec, Shoulda, Cucumber More…18
  • 19. BDD Tools (Java Related)JBehave – Java annotations based, Test frameworks agnostic Cuke4duke – Cucumber support for JVM JDave – RSpec (Ruby) inspired, Mojo 2 & Hamcrest based beanSpec – Java based easyb – Java based, Specifications written in Groovy instinct – BDD framework for Java, providing annotations for contexts. Inspired by Rspec BDoc - Extracts behaviour from unit tests19
  • 20. JBehave20
  • 21. JBehave - FeaturesPure Java implementation Text-based user stories Annotation-based binding of textual steps to Java methods DI support (Spring, Guice, Pico, Weld) Story reporting (HTML, TXT, XML) User stories localization IDE integration Ant and Maven integration Test frameworks agnostic (JUnit, hamcrest, etc.)21
  • 22. JBehave Web - FeaturesExtension of JBehave providing web integration layer for BDD Features JBehave Queue – allows generic stories to be run asynchronously Web Runner – allows generic stories to be run synchronously Selenium Integration – automation of stories for web apps using Selenium 22
  • 23. JBehave – Five Steps Overview23 Write a story Map steps to Java Configure Stories Run Stories View Reports
  • 24. JBehave – Five Steps OverviewStep 1 – Write a story24
  • 25. JBehave – Five Steps OverviewStep 2 – Map steps to Java25
  • 26. JBehave – Five Steps OverviewStep 3 – Configure stories26
  • 27. JBehave – Five Steps Overview27
  • 28. JBehave – Five Steps Overview28
  • 29. JBehave StoriesPlain-text stories Consists of narrative and multiple scenarios Usually stored as .story file, but this is configurable Narrative Optional As a, In order to, I want to A scenario consists of: Given, When, Then And maps to any of them Possible use of When after Then Scenarios could depend on others scenario GivenScenarios Comments (!--)29
  • 30. JBehave StepsDeclared as Java annotations Steps annotations @Given, @When, @Then Lifecycle annotations @BeforeStory, @AfterStory @BeforeScenario, @AfterScenario Pending steps @Pending keyword 30
  • 31. JBehave StepsStep annotations take regex See Code Example Alias(es) – mapping various text strings to one method @Alias, @Aliases See Code Example Parameter Injection Captured values are converted to method parameters @Named – Explicit mapping of values to parameters See Code Example 31
  • 32. JBehave ConfigurationEverything is configurable (powerful) Everything has defaults (makes life easy) Main Configuration How to load stories (classpath, file, etc.) Story file naming and parsing configuration Error strategy and Pending error strategy How to handle failure and missing steps Step Configuration Parameter Converters 32
  • 33. JBehave ConfigurationEmbedder and Embeddable 33
  • 34. JBehave ConfigurationJbehave provides two Embeddable implementations ConfigurableEmbedder InjectableEmbedder (example AnnotatedEmbedder) JUnit-enabled Embeddables Ran like JUnit tests JUnitStory - one-to-one mapping with the textual story JUnitStories - many-to-one mapping Exntending Embedder EclipseEmbedder example 34
  • 35. JBehave – AdvancedParameterized Scenarios Examples: - required in the story Followed by table of parameters The mapped parameters should be surrounded by '<‘ and '>‘ in the story Table examples require named parameters for the step candidates to be matched to the Java methods The step annotation pattern must hold the verbatim textual step(必须保持原封不动地诠释文本的一步) The tables could be loaded from external resources35
  • 36. JBehave – AdvancedAnt tasks and Maven plugin Integration with Spring, Pico, Guice Reporting options Console, Text, HTML, XML Default reports location in a Maven project: ${project.dir}/target/jbehave Example Test integration (JUnit and TestNG) See AnnotatedEmbedder example36
  • 37. JBehave Reporting OptionsFailing Story HTML Report37
  • 38. JBehave Reporting OptionsPending Steps Story HTML Report38
  • 39. JBehave Reporting OptionsParametrized Story HTML Report39
  • 40. JBehave – Eclipse PluginHome Page Status: In development Non-trivial installation (next slides) Not very rich functionality but makes the life easier Provides Basic highlighting On match, the step in the story is linked to the mapped method Certain autocomplete when writing stories 40
  • 41. JBehave – Eclipse PluginExample Keywords highlighting “Jumping” from story to Steps class Autocomplete41
  • 42. JBehave – Install Eclipse PluginDownload the plugin42
  • 43. JBehave – Install Eclipse PluginEclipse > File > Import43
  • 44. JBehave – Install Eclipse PluginThe story files are with different icon 44
  • 45. JBehave – Install Eclipse PluginNot “recognized” stories > Select + Right Click > Open With > Behavior Editor45
  • 46. JBehave – Install Eclipse PluginNow the keywords are highlighted46
  • 47. Jbehave and Selenium47
  • 48. JBehave and SeleniumSelenium A suite of tools to automate web app testing across many platforms. Abstracts away the interaction with the web layer (browser/server) 48Java, Perl, C#, C, etc.Selenium ObjectTested WebAppSelenium RC ServerBrowsers
  • 49. JBehave and SeleniumSelenium would let us focus on testing the web-app functionality Although, steps classes get cluttered by selenium calls 49StepsSelenium ObjectTested WebAppSelenium RC ServerBrowsersStories
  • 50. JBehave and SeleniumJBehave and Selenium First thought - Steps will interact with the selenium object from the steps classes50StepsSelenium ObjectTested WebAppSelenium RC ServerBrowsersStories
  • 51. JBehave and SeleniumPage Objects Pattern Page object represent the services offered by a page Hides the knowledge of the page structure from the developer51StepsSelenium ObjectTested WebAppSelenium RC ServerBrowsersStoriesPage Object
  • 52. JBehave and SeleniumRules of Thumb Keep assertions in the steps mapping classes Keep selenium interaction in the page objects Stories should address the functionality which the pages offer 52
  • 53. JBehave and SeleniumWhat do we need to integrate JBehave and Selenium SeleniumConfiguration (part of JBehave Web) @BeforeScenario, @AfterScenario steps Responsible of start/stop selenium object Pages and Steps implementation Running selenium tests in an automated way (maven – integration-test phase) Tip: Configure Firefox for testing with Selenium 53
  • 54. Use Case – Web TestingWeb app for our Use Case 2 JSPs – one for main form, another for result In order to run it are required: Run the web app on a web server Run the Selenium RC server with the selenium profile (see tip from prev. slide) Execute WebBmiCalculatorStories embedder as JUnit test54
  • 55. JBehave - Pros and Cons55
  • 56. Use Case & Examples CodeUse Case Code – Consists of 3 Maven 2 projects jug-bg-bdd-domain Domain Classes of the Application jug-bg-bdd-jbehave JBehave Examples (depending on the first project) jug-bg-bdd-web JBehave & Selenium Examples (depending on the first project)56
  • 57. Use Case & Examples CodeSource Code could be found on: http://code.google.com/p/bg-jug-resource-repository/57
  • 58. ReferencesBDD Wiki Jbehave JBehave Tutorial Dan North – Introducing BDD Dan North - What’s in a Story? [pdf] BDD in Java and Groovy [pdf] TDD Beyond Junit BDD in a Nutshell 58
  • 59. ReferencesRyan Greenhall – BDD by Example Localizing JBehave Scenarios Eric Evans - "Domain-Driven Design: Tackling Complexity in the Heart of Software", Addison-Wesley JBehave Site :: Dependency Injection JBehave + Spring + Selenium Example 59
  • 60. ReferencesSelenium Project Page Objects Pattern Creating Firefox Profile for Selenium RC Tests JBehave Site :: Using Selenium BDD with JBehave Web 3, Selenium and Maven 2 for OS X Leopard Nice JBehave + Selenium + Maven Example Selenium Tutorial to set up a Selenium Grid 60
  • 61. Thank you for your attention!61