104
Le Tour de xUnit JavaOne 2011 Abdelmonaim Remani [email protected]

Le Tour de xUnit

Embed Size (px)

DESCRIPTION

This session showcases several unit testing libraries and frameworks that make it possible to write the most-effective unit and integration tests. It also highlights some of the most underused features of JUnit, including Theories, parameterized tests, and Hamcrest matchers. Among the libraries it covers: Unitils, Spring Test, DbUnit, XMLUnit, Dumpster, Mockito, and JBehave. The presentation supplies code examples and discusses TDD/BDD best practices.

Citation preview

Page 1: Le Tour de xUnit

Le Tour de xUnitJavaOne 2011

Abdelmonaim Remani

[email protected]

Page 2: Le Tour de xUnit

License

● Creative Commons Attribution-NonCommercial 3.0 Unported

● http://creativecommons.org/licenses/by-nc/3.0/

Page 3: Le Tour de xUnit

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

Page 4: Le Tour de xUnit

WarningThis presentation is very long and covers a lot of material

Page 5: Le Tour de xUnit

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

Page 6: Le Tour de xUnit

There Will Be Code!

Page 7: Le Tour de xUnit

Part I - Unit Testing

Page 8: Le Tour de xUnit

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

Page 9: Le Tour de xUnit

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?

Page 10: Le Tour de xUnit

xUnit and 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

Page 11: Le Tour de xUnit

Good Test Data Include

● Valid data

● Invalid data / Boundary conditions● Different Formats● Different Order● Wide Range● Null data● Error Conditions

Page 12: Le Tour de xUnit

Good Tests

● Cover all possible basis paths

● Have Self-Describing Names

● Are Cohesive● Independent of each other● Reliable● Repeatable● Fast

Page 13: Le Tour de xUnit

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

Page 14: Le Tour de xUnit

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

Page 15: Le Tour de xUnit

Vanilla Is Boring

Page 16: Le Tour de xUnit

Story Time

Page 17: Le Tour de xUnit

The Quadratic Equation

Page 18: Le Tour de xUnit

The Quadratic Equation

Page 20: Le Tour de xUnit

Testing the Quadratic EquationVanilla Unit Tests

Page 21: Le Tour de xUnit

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

Page 22: Le Tour de xUnit

JUnit Annotations

● Test suites● @RunWith● Naming Convention

● <Class Name>Test

● Test fixtures● Set Up

● @Before

● @BeforeClass

● Tear Down● @After

● @AfterClass

Page 23: Le Tour de xUnit

JUnit Annotations

● Tests● @Test● Naming Convention

● <Method Name>_<State Under Test>_<Expected Behavior>

● Assertions● assertTrue, assertEquals, assertThat, assertNull,

etc…

Page 24: Le Tour de xUnit

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

Page 26: Le Tour de xUnit

Stay PUT

Page 27: Le Tour de xUnit

Testing the Quadratic EquationParameterized Unit Tests

Page 28: Le Tour de xUnit

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

Page 29: Le Tour de xUnit

Libra-paloozaFeaturing the coolest JUnit extensions and libraries

Page 30: Le Tour de xUnit

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/

Page 32: Le Tour de xUnit

All Those Theories

Page 33: Le Tour de xUnit

Story Time

Page 34: Le Tour de xUnit

The River Crossing Puzzle

Page 35: Le Tour de xUnit

The River Crossing Puzzle

Page 37: Le Tour de xUnit

Testing the River Crossing PuzzleTheories

Page 38: Le Tour de xUnit

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

Page 39: Le Tour de xUnit

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

Page 40: Le Tour de xUnit

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

Page 41: Le Tour de xUnit

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

Page 43: Le Tour de xUnit

All That CRUD

Page 44: Le Tour de xUnit

Story Time

Page 45: Le Tour de xUnit

The Employee Database

Page 46: Le Tour de xUnit

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

Page 48: Le Tour de xUnit

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

Page 49: Le Tour de xUnit

Testing the Employee DatabaseAll that CRUD

Page 50: Le Tour de xUnit

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

Page 51: Le Tour de xUnit

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…

Page 52: Le Tour de xUnit

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

Page 53: Le Tour de xUnit

Libra-paloozaFeaturing the coolest JUnit extensions and libraries

Page 54: Le Tour de xUnit

Libra-palooza

● HamSandwich● http://code.google.com/p/hamsandwich/

● Hamcrest Text Patterns● http://code.google.com/p/hamcrest-text-patterns/

Page 56: Le Tour de xUnit

Libra-paloozaFeaturing the coolest JUnit extensions and libraries

Page 57: Le Tour de xUnit

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/

Page 58: Le Tour de xUnit

Libra-palooza

● Unitils● Database testing, etc…● Integrates with DBUnit

● Annotations

● @RunWith(UnitilsJUnit4TestClassRunner.class)

● @DataSet

● @ExpectedDataSet

● @TestDataSource

● http://unitils.org

Page 60: Le Tour de xUnit

Fakery

Page 61: Le Tour de xUnit

The Mailer

Page 62: Le Tour de xUnit

The Mailer

● Simple email sender that uses the JavaMail API

● 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/

Page 64: Le Tour de xUnit

Libra-paloozaFeaturing the coolest JUnit extensions and libraries

Page 66: Le Tour de xUnit

Mockery

Page 67: Le Tour de xUnit

Story Time

Page 68: Le Tour de xUnit

The Egyptian Plover & the Nile Crocodile

Page 69: Le Tour de xUnit

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

Page 70: Le Tour de xUnit
Page 72: Le Tour de xUnit

Testing the Egyptian Plover & the Nile CrocodileMocking

Page 73: Le Tour de xUnit

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

Page 74: Le Tour de xUnit

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

Egyptian

Plover

Nile Crocodile

Page 75: Le Tour de xUnit

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

Egyptian

Plover

Nile Crocodile

Page 76: Le Tour de xUnit

Libra-paloozaFeaturing the coolest JUnit extensions and libraries

Page 77: Le Tour de xUnit

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/

Page 79: Le Tour de xUnit

This is a digitally constructed image from the Warren Photographic Image Library of Nature and Pets

http://www.warrenphotographic.co.uk/

Page 80: Le Tour de xUnit

Miscellaneous Topics

Page 81: Le Tour de xUnit

Test Suites and Groups

● Annotations● @Category● @RunWith(Categories.class)● @IncludeCategory● @ExcludeCategory● @SuiteClasses

Page 83: Le Tour de xUnit

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/

Page 84: Le Tour de xUnit

Part II – TDDTest-Driver Development

Page 85: Le Tour de xUnit

This Is How We Have Been Doing It

Design Implementation Testing

Page 86: Le Tour de xUnit

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

Page 87: Le Tour de xUnit

What if?

● Design

● Testing● Write failing tests

● Implementation● Get the tests to pass

Design Testing Implementation Testing

Page 88: Le Tour de xUnit

The TDD WayDesign

Testing

ImplementationTesting

Refactor

Page 89: Le Tour de xUnit

Part III – BDDBehavior-Driver

Development

Page 90: Le Tour de xUnit

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?

Page 91: Le Tour de xUnit

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. BDDVerification

State-Based

Bottom-Up approach

Specification

Interaction-Based

Outside-In Approach

Page 92: Le Tour de xUnit

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

Page 93: Le Tour de xUnit

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!

Page 94: Le Tour de xUnit

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]

Page 95: Le Tour de xUnit

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/

Page 96: Le Tour de xUnit

Testing the Quadratic EquationStories, Scenarios, and Steps

Page 97: Le Tour de xUnit

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

Page 98: Le Tour de xUnit

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

Page 100: Le Tour de xUnit

Part IV - Tools

Page 101: Le Tour de xUnit

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/

Page 102: Le Tour de xUnit

Q & A

Page 103: Le Tour de xUnit

Material

● The Slides● http://www.slideshare.net/PolymathicCoder

● The Code● https://github.com/PolymathicCoder/LeTourDeXUnit

● The Speaker● Email: [email protected]● Twitter: @polymathiccoder● LinkedIn: http

://www.linkedin.com/in/polymathiccoder

Page 104: Le Tour de xUnit

Thank You