SlideShare une entreprise Scribd logo
1  sur  104
Le Tour de xUnit JavaOne 2011 AbdelmonaimRemani abdelmonaim.remani@gmail.com
License Creative Commons Attribution-NonCommercial3.0 Unported http://creativecommons.org/licenses/by-nc/3.0/
Who Am I? Software Engineer Particularly interested in technology evangelism and enterprise software development and architecture President and Founder of a number of organizations The Chico Java User Group The Silicon Valley Spring User Group LinkedIn http://www.linkedin.com/in/polymathiccoder Twitter http://twitter.com/polymathiccoder
                 Warning This presentation is very long and covers a lot of material
Outline Part I: Unit Testing Vanilla Is Boring Stay PUT All Those Theories All that CRUD Fakery Mockery Part II: TDD Part III: BDD Part IV: Tools Cross-cutting Story Time When I tell you a story Libra-palooza When I tell you about the coolness of some libraries
There Will Be Code!
Part I - Unit Testing
What is Unit Testing? What is a Unit? The smallest piece of code that Can be isolated Is testable Targets specific functionality Hmm… Let’s see… A statement? A branch? A method? A basis path within a method Defined by the flow of execution from the start of a method to its exit How many a method has depends on cyclomatic complexity N decisions = 2^N basis possible paths Infinite paths
What is Unit Testing? What kind of Testing? The verification of Intent The answer to the question: Does the code do what the developer intended for it to do? Reliability The answer to the question: Can I depend or build upon it?
xUnitand xUnit Concepts xUnit is any Unit Testing framework Based on SUnit, a Smalltalk project, design by Kent Beck Concepts Test fixtures Test case Assertions Test execution Test suites
Good Test Data Include Valid data Invalid data / Boundary conditions Different Formats Different Order Wide Range Null data Error Conditions
Good Tests Cover all possible basis paths Have Self-Describing Names Are Cohesive Independent of each other Reliable Repeatable Fast
The Most Opinionated Slide! Lame Excuses! Waste of time Nuisance Distraction from real work Hard to maintain Blah… Blah… Blah… 3 bullet points Quit being lazy! Do yourself a favor and get with the program! You are attitude is the fastest way to get inducted to the Hall of Lame
xUnit Frameworks in Java The most popular frameworks JUnit A port of the original SUnit to Java by Erich Gamma and Kent Beck http://junit.org/ TestNG http://testng.org/ This presentation focuses on JUnit
Vanilla Is Boring
Story Time
The Quadratic Equation
The Quadratic Equation
The Code QuadraticEquation.java https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/main/java/com/polymathiccoder/talk/xunit/domain/QuadraticEquation.java
Testing the Quadratic Equation Vanilla Unit Tests
The Quadratic Equation 3 possible data combinations that must be tested Coefficients yielding a negative discriminant Coefficients yielding a discriminant equals to zero Coefficients yielding a positive discriminant 3 different outcomes The equation has no real solution The equation has one real solution The equation has two real solution 3 different basis paths
JUnit Annotations Test suites @RunWith Naming Convention <Class Name>Test Test fixtures Set Up @Before @BeforeClass Tear Down @After @AfterClass
JUnit Annotations Tests @Test Naming Convention <Method Name>_<State Under Test>_<Expected Behavior> Assertions assertTrue, assertEquals, assertThat, assertNull, etc…
Testing Private Methods Don’t test them Relax the visibility to make the code testable Annotate Google Guava’s @VisibleForTesting Use a nested test class Use reflection
The Code QuadraticEquationTest.java https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/test/java/com/polymathiccoder/talk/xunit/domain/QuadraticEquationTest.java
Stay PUT
Testing the Quadratic Equation Parameterized Unit Tests
Stay PUT Parameterized or Data-Driven Unit Tests Annotations @RunWith(Parameterized.class) To provide the parameters to be supplied via constructor injection @Parameters public static Collection<Object[]> parameters() @Parameter Object[] parameters
Libra-palooza Featuring the coolest JUnit extensions and libraries
Libra-palooza Hamcrest Matchers Library Included in JUnit since 4.4 http://code.google.com/p/hamcrest/ Unitils Reflection-based assertions, etc… http://unitils.org Fest Fluent Assertion, etc… http://code.google.com/p/fest/
The Code QuadraticEquationParameterizedTest.java https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/test/java/com/polymathiccoder/talk/xunit/domain/QuadraticEquationParameterizedTest.java
All Those Theories
Story Time
The River Crossing Puzzle
The River Crossing Puzzle
The Code RiverCrossing.java https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/main/java/com/polymathiccoder/talk/xunit/domain/RiverCrossing.java
Testing the River Crossing Puzzle Theories
The River Crossing Puzzle 9 possible combinations that must be tested Wolf  and Cabbage left behind Cabbage and Wolf left behind Wolf and Goat left behind Goat and Wolf left behind Goat and Cabbage left behind Cabbage and Goat left behind Wolf and Wolf left behind Goat and Goat left behind Cabbage and Cabbage left behind 3 different outcomes One gets transported to the other side One of two left behind eats the other Error trying to transport more than one 18 basis paths
The River Crossing Puzzle 9 possible combinations that must be tested and 3 basis paths yielding 3 different outcomes 9 x 3 = 18    Vanilla Tests 3 x 3 = 9      Parameterized Tests 1 x 3 = 3      Theories
Theories Running tests with every possible combination of data points Annotations @RunWith(Theories.class) To provide the parameters to be supplied via constructor injection @DataPoints public static Object[] objects @DataPoint public static object
Assumptions and Rules Assumptions assumeThat, assumeTrue, assumeNotNull, etc… Rules Allowing for alterations in how test methods are run and reported @Rule Injects public fields of type MethodRule ErrorCollector ExpectedException ExternalResource TemporaryFolder TestName TestWatchman Timeout Verifier
The Code RiverCrossingTheory.java https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/test/java/com/polymathiccoder/talk/xunit/domain/RiverCrossingTheory.java
All That CRUD
Story Time
The Employee Database
The Employee Database Simple Domain Object Employee Id - Number Name - Text Data-Access Object Interface EmployeeDao – CRUD operations Two implementations EmployeeCollectionImpl – A Java Collection implementation EmployeeDaoDbImpl – A JDBC implementation
The Code Employee.java https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/main/java/com/polymathiccoder/talk/xunit/domain/Employee.java EmployeeDao.java https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/main/java/com/polymathiccoder/talk/xunit/repository/EmployeeDao.java
The Code EmployeeDaoCollectionImpl.java https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/main/java/com/polymathiccoder/talk/xunit/repository/EmployeeDaoCollectionImpl.java EmployeeDaoDbImpl.java https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/main/java/com/polymathiccoder/talk/xunit/repository/EmployeeDaoDbImpl.java
Testing the Employee Database All that CRUD
Testing Persistence Code  Data Define the initial state of data before each test Define the expected state of data after each test Ensure that the data is in a known state before you run the test Run the test Compare against the expected dataset to determine the success or failure of the test Clean after yourself if necessary
Testing Persistence Code  Notes of Java Collections An Immutable/un-modifiable collection is NOT necessarily a collection of Immutable/un-modifiable objects Notes on testing database code Use a dedicated database instance for testing per user Use an in-memory database if you can HSQLDB H2 Etc…
Custom Hamcrest Matches Hamcrest Matches Write your own custom type-safe matcher One asserting per unit test Generating a readable description to be included in test failure messages https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/test/java/com/polymathiccoder/talk/xunit/domain/matcher/EmployeeIsEqual.java
Libra-palooza Featuring the coolest JUnit extensions and libraries
Libra-palooza HamSandwich http://code.google.com/p/hamsandwich/ Hamcrest Text Patterns http://code.google.com/p/hamcrest-text-patterns/
The Code EmployeeDaoCollectionImplTest.java https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/test/java/com/polymathiccoder/talk/xunit/repository/EmployeeDaoCollectionImplTest.java
Libra-palooza Featuring the coolest JUnit extensions and libraries
Libra-palooza DBUnit A JUnit extension used to unit test database code Export/Import data to and from XML Initialize database into a known state Verify the state of the database against an expected state http://www.dbunit.org/
Libra-palooza Unitils Database testing, etc… Integrates with DBUnit Annotations @RunWith(UnitilsJUnit4TestClassRunner.class) @DataSet @ExpectedDataSet @TestDataSource http://unitils.org
The Code EmployeeDaoDbImplTest.java https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/test/java/com/polymathiccoder/talk/xunit/repository/EmployeeDaoDbImplTest.java
Fakery
The Mailer
The Mailer Simple email sender that uses the JavaMailAPI Fakes Dumpster A fake SMTP server to be used in unit tests http://quintanasoft.com/dumbster/ ActiveMQ An embedded broker (Make sure to disabled persistence) http://activemq.apache.org/
The Code Mailer.java https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/main/java/com/polymathiccoder/talk/xunit/repository/Mailer.java MailerTest.java https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/test/java/com/polymathiccoder/talk/xunit/repository/MailerTest.java
Libra-palooza Featuring the coolest JUnit extensions and libraries
Libra-palooza XMLUnit http://xmlunit.sourceforge.net/ HTMLUnit http://htmlunit.sourceforge.net/ HttpUnit http://httpunit.sourceforge.net/ Spring Test http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/testing.html
Mockery
Story Time
The Egyptian Plover & the Nile Crocodile
The Egyptian Plover & the Nile Crocodile Herodotus in “The Histories” claimed that there is a symbiotic relationship between the Egyptian Plover and the Nile Crocodile
The Code EgyptianPlover.java https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/main/java/com/polymathiccoder/talk/xunit/domain/EgyptianPlover.java
Testing the Egyptian Plover & the Nile Crocodile Mocking
The Egyptian Plover & the Nile Crocodile 3 different basis path The plover finds the crocodile’s mouth closed and flies away The plover finds the crocodile’s mouth open, doesn’t find any leeches, then flies away The plover finds the crocodile’s mouth open, picks the leeches, then flies away 3 different outcomes False is returned indicating that the plover didn’t eat An exception is thrown and False is returned indicating that the plover didn’t eat True indicating that the plover ate
Mocking Dependencies need to be mock to test in isolation Simulating an object to mimic the behavior of a real object in a controlled manner
Mocking Dependencies need to be mock to test in isolation Simulating an object to mimic the behavior of a real object in a controlled manner
Libra-palooza Featuring the coolest JUnit extensions and libraries
Libra-palooza Mockito The coolest mocking framework there is Annotations @RunWith(MockitoJUnitRunner.class) @Mock @InjectMocks @Spy Stub method calls Verify interactions http://code.google.com/p/mockito/
The Code EgyptianPloverTest.java https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/test/java/com/polymathiccoder/talk/xunit/domain/EgyptianPloverTest.java
This is a digitally constructed image from the Warren Photographic Image Library of Nature and Pets http://www.warrenphotographic.co.uk/
Miscellaneous Topics
Test Suites and Groups Annotations @Category @RunWith(Categories.class) @IncludeCategory @ExcludeCategory @SuiteClasses
The Code FastTest.java SlowTest.java SlowAndFastTest.java SlowTestSuite.java https://github.com/PolymathicCoder/LeTourDeXUnit/tree/master/src/test/java/com/polymathiccoder/talk/xunit/misc
Miscellaneous Topics Testing AOP (Aspect-Oriented Programming) Code Unit Testing the Advice Verify the execution of the Advice when Joint Point is reached Testing Concurrency In Junit Concurrent test execution Annotations @Concurrent @RunWith(ConcurrentSuite.class) GroboUtils http://groboutils.sourceforge.net/ ConcJUnit http://www.cs.rice.edu/~mgricken/research/concutest/concjunit/
Part II – TDDTest-Driver Development
This Is How We Have Been Doing It
Why Not Test First Instead? Most of us are just not disciplined to test last In order to determine a sets of verifications in the form tests to fulfill the requirements No room for misunderstanding Testable code is good code When you let testing drive the implementation A test-driven implementation is testable by definition No refactoring will be necessary
What if? Design Testing Write failing tests Implementation Get the tests to pass
The TDD Way
Part III – BDDBehavior-Driver Development
TDD Is Great, But… TDD works But Thinking of requirements in terms of tests is NOT easy Syllogism Tests verify requirements Requirements define behavior Tests verify behavior Neuro-Linguistic Programming (NLP) suggests that the words we use influence the way we think What if we start using terminology that focuses on the behavioral aspects of the system rather than testing?
The BDD Way BDD is simply a rephrased TDD The focus on behavior Bridges the gap between Business users and Technologists Makes the development goals and priorities more aligned with business requirements TDD vs. BDD Verification State-Based Bottom-Up approach Specification Interaction-Based Outside-In Approach
The BDD Way “Behavior-Driven Development (BDD) is about implementing an application by describing it from the point of view of its stakeholders” – Jbehave.org
BDD Concepts Story A description of a feature that has business value As a [Role], I want to [Feature] So that I [Value] Sounds familiar? Agile for you!
BDD Concepts Scenario A description of how the user expects the system to behave using a sequence of steps Step Can be a context, an event, or an outcome Given [Context] When [Event] Then [Outcome]
BDD in Java JBehave Very powerful and flexible Well-documented Separation of story files from code http://jbehave.org EasyB http://www.easyb.org/ Concordion http://www.concordion.org/
Testing the Quadratic Equation Stories, Scenarios, and Steps
The Quadratic Equation 3 possible data combinations that must be tested Coefficients yielding a negative discriminant Coefficients yielding a discriminant equals to zero Coefficients yielding a positive discriminant 3 different outcomes The equation has no real solution The equation has one real solution The equation has two real solution 3 different basis paths
BDD with JBehave Write the story Map the steps to a POJO @Given @When @Then Configure the stories @Configure Run the stories @RunWith(AnnotatedEmbedderRunner.class) @UsingEmbedder @UsingSteps View Reports
The Code quadraticEquation.story https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/test/java/com/polymathiccoder/talk/xunit/domain/quadraticEquation.story QuadraticEquationStories.java https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/test/java/com/polymathiccoder/talk/xunit/domain/QuadraticEquationStories.java
Part IV - Tools
Tools Code Coverage Cobertura http://cobertura.sourceforge.net/ EMMA http://emma.sourceforge.net/ Continuous Integration On the server: Jenkins/Hudson http://jenkins-ci.org/ On your IDE: Infinitest http://infinitest.github.com/
Q & A
Material The Slides http://www.slideshare.net/PolymathicCoder The Code https://github.com/PolymathicCoder/LeTourDeXUnit The Speaker Email: abdelmonaim.remani@gmail.com Twitter: @polymathiccoder LinkedIn: http://www.linkedin.com/in/polymathiccoder
Thank You

Contenu connexe

Tendances

basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operatorkamal kotecha
 
Advanced java
Advanced java Advanced java
Advanced java NA
 
Introduction to the Java(TM) Advanced Imaging API
Introduction to the Java(TM) Advanced Imaging APIIntroduction to the Java(TM) Advanced Imaging API
Introduction to the Java(TM) Advanced Imaging APIwhite paper
 
Java interview-questions-and-answers
Java interview-questions-and-answersJava interview-questions-and-answers
Java interview-questions-and-answersbestonlinetrainers
 
Java questions and answers jan bask.net
Java questions and answers jan bask.netJava questions and answers jan bask.net
Java questions and answers jan bask.netJanbask ItTraining
 
Bea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guideBea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guidePankaj Singh
 
Core java interview questions
Core java interview questionsCore java interview questions
Core java interview questionsRohit Singh
 
Java programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, MysuruJava programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, MysuruNithin Kumar,VVCE, Mysuru
 
Introduction to Java
Introduction to Java Introduction to Java
Introduction to Java Hitesh-Java
 
Notes of java first unit
Notes of java first unitNotes of java first unit
Notes of java first unitgowher172236
 
1 java programming- introduction
1  java programming- introduction1  java programming- introduction
1 java programming- introductionjyoti_lakhani
 
Introduction to java
Introduction to java Introduction to java
Introduction to java Sandeep Rawat
 

Tendances (20)

basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operator
 
Advanced java
Advanced java Advanced java
Advanced java
 
Java notes
Java notesJava notes
Java notes
 
Introduction to the Java(TM) Advanced Imaging API
Introduction to the Java(TM) Advanced Imaging APIIntroduction to the Java(TM) Advanced Imaging API
Introduction to the Java(TM) Advanced Imaging API
 
Java basics
Java basicsJava basics
Java basics
 
Core Java
Core JavaCore Java
Core Java
 
Java interview-questions-and-answers
Java interview-questions-and-answersJava interview-questions-and-answers
Java interview-questions-and-answers
 
Java questions and answers jan bask.net
Java questions and answers jan bask.netJava questions and answers jan bask.net
Java questions and answers jan bask.net
 
Basic java tutorial
Basic java tutorialBasic java tutorial
Basic java tutorial
 
Introduction to JAVA
Introduction to JAVAIntroduction to JAVA
Introduction to JAVA
 
Bea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guideBea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guide
 
Advanced Java
Advanced JavaAdvanced Java
Advanced Java
 
Core java interview questions
Core java interview questionsCore java interview questions
Core java interview questions
 
Java programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, MysuruJava programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, Mysuru
 
Introduction to Java
Introduction to Java Introduction to Java
Introduction to Java
 
Java basic
Java basicJava basic
Java basic
 
Java notes
Java notesJava notes
Java notes
 
Notes of java first unit
Notes of java first unitNotes of java first unit
Notes of java first unit
 
1 java programming- introduction
1  java programming- introduction1  java programming- introduction
1 java programming- introduction
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
 

En vedette

Using xUnit as a Swiss-Aarmy Testing Toolkit
Using xUnit as a Swiss-Aarmy Testing ToolkitUsing xUnit as a Swiss-Aarmy Testing Toolkit
Using xUnit as a Swiss-Aarmy Testing ToolkitChris Oldwood
 
Introduction to Unit Testing
Introduction to Unit TestingIntroduction to Unit Testing
Introduction to Unit TestingGil Zilberfeld
 
ASP.NET Core 2.0 - .NET São Paulo - Outubro-2017
ASP.NET Core 2.0 - .NET São Paulo - Outubro-2017ASP.NET Core 2.0 - .NET São Paulo - Outubro-2017
ASP.NET Core 2.0 - .NET São Paulo - Outubro-2017Renato Groff
 
xUnit Test Patterns - Chapter19
xUnit Test Patterns - Chapter19xUnit Test Patterns - Chapter19
xUnit Test Patterns - Chapter19Takuto Wada
 
AI and Machine Learning Demystified by Carol Smith at Midwest UX 2017
AI and Machine Learning Demystified by Carol Smith at Midwest UX 2017AI and Machine Learning Demystified by Carol Smith at Midwest UX 2017
AI and Machine Learning Demystified by Carol Smith at Midwest UX 2017Carol Smith
 

En vedette (6)

Using xUnit as a Swiss-Aarmy Testing Toolkit
Using xUnit as a Swiss-Aarmy Testing ToolkitUsing xUnit as a Swiss-Aarmy Testing Toolkit
Using xUnit as a Swiss-Aarmy Testing Toolkit
 
Introduction to Unit Testing
Introduction to Unit TestingIntroduction to Unit Testing
Introduction to Unit Testing
 
Mini training - Moving to xUnit.net
Mini training - Moving to xUnit.netMini training - Moving to xUnit.net
Mini training - Moving to xUnit.net
 
ASP.NET Core 2.0 - .NET São Paulo - Outubro-2017
ASP.NET Core 2.0 - .NET São Paulo - Outubro-2017ASP.NET Core 2.0 - .NET São Paulo - Outubro-2017
ASP.NET Core 2.0 - .NET São Paulo - Outubro-2017
 
xUnit Test Patterns - Chapter19
xUnit Test Patterns - Chapter19xUnit Test Patterns - Chapter19
xUnit Test Patterns - Chapter19
 
AI and Machine Learning Demystified by Carol Smith at Midwest UX 2017
AI and Machine Learning Demystified by Carol Smith at Midwest UX 2017AI and Machine Learning Demystified by Carol Smith at Midwest UX 2017
AI and Machine Learning Demystified by Carol Smith at Midwest UX 2017
 

Similaire à Le Tour de xUnit

Testing in Android: automatici, di integrazione, TDD e scenari avanzati
Testing in Android: automatici, di integrazione, TDD e scenari avanzatiTesting in Android: automatici, di integrazione, TDD e scenari avanzati
Testing in Android: automatici, di integrazione, TDD e scenari avanzatiAlfredo Morresi
 
API Doc Smackdown
API Doc SmackdownAPI Doc Smackdown
API Doc SmackdownTed Husted
 
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)Selenium & PHPUnit made easy with Steward (Berlin, April 2017)
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)Ondřej Machulda
 
JavaScript Miller Columns
JavaScript Miller ColumnsJavaScript Miller Columns
JavaScript Miller ColumnsJonathan Fine
 
Codeception Testing Framework -- English #phpkansai
Codeception Testing Framework -- English #phpkansaiCodeception Testing Framework -- English #phpkansai
Codeception Testing Framework -- English #phpkansaiFlorent Batard
 
Devoxx 2014 [incomplete] summary
Devoxx 2014 [incomplete] summaryDevoxx 2014 [incomplete] summary
Devoxx 2014 [incomplete] summaryArtem Oboturov
 
Lunch and learn as3_frameworks
Lunch and learn as3_frameworksLunch and learn as3_frameworks
Lunch and learn as3_frameworksYuri Visser
 
Java Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug ClassJava Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug ClassCODE WHITE GmbH
 
10 Ways To Improve Your Code( Neal Ford)
10  Ways To  Improve  Your  Code( Neal  Ford)10  Ways To  Improve  Your  Code( Neal  Ford)
10 Ways To Improve Your Code( Neal Ford)guestebde
 
Creating Realistic Unit Tests with Testcontainers
Creating Realistic Unit Tests with TestcontainersCreating Realistic Unit Tests with Testcontainers
Creating Realistic Unit Tests with TestcontainersPaul Balogh
 
Dead-Simple Async Control Flow with Coroutines
Dead-Simple Async Control Flow with CoroutinesDead-Simple Async Control Flow with Coroutines
Dead-Simple Async Control Flow with CoroutinesTravis Kaufman
 
Venice boats classification
Venice boats classificationVenice boats classification
Venice boats classificationRoberto Falconi
 
JSR 168 Portal - Overview
JSR 168 Portal - OverviewJSR 168 Portal - Overview
JSR 168 Portal - OverviewVinay Kumar
 
Passing The Joel Test In The PHP World
Passing The Joel Test In The PHP WorldPassing The Joel Test In The PHP World
Passing The Joel Test In The PHP WorldLorna Mitchell
 
Taming the Testing Beast - AgileDC 2012
Taming the Testing Beast - AgileDC 2012Taming the Testing Beast - AgileDC 2012
Taming the Testing Beast - AgileDC 2012Daniel Doubrovkine
 
Plugin-based software design with Ruby and RubyGems
Plugin-based software design with Ruby and RubyGemsPlugin-based software design with Ruby and RubyGems
Plugin-based software design with Ruby and RubyGemsSadayuki Furuhashi
 
How to test infrastructure code: automated testing for Terraform, Kubernetes,...
How to test infrastructure code: automated testing for Terraform, Kubernetes,...How to test infrastructure code: automated testing for Terraform, Kubernetes,...
How to test infrastructure code: automated testing for Terraform, Kubernetes,...Yevgeniy Brikman
 
Release with confidence
Release with confidenceRelease with confidence
Release with confidenceJohn Congdon
 
MvvmCross Introduction
MvvmCross IntroductionMvvmCross Introduction
MvvmCross IntroductionStuart Lodge
 

Similaire à Le Tour de xUnit (20)

Testing in Android: automatici, di integrazione, TDD e scenari avanzati
Testing in Android: automatici, di integrazione, TDD e scenari avanzatiTesting in Android: automatici, di integrazione, TDD e scenari avanzati
Testing in Android: automatici, di integrazione, TDD e scenari avanzati
 
API Doc Smackdown
API Doc SmackdownAPI Doc Smackdown
API Doc Smackdown
 
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)Selenium & PHPUnit made easy with Steward (Berlin, April 2017)
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)
 
JavaScript Miller Columns
JavaScript Miller ColumnsJavaScript Miller Columns
JavaScript Miller Columns
 
Codeception Testing Framework -- English #phpkansai
Codeception Testing Framework -- English #phpkansaiCodeception Testing Framework -- English #phpkansai
Codeception Testing Framework -- English #phpkansai
 
Devoxx 2014 [incomplete] summary
Devoxx 2014 [incomplete] summaryDevoxx 2014 [incomplete] summary
Devoxx 2014 [incomplete] summary
 
Lunch and learn as3_frameworks
Lunch and learn as3_frameworksLunch and learn as3_frameworks
Lunch and learn as3_frameworks
 
Java Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug ClassJava Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug Class
 
10 Ways To Improve Your Code( Neal Ford)
10  Ways To  Improve  Your  Code( Neal  Ford)10  Ways To  Improve  Your  Code( Neal  Ford)
10 Ways To Improve Your Code( Neal Ford)
 
Creating Realistic Unit Tests with Testcontainers
Creating Realistic Unit Tests with TestcontainersCreating Realistic Unit Tests with Testcontainers
Creating Realistic Unit Tests with Testcontainers
 
Dead-Simple Async Control Flow with Coroutines
Dead-Simple Async Control Flow with CoroutinesDead-Simple Async Control Flow with Coroutines
Dead-Simple Async Control Flow with Coroutines
 
Venice boats classification
Venice boats classificationVenice boats classification
Venice boats classification
 
JSR 168 Portal - Overview
JSR 168 Portal - OverviewJSR 168 Portal - Overview
JSR 168 Portal - Overview
 
Passing The Joel Test In The PHP World
Passing The Joel Test In The PHP WorldPassing The Joel Test In The PHP World
Passing The Joel Test In The PHP World
 
10 Ways To Improve Your Code
10 Ways To Improve Your Code10 Ways To Improve Your Code
10 Ways To Improve Your Code
 
Taming the Testing Beast - AgileDC 2012
Taming the Testing Beast - AgileDC 2012Taming the Testing Beast - AgileDC 2012
Taming the Testing Beast - AgileDC 2012
 
Plugin-based software design with Ruby and RubyGems
Plugin-based software design with Ruby and RubyGemsPlugin-based software design with Ruby and RubyGems
Plugin-based software design with Ruby and RubyGems
 
How to test infrastructure code: automated testing for Terraform, Kubernetes,...
How to test infrastructure code: automated testing for Terraform, Kubernetes,...How to test infrastructure code: automated testing for Terraform, Kubernetes,...
How to test infrastructure code: automated testing for Terraform, Kubernetes,...
 
Release with confidence
Release with confidenceRelease with confidence
Release with confidence
 
MvvmCross Introduction
MvvmCross IntroductionMvvmCross Introduction
MvvmCross Introduction
 

Plus de Abdelmonaim Remani

The Economies of Scaling Software
The Economies of Scaling SoftwareThe Economies of Scaling Software
The Economies of Scaling SoftwareAbdelmonaim Remani
 
The Rise of NoSQL and Polyglot Persistence
The Rise of NoSQL and Polyglot PersistenceThe Rise of NoSQL and Polyglot Persistence
The Rise of NoSQL and Polyglot PersistenceAbdelmonaim Remani
 
Building enterprise web applications with spring 3
Building enterprise web applications with spring 3Building enterprise web applications with spring 3
Building enterprise web applications with spring 3Abdelmonaim Remani
 
Introduction To Building Enterprise Web Application With Spring Mvc
Introduction To Building Enterprise Web Application With Spring MvcIntroduction To Building Enterprise Web Application With Spring Mvc
Introduction To Building Enterprise Web Application With Spring MvcAbdelmonaim Remani
 
Introduction To Rich Internet Applications
Introduction To Rich Internet ApplicationsIntroduction To Rich Internet Applications
Introduction To Rich Internet ApplicationsAbdelmonaim Remani
 

Plus de Abdelmonaim Remani (7)

The Eschatology of Java
The Eschatology of JavaThe Eschatology of Java
The Eschatology of Java
 
The Economies of Scaling Software
The Economies of Scaling SoftwareThe Economies of Scaling Software
The Economies of Scaling Software
 
How RESTful Is Your REST?
How RESTful Is Your REST?How RESTful Is Your REST?
How RESTful Is Your REST?
 
The Rise of NoSQL and Polyglot Persistence
The Rise of NoSQL and Polyglot PersistenceThe Rise of NoSQL and Polyglot Persistence
The Rise of NoSQL and Polyglot Persistence
 
Building enterprise web applications with spring 3
Building enterprise web applications with spring 3Building enterprise web applications with spring 3
Building enterprise web applications with spring 3
 
Introduction To Building Enterprise Web Application With Spring Mvc
Introduction To Building Enterprise Web Application With Spring MvcIntroduction To Building Enterprise Web Application With Spring Mvc
Introduction To Building Enterprise Web Application With Spring Mvc
 
Introduction To Rich Internet Applications
Introduction To Rich Internet ApplicationsIntroduction To Rich Internet Applications
Introduction To Rich Internet Applications
 

Dernier

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
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
 
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
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 

Dernier (20)

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
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
 
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
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 

Le Tour de xUnit

  • 1. Le Tour de xUnit JavaOne 2011 AbdelmonaimRemani abdelmonaim.remani@gmail.com
  • 2. License Creative Commons Attribution-NonCommercial3.0 Unported http://creativecommons.org/licenses/by-nc/3.0/
  • 3. Who Am I? Software Engineer Particularly interested in technology evangelism and enterprise software development and architecture President and Founder of a number of organizations The Chico Java User Group The Silicon Valley Spring User Group LinkedIn http://www.linkedin.com/in/polymathiccoder Twitter http://twitter.com/polymathiccoder
  • 4. Warning This presentation is very long and covers a lot of material
  • 5. Outline Part I: Unit Testing Vanilla Is Boring Stay PUT All Those Theories All that CRUD Fakery Mockery Part II: TDD Part III: BDD Part IV: Tools Cross-cutting Story Time When I tell you a story Libra-palooza When I tell you about the coolness of some libraries
  • 7. Part I - Unit Testing
  • 8. What is Unit Testing? What is a Unit? The smallest piece of code that Can be isolated Is testable Targets specific functionality Hmm… Let’s see… A statement? A branch? A method? A basis path within a method Defined by the flow of execution from the start of a method to its exit How many a method has depends on cyclomatic complexity N decisions = 2^N basis possible paths Infinite paths
  • 9. What is Unit Testing? What kind of Testing? The verification of Intent The answer to the question: Does the code do what the developer intended for it to do? Reliability The answer to the question: Can I depend or build upon it?
  • 10. xUnitand xUnit Concepts xUnit is any Unit Testing framework Based on SUnit, a Smalltalk project, design by Kent Beck Concepts Test fixtures Test case Assertions Test execution Test suites
  • 11. Good Test Data Include Valid data Invalid data / Boundary conditions Different Formats Different Order Wide Range Null data Error Conditions
  • 12. Good Tests Cover all possible basis paths Have Self-Describing Names Are Cohesive Independent of each other Reliable Repeatable Fast
  • 13. The Most Opinionated Slide! Lame Excuses! Waste of time Nuisance Distraction from real work Hard to maintain Blah… Blah… Blah… 3 bullet points Quit being lazy! Do yourself a favor and get with the program! You are attitude is the fastest way to get inducted to the Hall of Lame
  • 14. xUnit Frameworks in Java The most popular frameworks JUnit A port of the original SUnit to Java by Erich Gamma and Kent Beck http://junit.org/ TestNG http://testng.org/ This presentation focuses on JUnit
  • 19. The Code QuadraticEquation.java https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/main/java/com/polymathiccoder/talk/xunit/domain/QuadraticEquation.java
  • 20. Testing the Quadratic Equation Vanilla Unit Tests
  • 21. The Quadratic Equation 3 possible data combinations that must be tested Coefficients yielding a negative discriminant Coefficients yielding a discriminant equals to zero Coefficients yielding a positive discriminant 3 different outcomes The equation has no real solution The equation has one real solution The equation has two real solution 3 different basis paths
  • 22. JUnit Annotations Test suites @RunWith Naming Convention <Class Name>Test Test fixtures Set Up @Before @BeforeClass Tear Down @After @AfterClass
  • 23. JUnit Annotations Tests @Test Naming Convention <Method Name>_<State Under Test>_<Expected Behavior> Assertions assertTrue, assertEquals, assertThat, assertNull, etc…
  • 24. Testing Private Methods Don’t test them Relax the visibility to make the code testable Annotate Google Guava’s @VisibleForTesting Use a nested test class Use reflection
  • 25. The Code QuadraticEquationTest.java https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/test/java/com/polymathiccoder/talk/xunit/domain/QuadraticEquationTest.java
  • 27. Testing the Quadratic Equation Parameterized Unit Tests
  • 28. Stay PUT Parameterized or Data-Driven Unit Tests Annotations @RunWith(Parameterized.class) To provide the parameters to be supplied via constructor injection @Parameters public static Collection<Object[]> parameters() @Parameter Object[] parameters
  • 29. Libra-palooza Featuring the coolest JUnit extensions and libraries
  • 30. Libra-palooza Hamcrest Matchers Library Included in JUnit since 4.4 http://code.google.com/p/hamcrest/ Unitils Reflection-based assertions, etc… http://unitils.org Fest Fluent Assertion, etc… http://code.google.com/p/fest/
  • 31. The Code QuadraticEquationParameterizedTest.java https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/test/java/com/polymathiccoder/talk/xunit/domain/QuadraticEquationParameterizedTest.java
  • 36. The Code RiverCrossing.java https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/main/java/com/polymathiccoder/talk/xunit/domain/RiverCrossing.java
  • 37. Testing the River Crossing Puzzle Theories
  • 38. The River Crossing Puzzle 9 possible combinations that must be tested Wolf and Cabbage left behind Cabbage and Wolf left behind Wolf and Goat left behind Goat and Wolf left behind Goat and Cabbage left behind Cabbage and Goat left behind Wolf and Wolf left behind Goat and Goat left behind Cabbage and Cabbage left behind 3 different outcomes One gets transported to the other side One of two left behind eats the other Error trying to transport more than one 18 basis paths
  • 39. The River Crossing Puzzle 9 possible combinations that must be tested and 3 basis paths yielding 3 different outcomes 9 x 3 = 18 Vanilla Tests 3 x 3 = 9 Parameterized Tests 1 x 3 = 3 Theories
  • 40. Theories Running tests with every possible combination of data points Annotations @RunWith(Theories.class) To provide the parameters to be supplied via constructor injection @DataPoints public static Object[] objects @DataPoint public static object
  • 41. Assumptions and Rules Assumptions assumeThat, assumeTrue, assumeNotNull, etc… Rules Allowing for alterations in how test methods are run and reported @Rule Injects public fields of type MethodRule ErrorCollector ExpectedException ExternalResource TemporaryFolder TestName TestWatchman Timeout Verifier
  • 42. The Code RiverCrossingTheory.java https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/test/java/com/polymathiccoder/talk/xunit/domain/RiverCrossingTheory.java
  • 46. The Employee Database Simple Domain Object Employee Id - Number Name - Text Data-Access Object Interface EmployeeDao – CRUD operations Two implementations EmployeeCollectionImpl – A Java Collection implementation EmployeeDaoDbImpl – A JDBC implementation
  • 47. The Code Employee.java https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/main/java/com/polymathiccoder/talk/xunit/domain/Employee.java EmployeeDao.java https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/main/java/com/polymathiccoder/talk/xunit/repository/EmployeeDao.java
  • 48. The Code EmployeeDaoCollectionImpl.java https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/main/java/com/polymathiccoder/talk/xunit/repository/EmployeeDaoCollectionImpl.java EmployeeDaoDbImpl.java https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/main/java/com/polymathiccoder/talk/xunit/repository/EmployeeDaoDbImpl.java
  • 49. Testing the Employee Database All that CRUD
  • 50. Testing Persistence Code Data Define the initial state of data before each test Define the expected state of data after each test Ensure that the data is in a known state before you run the test Run the test Compare against the expected dataset to determine the success or failure of the test Clean after yourself if necessary
  • 51. Testing Persistence Code Notes of Java Collections An Immutable/un-modifiable collection is NOT necessarily a collection of Immutable/un-modifiable objects Notes on testing database code Use a dedicated database instance for testing per user Use an in-memory database if you can HSQLDB H2 Etc…
  • 52. Custom Hamcrest Matches Hamcrest Matches Write your own custom type-safe matcher One asserting per unit test Generating a readable description to be included in test failure messages https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/test/java/com/polymathiccoder/talk/xunit/domain/matcher/EmployeeIsEqual.java
  • 53. Libra-palooza Featuring the coolest JUnit extensions and libraries
  • 54. Libra-palooza HamSandwich http://code.google.com/p/hamsandwich/ Hamcrest Text Patterns http://code.google.com/p/hamcrest-text-patterns/
  • 55. The Code EmployeeDaoCollectionImplTest.java https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/test/java/com/polymathiccoder/talk/xunit/repository/EmployeeDaoCollectionImplTest.java
  • 56. Libra-palooza Featuring the coolest JUnit extensions and libraries
  • 57. Libra-palooza DBUnit A JUnit extension used to unit test database code Export/Import data to and from XML Initialize database into a known state Verify the state of the database against an expected state http://www.dbunit.org/
  • 58. Libra-palooza Unitils Database testing, etc… Integrates with DBUnit Annotations @RunWith(UnitilsJUnit4TestClassRunner.class) @DataSet @ExpectedDataSet @TestDataSource http://unitils.org
  • 59. The Code EmployeeDaoDbImplTest.java https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/test/java/com/polymathiccoder/talk/xunit/repository/EmployeeDaoDbImplTest.java
  • 62. The Mailer Simple email sender that uses the JavaMailAPI Fakes Dumpster A fake SMTP server to be used in unit tests http://quintanasoft.com/dumbster/ ActiveMQ An embedded broker (Make sure to disabled persistence) http://activemq.apache.org/
  • 63. The Code Mailer.java https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/main/java/com/polymathiccoder/talk/xunit/repository/Mailer.java MailerTest.java https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/test/java/com/polymathiccoder/talk/xunit/repository/MailerTest.java
  • 64. Libra-palooza Featuring the coolest JUnit extensions and libraries
  • 65. Libra-palooza XMLUnit http://xmlunit.sourceforge.net/ HTMLUnit http://htmlunit.sourceforge.net/ HttpUnit http://httpunit.sourceforge.net/ Spring Test http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/testing.html
  • 68. The Egyptian Plover & the Nile Crocodile
  • 69. The Egyptian Plover & the Nile Crocodile Herodotus in “The Histories” claimed that there is a symbiotic relationship between the Egyptian Plover and the Nile Crocodile
  • 70.
  • 71. The Code EgyptianPlover.java https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/main/java/com/polymathiccoder/talk/xunit/domain/EgyptianPlover.java
  • 72. Testing the Egyptian Plover & the Nile Crocodile Mocking
  • 73. The Egyptian Plover & the Nile Crocodile 3 different basis path The plover finds the crocodile’s mouth closed and flies away The plover finds the crocodile’s mouth open, doesn’t find any leeches, then flies away The plover finds the crocodile’s mouth open, picks the leeches, then flies away 3 different outcomes False is returned indicating that the plover didn’t eat An exception is thrown and False is returned indicating that the plover didn’t eat True indicating that the plover ate
  • 74. Mocking Dependencies need to be mock to test in isolation Simulating an object to mimic the behavior of a real object in a controlled manner
  • 75. Mocking Dependencies need to be mock to test in isolation Simulating an object to mimic the behavior of a real object in a controlled manner
  • 76. Libra-palooza Featuring the coolest JUnit extensions and libraries
  • 77. Libra-palooza Mockito The coolest mocking framework there is Annotations @RunWith(MockitoJUnitRunner.class) @Mock @InjectMocks @Spy Stub method calls Verify interactions http://code.google.com/p/mockito/
  • 78. The Code EgyptianPloverTest.java https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/test/java/com/polymathiccoder/talk/xunit/domain/EgyptianPloverTest.java
  • 79. This is a digitally constructed image from the Warren Photographic Image Library of Nature and Pets http://www.warrenphotographic.co.uk/
  • 81. Test Suites and Groups Annotations @Category @RunWith(Categories.class) @IncludeCategory @ExcludeCategory @SuiteClasses
  • 82. The Code FastTest.java SlowTest.java SlowAndFastTest.java SlowTestSuite.java https://github.com/PolymathicCoder/LeTourDeXUnit/tree/master/src/test/java/com/polymathiccoder/talk/xunit/misc
  • 83. Miscellaneous Topics Testing AOP (Aspect-Oriented Programming) Code Unit Testing the Advice Verify the execution of the Advice when Joint Point is reached Testing Concurrency In Junit Concurrent test execution Annotations @Concurrent @RunWith(ConcurrentSuite.class) GroboUtils http://groboutils.sourceforge.net/ ConcJUnit http://www.cs.rice.edu/~mgricken/research/concutest/concjunit/
  • 84. Part II – TDDTest-Driver Development
  • 85. This Is How We Have Been Doing It
  • 86. Why Not Test First Instead? Most of us are just not disciplined to test last In order to determine a sets of verifications in the form tests to fulfill the requirements No room for misunderstanding Testable code is good code When you let testing drive the implementation A test-driven implementation is testable by definition No refactoring will be necessary
  • 87. What if? Design Testing Write failing tests Implementation Get the tests to pass
  • 89. Part III – BDDBehavior-Driver Development
  • 90. TDD Is Great, But… TDD works But Thinking of requirements in terms of tests is NOT easy Syllogism Tests verify requirements Requirements define behavior Tests verify behavior Neuro-Linguistic Programming (NLP) suggests that the words we use influence the way we think What if we start using terminology that focuses on the behavioral aspects of the system rather than testing?
  • 91. The BDD Way BDD is simply a rephrased TDD The focus on behavior Bridges the gap between Business users and Technologists Makes the development goals and priorities more aligned with business requirements TDD vs. BDD Verification State-Based Bottom-Up approach Specification Interaction-Based Outside-In Approach
  • 92. The BDD Way “Behavior-Driven Development (BDD) is about implementing an application by describing it from the point of view of its stakeholders” – Jbehave.org
  • 93. BDD Concepts Story A description of a feature that has business value As a [Role], I want to [Feature] So that I [Value] Sounds familiar? Agile for you!
  • 94. BDD Concepts Scenario A description of how the user expects the system to behave using a sequence of steps Step Can be a context, an event, or an outcome Given [Context] When [Event] Then [Outcome]
  • 95. BDD in Java JBehave Very powerful and flexible Well-documented Separation of story files from code http://jbehave.org EasyB http://www.easyb.org/ Concordion http://www.concordion.org/
  • 96. Testing the Quadratic Equation Stories, Scenarios, and Steps
  • 97. The Quadratic Equation 3 possible data combinations that must be tested Coefficients yielding a negative discriminant Coefficients yielding a discriminant equals to zero Coefficients yielding a positive discriminant 3 different outcomes The equation has no real solution The equation has one real solution The equation has two real solution 3 different basis paths
  • 98. BDD with JBehave Write the story Map the steps to a POJO @Given @When @Then Configure the stories @Configure Run the stories @RunWith(AnnotatedEmbedderRunner.class) @UsingEmbedder @UsingSteps View Reports
  • 99. The Code quadraticEquation.story https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/test/java/com/polymathiccoder/talk/xunit/domain/quadraticEquation.story QuadraticEquationStories.java https://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/test/java/com/polymathiccoder/talk/xunit/domain/QuadraticEquationStories.java
  • 100. Part IV - Tools
  • 101. Tools Code Coverage Cobertura http://cobertura.sourceforge.net/ EMMA http://emma.sourceforge.net/ Continuous Integration On the server: Jenkins/Hudson http://jenkins-ci.org/ On your IDE: Infinitest http://infinitest.github.com/
  • 102. Q & A
  • 103. Material The Slides http://www.slideshare.net/PolymathicCoder The Code https://github.com/PolymathicCoder/LeTourDeXUnit The Speaker Email: abdelmonaim.remani@gmail.com Twitter: @polymathiccoder LinkedIn: http://www.linkedin.com/in/polymathiccoder