Le Tour de xUnitJavaOne 2011AbdelmonaimRemaniabdelmonaim.remani@gmail.com
LicenseCreative Commons Attribution-NonCommercial3.0 Unportedhttp://creativecommons.org/licenses/by-nc/3.0/
Who Am I?Software EngineerParticularly interested in technology evangelism and enterprise software development and architecturePresident and Founder of a number of organizationsThe Chico Java User GroupThe Silicon Valley Spring User GroupLinkedInhttp://www.linkedin.com/in/polymathiccoderTwitterhttp://twitter.com/polymathiccoder
                 WarningThis presentation is very long and covers a lot of material
OutlinePart I: Unit TestingVanilla Is BoringStay PUTAll Those TheoriesAll that CRUDFakeryMockeryPart II: TDDPart III: BDDPart IV: ToolsCross-cuttingStory TimeWhen I tell you a storyLibra-paloozaWhen 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 thatCan be isolatedIs testableTargets specific functionalityHmm… Let’s see…A statement?A branch?A method?A basis path within a methodDefined by the flow of execution from the start of a method to its exitHow many a method has depends on cyclomatic complexityN decisions = 2^N basis possible pathsInfinite paths
What is Unit Testing?What kind of Testing?The verification ofIntentThe answer to the question:Does the code do what the developer intended for it to do?ReliabilityThe answer to the question:Can I depend or build upon it?
xUnitand xUnit ConceptsxUnit is any Unit Testing frameworkBased on SUnit, a Smalltalk project, design by Kent BeckConceptsTest fixturesTest caseAssertionsTest executionTest suites
Good Test Data IncludeValid dataInvalid data / Boundary conditionsDifferent FormatsDifferent OrderWide RangeNull dataError Conditions
Good TestsCover all possible basis pathsHave Self-Describing NamesAre CohesiveIndependent of each otherReliableRepeatableFast
The Most Opinionated Slide!Lame Excuses!Waste of timeNuisanceDistraction from real workHard to maintainBlah… Blah… Blah…3 bullet pointsQuit 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 JavaThe most popular frameworksJUnitA port of the original SUnit to Java by Erich Gamma and Kent Beckhttp://junit.org/TestNGhttp://testng.org/This presentation focuses on JUnit
Vanilla Is Boring
Story Time
The Quadratic Equation
The Quadratic Equation
The CodeQuadraticEquation.javahttps://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/main/java/com/polymathiccoder/talk/xunit/domain/QuadraticEquation.java
Testing the Quadratic EquationVanilla Unit Tests
The Quadratic Equation3 possible data combinations that must be testedCoefficients yielding a negative discriminantCoefficients yielding a discriminant equals to zeroCoefficients yielding a positive discriminant3 different outcomesThe equation has no real solutionThe equation has one real solutionThe equation has two real solution3 different basis paths
JUnit AnnotationsTest suites@RunWithNaming Convention<Class Name>TestTest fixturesSet Up@Before@BeforeClassTear Down@After@AfterClass
JUnit AnnotationsTests@TestNaming Convention<Method Name>_<State Under Test>_<Expected Behavior>AssertionsassertTrue, assertEquals, assertThat, assertNull, etc…
Testing Private MethodsDon’t test themRelax the visibility to make the code testableAnnotate Google Guava’s @VisibleForTestingUse a nested test classUse reflection
The CodeQuadraticEquationTest.javahttps://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/test/java/com/polymathiccoder/talk/xunit/domain/QuadraticEquationTest.java
Stay PUT
Testing the Quadratic EquationParameterized Unit Tests
Stay PUTParameterized or Data-Driven Unit TestsAnnotations@RunWith(Parameterized.class)To provide the parameters to be supplied via constructor injection@Parameters public static Collection<Object[]> parameters()@Parameter Object[] parameters
Libra-paloozaFeaturing the coolest JUnit extensions and libraries
Libra-paloozaHamcrestMatchers LibraryIncluded in JUnit since 4.4http://code.google.com/p/hamcrest/UnitilsReflection-based assertions, etc…http://unitils.orgFestFluent Assertion, etc…http://code.google.com/p/fest/
The CodeQuadraticEquationParameterizedTest.javahttps://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 CodeRiverCrossing.javahttps://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/main/java/com/polymathiccoder/talk/xunit/domain/RiverCrossing.java
Testing the River Crossing PuzzleTheories
The River Crossing Puzzle9 possible combinations that must be testedWolf  and Cabbage left behindCabbage and Wolf left behindWolf and Goat left behindGoat and Wolf left behindGoat and Cabbage left behindCabbage and Goat left behindWolf and Wolf left behindGoat and Goat left behindCabbage and Cabbage left behind3 different outcomesOne gets transported to the other sideOne of two left behind eats the otherError trying to transport more than one18 basis paths
The River Crossing Puzzle9 possible combinations that must be tested and 3 basis paths yielding 3 different outcomes9 x 3 = 18    Vanilla Tests3 x 3 = 9      Parameterized Tests1 x 3 = 3      Theories
TheoriesRunning tests with every possible combination of data pointsAnnotations@RunWith(Theories.class)To provide the parameters to be supplied via constructor injection@DataPoints public static Object[] objects@DataPoint public static object
Assumptions and RulesAssumptionsassumeThat, assumeTrue, assumeNotNull, etc…RulesAllowing for alterations in how test methods are run and reported@RuleInjects public fields of type MethodRuleErrorCollectorExpectedExceptionExternalResourceTemporaryFolderTestNameTestWatchmanTimeoutVerifier
The CodeRiverCrossingTheory.javahttps://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 DatabaseSimple Domain ObjectEmployeeId - NumberName - TextData-Access Object InterfaceEmployeeDao – CRUD operationsTwo implementationsEmployeeCollectionImpl – A Java Collection implementationEmployeeDaoDbImpl – A JDBC implementation
The CodeEmployee.javahttps://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/main/java/com/polymathiccoder/talk/xunit/domain/Employee.javaEmployeeDao.javahttps://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/main/java/com/polymathiccoder/talk/xunit/repository/EmployeeDao.java
The CodeEmployeeDaoCollectionImpl.javahttps://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/main/java/com/polymathiccoder/talk/xunit/repository/EmployeeDaoCollectionImpl.javaEmployeeDaoDbImpl.javahttps://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/main/java/com/polymathiccoder/talk/xunit/repository/EmployeeDaoDbImpl.java
Testing the Employee DatabaseAll that CRUD
Testing Persistence Code DataDefine the initial state of data before each testDefine the expected state of data after each testEnsure that the data is in a known state before you run the testRun the testCompare against the expected dataset to determine the success or failure of the testClean after yourself if necessary
Testing Persistence Code Notes of Java CollectionsAn Immutable/un-modifiable collection is NOT necessarily a collection of Immutable/un-modifiable objectsNotes on testing database codeUse a dedicated database instance for testing per userUse an in-memory database if you canHSQLDBH2Etc…
Custom Hamcrest MatchesHamcrest MatchesWrite your own custom type-safe matcherOne asserting per unit testGenerating a readable description to be included in test failure messageshttps://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/test/java/com/polymathiccoder/talk/xunit/domain/matcher/EmployeeIsEqual.java
Libra-paloozaFeaturing the coolest JUnit extensions and libraries
Libra-paloozaHamSandwichhttp://code.google.com/p/hamsandwich/Hamcrest Text Patternshttp://code.google.com/p/hamcrest-text-patterns/
The CodeEmployeeDaoCollectionImplTest.javahttps://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/test/java/com/polymathiccoder/talk/xunit/repository/EmployeeDaoCollectionImplTest.java
Libra-paloozaFeaturing the coolest JUnit extensions and libraries
Libra-paloozaDBUnitA JUnit extension used to unit test database codeExport/Import data to and from XMLInitialize database into a known stateVerify the state of the database against an expected statehttp://www.dbunit.org/
Libra-paloozaUnitilsDatabase testing, etc…Integrates with DBUnitAnnotations@RunWith(UnitilsJUnit4TestClassRunner.class)@DataSet@ExpectedDataSet@TestDataSourcehttp://unitils.org
The CodeEmployeeDaoDbImplTest.javahttps://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/test/java/com/polymathiccoder/talk/xunit/repository/EmployeeDaoDbImplTest.java
Fakery
The Mailer
The MailerSimple email sender that uses the JavaMailAPIFakesDumpsterA fake SMTP server to be used in unit testshttp://quintanasoft.com/dumbster/ActiveMQAn embedded broker (Make sure to disabled persistence)http://activemq.apache.org/
The CodeMailer.javahttps://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/main/java/com/polymathiccoder/talk/xunit/repository/Mailer.javaMailerTest.javahttps://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/test/java/com/polymathiccoder/talk/xunit/repository/MailerTest.java
Libra-paloozaFeaturing the coolest JUnit extensions and libraries
Libra-paloozaXMLUnithttp://xmlunit.sourceforge.net/HTMLUnithttp://htmlunit.sourceforge.net/HttpUnithttp://httpunit.sourceforge.net/Spring Testhttp://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 CrocodileHerodotus in “The Histories” claimed that there is a symbiotic relationship between the Egyptian Plover and the Nile Crocodile
The CodeEgyptianPlover.javahttps://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/main/java/com/polymathiccoder/talk/xunit/domain/EgyptianPlover.java
Testing the Egyptian Plover & the Nile CrocodileMocking
The Egyptian Plover & the Nile Crocodile3 different basis pathThe plover finds the crocodile’s mouth closed and flies awayThe plover finds the crocodile’s mouth open, doesn’t find any leeches, then flies awayThe plover finds the crocodile’s mouth open, picks the leeches, then flies away3 different outcomesFalse is returned indicating that the plover didn’t eatAn exception is thrown and False is returned indicating that the plover didn’t eatTrue indicating that the plover ate
MockingDependencies need to be mock to test in isolationSimulating an object to mimic the behavior of a real object in a controlled manner
MockingDependencies need to be mock to test in isolationSimulating an object to mimic the behavior of a real object in a controlled manner
Libra-paloozaFeaturing the coolest JUnit extensions and libraries
Libra-paloozaMockitoThe coolest mocking framework there isAnnotations@RunWith(MockitoJUnitRunner.class)@Mock@InjectMocks@SpyStub method callsVerify interactionshttp://code.google.com/p/mockito/
The CodeEgyptianPloverTest.javahttps://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 Petshttp://www.warrenphotographic.co.uk/
Miscellaneous Topics
Test Suites and GroupsAnnotations@Category@RunWith(Categories.class)@IncludeCategory@ExcludeCategory@SuiteClasses
The CodeFastTest.javaSlowTest.javaSlowAndFastTest.javaSlowTestSuite.javahttps://github.com/PolymathicCoder/LeTourDeXUnit/tree/master/src/test/java/com/polymathiccoder/talk/xunit/misc
Miscellaneous TopicsTesting AOP (Aspect-Oriented Programming) CodeUnit Testing the AdviceVerify the execution of the Advice when Joint Point is reachedTesting ConcurrencyIn JunitConcurrent test executionAnnotations@Concurrent@RunWith(ConcurrentSuite.class)GroboUtilshttp://groboutils.sourceforge.net/ConcJUnithttp://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 lastIn order to determine a sets of verifications in the form tests to fulfill the requirementsNo room for misunderstandingTestable code is good codeWhen you let testing drive the implementationA test-driven implementation is testable by definitionNo refactoring will be necessary
What if?DesignTestingWrite failing testsImplementationGet the tests to pass
The TDD Way
Part III – BDDBehavior-Driver Development
TDD Is Great, But…TDD worksBut Thinking of requirements in terms of tests is NOT easySyllogismTests verify requirementsRequirements define behaviorTests verify behaviorNeuro-Linguistic Programming (NLP) suggests that the words we use influence the way we thinkWhat if we start using terminology that focuses on the behavioral aspects of the system rather than testing?
The BDD WayBDD is simply a rephrased TDDThe focus on behaviorBridges the gap between Business users and TechnologistsMakes the development goals and priorities more aligned with business requirementsTDD vs. BDDVerificationState-BasedBottom-Up approachSpecificationInteraction-BasedOutside-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 ConceptsStoryA description of a feature that has business valueAs a [Role],I want to [Feature]So that I [Value]Sounds familiar?Agile for you!
BDD ConceptsScenarioA description of how the user expects the system to behave using a sequence of stepsStepCan be a context, an event, or an outcomeGiven [Context]When [Event]Then [Outcome]
BDD in JavaJBehaveVery powerful and flexibleWell-documentedSeparation of story files from codehttp://jbehave.orgEasyBhttp://www.easyb.org/Concordionhttp://www.concordion.org/
Testing the Quadratic EquationStories, Scenarios, and Steps
The Quadratic Equation3 possible data combinations that must be testedCoefficients yielding a negative discriminantCoefficients yielding a discriminant equals to zeroCoefficients yielding a positive discriminant3 different outcomesThe equation has no real solutionThe equation has one real solutionThe equation has two real solution3 different basis paths
BDD with JBehaveWrite the storyMap the steps to a POJO@Given@When@ThenConfigure the stories@ConfigureRun the stories@RunWith(AnnotatedEmbedderRunner.class)@UsingEmbedder@UsingStepsView Reports
The CodequadraticEquation.storyhttps://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/test/java/com/polymathiccoder/talk/xunit/domain/quadraticEquation.storyQuadraticEquationStories.javahttps://github.com/PolymathicCoder/LeTourDeXUnit/blob/master/src/test/java/com/polymathiccoder/talk/xunit/domain/QuadraticEquationStories.java
Part IV - Tools
ToolsCode CoverageCoberturahttp://cobertura.sourceforge.net/EMMAhttp://emma.sourceforge.net/Continuous IntegrationOn the server: Jenkins/Hudsonhttp://jenkins-ci.org/On your IDE: Infinitesthttp://infinitest.github.com/
Q & A
MaterialThe Slideshttp://www.slideshare.net/PolymathicCoderThe Codehttps://github.com/PolymathicCoder/LeTourDeXUnitThe SpeakerEmail: abdelmonaim.remani@gmail.comTwitter: @polymathiccoderLinkedIn: http://www.linkedin.com/in/polymathiccoder
Thank You

Le Tour de xUnit