SlideShare a Scribd company logo
1 of 85
Download to read offline
C l e a n U n i t T e s t P a t t e r n s 
F r a n k A p p e l Blog: www.codeaffine.com 
Email: fappel@codeaffine.com 
Twitter: @frank_appel
C l e a n U n i t T e s t P a t t e r n s 
Why bother? 
Structure 
Isolation 
Runners and Rules 
Assertions 
Q&A
Who I am.. 
Independent Software Developer 
Blogger (http://codeaffine.com/blog) 
Stalwart of agile methods and TDD in particular
C l e a n U n i t T e s t P a t t e r n s 
Why bother? 
Structure 
Isolation 
Runners and Rules 
Assertions 
Q&A
Why bother?
Why bother? 
Test of too many concepts
Why bother?
Why bother? 
Mix of integration and unit test
Why bother?
Why bother? 
Missing of clean and recognizable test structure
Why bother?
Why bother? 
Tight coupling of unit under test and dependencies
Why bother?
Why bother? 
Poor maintainability and progression
Why bother?
Why bother? 
Don't do it!
C l e a n U n i t T e s t P a t t e r n s 
Why bother? 
Structure 
Isolation 
Runners and Rules 
Assertions 
Q&A
Test Structure 
Four Phases Pattern
Test Structure 
Four Phases Pattern 
Setup (Fixture)
Test Structure 
Four Phases Pattern 
Setup (Fixture) 
Exercise
Test Structure 
Four Phases Pattern 
Setup (Fixture) 
Exercise 
Verify
Test Structure 
Four Phases Pattern 
Setup (Fixture) 
Exercise 
Verify 
Teardown: cleaning up the fixture in case it is persistent.
Test Structure 
Four Phases Pattern 
Setup (Fixture) 
Exercise 
Verify 
Teardown: cleaning up the fixture in case it is persistent.
Test Structure 
Setup Patterns
Test Structure 
Setup Patterns 
Inline Setup
Test Structure 
Setup Patterns
Test Structure 
Setup Patterns
Test Structure 
Setup Patterns 
Delegate Setup
Test Structure 
Setup Patterns
Test Structure 
Setup Patterns
Test Structure 
Setup Patterns 
Implicit Setup
Test Structure 
Reusable Setup Helper 
Object Mother 
Test Fixture Registry 
Implementation either as stateless test helper class or, in case the helper 
holds references to fixture or SUT objects, as stateful test helper object.
Test Structure 
Implicit Teardown 
Teardown is all about housekeeping and adds no information at all to a 
particular test
Test Structure 
Corner Case Tests: Expected Exceptions 
Traditional approach: ugly try-catch block, mix of phases
Test Structure 
Corner Case Tests: Expected Exceptions
Test Structure 
Corner Case Tests: Expected Exceptions 
Expected Annotation Method: might swallow setup problems, limited verification 
capabilities
Test Structure 
Corner Case Tests: Expected Exceptions
Test Structure 
Corner Case Tests: Expected Exceptions 
ExpectedException Rule: Verification definition before execution phase
Test Structure 
Corner Case Tests: Expected Exceptions
Test Structure 
Corner Case Tests: Expected Exceptions 
Usage of a little execution utility and Java 8 Lambda expressions
C l e a n U n i t T e s t P a t t e r n s 
Why bother? 
Structure 
Isolation 
Runners and Rules 
Assertions 
Q&A
Isolation 
Dependencies: SUT and DOC 
The tested Unit is usually referred to as system under test (SUT) 
Components the SUT depends on are denoted as depended-on 
component (DOC) 
Test related problems with DOCs 
DOCs we cannot control might impede decent test verification 
DOCs might also slow down test execution 
DOC’s behavior may change unexpectedly e.g. due to the usage of a 
newer version of a third party library
Isolation 
Isolation – A Unit Tester’s SEP Field 
Test concerns seperately and keep tests independent of each other! 
Indirect Inputs and Outputs
Isolation 
Test Double Patterns 
A unit should be designed in a way that each DOC can be replaced by a 
so called Test Double, which is a lightweight stand-in component for the 
DOC. 
A DOC is provided using dependency injection or a service locator. This 
ensures a loosely coupled micro-architecture that allows replacement of 
the DOC with the test double.
Isolation 
Controlling Indirect Inputs with Stubs
Isolation 
Controlling Indirect Inputs with Stubs
Isolation 
Controlling Indirect Inputs with Stubs
Isolation 
Controlling Indirect Inputs with Stubs
Isolation 
Controlling Indirect Inputs with Stubs
Isolation 
Indirect Output Verification with Spies 
The spy records the number value of the invocation in the test double’s number field. 
This allows to verify the indirect output as shown here: 
record 
verify
Isolation 
What About Mocks?
Isolation 
What About Mocks? 
Behavior Verifcation
Isolation 
What About Mocks? 
Behavior Verifcation 
Invocation Verification
Isolation 
What About Mocks?
Isolation 
What About Mocks?
Isolation 
Spy or Mock? 
Mocks break the usual test structure 
Behavior verification is somewhat hidden 
but 
Mocks provide a precise stacktrace to the failure cause
Isolation 
Test Double Frameworks 
JMock, EasyMock mock based 
Mockito spy based
Isolation 
Test Double Frameworks 
Only create test doubles for types you own 
(indication for integration tests and an abstracting adapter layer) 
A test double should not return another test double 
(potential violation of law of demeter)
C l e a n U n i t T e s t P a t t e r n s 
Why bother? 
Structure 
Isolation 
Runners and Rules 
Assertions 
Q&A
Runners 
Suite and Categories 
Use @RunWith to specify a particular test processor
Runners 
Suite and Categories
Runners 
Suite and Categories
Runners 
Parameterized Tests 
Parameterized tests allow to run the same test against multiple data records 
provided as instance field(s) of the test case 
fields
Runners 
Parameterized Tests
Runners 
Parameterized Tests 
Specification of the Parameterized test processor using @RunWith
Runners 
Parameterized Tests
Runners 
Parameterized Tests 
Field initialization takes place by constructor injection. Each data record is 
provided by a particular collector method annotated with @Parameters 
data records 
initializations
Runners 
JUnitParams
Rules 
What are JUnit Rules? 
Rules provide a possibility to intercept test method calls similar as an AOP framework 
would do. 
TemporaryFolder for example removes automatically all created files and directories 
after a test run. 
A list of JUnit built-in Rules can be found at: 
https://github.com/junit-team/junit/wiki/Rules
Rules 
How does it work? 
y
Rules 
How does it work?
Rules 
How does it work? 
Test execution produces: 
before 
during 
after
Rules 
How does it work?
Rules 
How does it work?
C l e a n U n i t T e s t P a t t e r n s 
Why bother? 
Structure 
Isolation 
Runners and Rules 
Assertions 
Q&A
Assertions 
JUnit Assert 
The built-in assertion mechanism of JUnit is provided by the class org.junit.Assert: 
It is quite verbose and somewhat limited with respect to the expressiveness of 
assertions that require more complex predicates
Assertions 
Hamcrest 
A third-party library that claims to provide an API for creating flexible expressions of 
intent is Hamcrest: 
MatcherAssert.assertThat(...) evaluates the execution result (actual) against a 
predicate (matcher-expression) 
MatcherAssert provides an overloaded assertThat method for failure message 
specification
Assertions 
Hamcrest
Assertions 
Hamcrest
Assertions 
AssertJ 
The library AssertJ strives to improves verification by providing fluent assertions API: 
Assertions.assertThat(...) verifies the execution result (actual) against fluently added 
conditions 
The Assert instance provides the method describeAs(String) to specify a particular 
failure message
Assertions 
AssertJ
Assertions 
AssertJ
Assertions 
Which one to use? 
JUnit Assert is surely somewhat dated and less object-oriented 
Hamcrest matchers provide a clean separation of assertion 
and predicate definition 
AssertJ assertions score with a compact and easy to use programming 
style 
Hamcrest and AssertJ support custom matchers/assertions for domain 
specific types 
So now you are spoilt for choice…
C l e a n U n i t T e s t P a t t e r n s 
Why bother? 
Structure 
Isolation 
Runners and Rules 
Assertions 
Q&A
C l e a n U n i t T e s t P a t t e r n s 
References 
xUnit Test Patterns, Gerard Meszaros, 2007 
Clean Code, Chapter 9: Unit Tests, Robert C. Martin, 2009 
Growing Object-Oriented Software, Guided by Tests, Chapter 8, Steve Freeman, Nat Pryce, 2010 
Practical Unit Testing with JUnit and Mockito, Appendix C. Test Spy vs. Mock, Tomek Kaczanowski, 
2013 
JUnit in a Nutshell: Yet Another JUnit Tutorial, 
http://www.codeaffine.com/2014/09/24/junit-nutshell-junit-tutorial, Frank Appel 2014 
Clean JUnit Throwable-Tests with Java 8 Lambdas, 
http://www.codeaffine.com/2014/07/28/clean-junit-throwable-tests-with-java-8-lambdas/, 
Frank Appel 2014 
F r a n k A p p e l Blog: www.codeaffine.com 
Email: fappel@codeaffine.com 
Twitter: @frank_appel

More Related Content

What's hot

Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated TestingLee Englestone
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit TestingMike Lively
 
How and what to unit test
How and what to unit testHow and what to unit test
How and what to unit testEugenio Lentini
 
Benefit From Unit Testing In The Real World
Benefit From Unit Testing In The Real WorldBenefit From Unit Testing In The Real World
Benefit From Unit Testing In The Real WorldDror Helper
 
Embrace Unit Testing
Embrace Unit TestingEmbrace Unit Testing
Embrace Unit Testingalessiopace
 
Test driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseTest driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseUTC Fire & Security
 
Java Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionJava Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionAlex Su
 
Unit Test + Functional Programming = Love
Unit Test + Functional Programming = LoveUnit Test + Functional Programming = Love
Unit Test + Functional Programming = LoveAlvaro Videla
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration TestingDavid Berliner
 
Unit testing - the hard parts
Unit testing - the hard partsUnit testing - the hard parts
Unit testing - the hard partsShaun Abram
 
Unit testing, UI testing and Test Driven Development in Visual Studio 2012
Unit testing, UI testing and Test Driven Development in Visual Studio 2012Unit testing, UI testing and Test Driven Development in Visual Studio 2012
Unit testing, UI testing and Test Driven Development in Visual Studio 2012Jacinto Limjap
 
Unit Testing Guidelines
Unit Testing GuidelinesUnit Testing Guidelines
Unit Testing GuidelinesJoel Hooks
 
Unit Testing Done Right
Unit Testing Done RightUnit Testing Done Right
Unit Testing Done RightBrian Fenton
 

What's hot (20)

Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated Testing
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit Testing
 
How and what to unit test
How and what to unit testHow and what to unit test
How and what to unit test
 
Benefit From Unit Testing In The Real World
Benefit From Unit Testing In The Real WorldBenefit From Unit Testing In The Real World
Benefit From Unit Testing In The Real World
 
Embrace Unit Testing
Embrace Unit TestingEmbrace Unit Testing
Embrace Unit Testing
 
Workshop unit test
Workshop   unit testWorkshop   unit test
Workshop unit test
 
Test driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseTest driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + Eclipse
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Java Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionJava Unit Test and Coverage Introduction
Java Unit Test and Coverage Introduction
 
Unit Test + Functional Programming = Love
Unit Test + Functional Programming = LoveUnit Test + Functional Programming = Love
Unit Test + Functional Programming = Love
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration Testing
 
Testing In Java
Testing In JavaTesting In Java
Testing In Java
 
Unit Testing 101
Unit Testing 101Unit Testing 101
Unit Testing 101
 
Unit testing - the hard parts
Unit testing - the hard partsUnit testing - the hard parts
Unit testing - the hard parts
 
Unit testing
Unit testingUnit testing
Unit testing
 
Unit testing, UI testing and Test Driven Development in Visual Studio 2012
Unit testing, UI testing and Test Driven Development in Visual Studio 2012Unit testing, UI testing and Test Driven Development in Visual Studio 2012
Unit testing, UI testing and Test Driven Development in Visual Studio 2012
 
Unit testing
Unit testingUnit testing
Unit testing
 
Unit Testing Guidelines
Unit Testing GuidelinesUnit Testing Guidelines
Unit Testing Guidelines
 
Best practices unit testing
Best practices unit testing Best practices unit testing
Best practices unit testing
 
Unit Testing Done Right
Unit Testing Done RightUnit Testing Done Right
Unit Testing Done Right
 

Viewers also liked

UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPTsuhasreddy1
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practicesnickokiss
 
Moq Presentation
Moq PresentationMoq Presentation
Moq PresentationLynxStar
 
Mock driven development using .NET
Mock driven development using .NETMock driven development using .NET
Mock driven development using .NETPuneet Ghanshani
 
Principles and patterns for test driven development
Principles and patterns for test driven developmentPrinciples and patterns for test driven development
Principles and patterns for test driven developmentStephen Fuqua
 
Intro to Mocking - DjangoCon 2015
Intro to Mocking - DjangoCon 2015Intro to Mocking - DjangoCon 2015
Intro to Mocking - DjangoCon 2015Excella
 
Unit-Testing Bad-Practices by Example
Unit-Testing Bad-Practices by ExampleUnit-Testing Bad-Practices by Example
Unit-Testing Bad-Practices by ExampleBenjamin Eberlei
 
Практика использования Dependency Injection
Практика использования Dependency InjectionПрактика использования Dependency Injection
Практика использования Dependency InjectionPlatonov Sergey
 
Василий Сорокин, “Google C++ Mocking and Test Frameworks”
Василий Сорокин, “Google C++ Mocking and Test Frameworks”Василий Сорокин, “Google C++ Mocking and Test Frameworks”
Василий Сорокин, “Google C++ Mocking and Test Frameworks”Platonov Sergey
 
DI в C++ тонкости и нюансы
DI в C++ тонкости и нюансыDI в C++ тонкости и нюансы
DI в C++ тонкости и нюансыPlatonov Sergey
 
Юнит-тестирование и Google Mock. Влад Лосев, Google
Юнит-тестирование и Google Mock. Влад Лосев, GoogleЮнит-тестирование и Google Mock. Влад Лосев, Google
Юнит-тестирование и Google Mock. Влад Лосев, Googleyaevents
 
Boundary value analysis
Boundary value analysisBoundary value analysis
Boundary value analysisVadym Muliavka
 
Mockito (JUG Latvia)
Mockito (JUG Latvia)Mockito (JUG Latvia)
Mockito (JUG Latvia)Dmitry Buzdin
 
Programmer testing
Programmer testingProgrammer testing
Programmer testingJoao Pereira
 
Basic Unit Testing with Mockito
Basic Unit Testing with MockitoBasic Unit Testing with Mockito
Basic Unit Testing with MockitoAlexander De Leon
 
Software Engineering - RS3
Software Engineering - RS3Software Engineering - RS3
Software Engineering - RS3AtakanAral
 
All about unit testing using (power) mock
All about unit testing using (power) mockAll about unit testing using (power) mock
All about unit testing using (power) mockPranalee Rokde
 
Павел Филонов, Разделяй и управляй вместе с Conan.io
Павел Филонов, Разделяй и управляй вместе с Conan.ioПавел Филонов, Разделяй и управляй вместе с Conan.io
Павел Филонов, Разделяй и управляй вместе с Conan.ioSergey Platonov
 

Viewers also liked (20)

UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPT
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
 
Unit Testing (C#)
Unit Testing (C#)Unit Testing (C#)
Unit Testing (C#)
 
Moq Presentation
Moq PresentationMoq Presentation
Moq Presentation
 
Mock driven development using .NET
Mock driven development using .NETMock driven development using .NET
Mock driven development using .NET
 
Principles and patterns for test driven development
Principles and patterns for test driven developmentPrinciples and patterns for test driven development
Principles and patterns for test driven development
 
Intro to Mocking - DjangoCon 2015
Intro to Mocking - DjangoCon 2015Intro to Mocking - DjangoCon 2015
Intro to Mocking - DjangoCon 2015
 
Unit-Testing Bad-Practices by Example
Unit-Testing Bad-Practices by ExampleUnit-Testing Bad-Practices by Example
Unit-Testing Bad-Practices by Example
 
Практика использования Dependency Injection
Практика использования Dependency InjectionПрактика использования Dependency Injection
Практика использования Dependency Injection
 
Василий Сорокин, “Google C++ Mocking and Test Frameworks”
Василий Сорокин, “Google C++ Mocking and Test Frameworks”Василий Сорокин, “Google C++ Mocking and Test Frameworks”
Василий Сорокин, “Google C++ Mocking and Test Frameworks”
 
DI в C++ тонкости и нюансы
DI в C++ тонкости и нюансыDI в C++ тонкости и нюансы
DI в C++ тонкости и нюансы
 
Юнит-тестирование и Google Mock. Влад Лосев, Google
Юнит-тестирование и Google Mock. Влад Лосев, GoogleЮнит-тестирование и Google Mock. Влад Лосев, Google
Юнит-тестирование и Google Mock. Влад Лосев, Google
 
Boundary value analysis
Boundary value analysisBoundary value analysis
Boundary value analysis
 
Mockito (JUG Latvia)
Mockito (JUG Latvia)Mockito (JUG Latvia)
Mockito (JUG Latvia)
 
Programmer testing
Programmer testingProgrammer testing
Programmer testing
 
Basic Unit Testing with Mockito
Basic Unit Testing with MockitoBasic Unit Testing with Mockito
Basic Unit Testing with Mockito
 
Software Engineering - RS3
Software Engineering - RS3Software Engineering - RS3
Software Engineering - RS3
 
Demystifying git
Demystifying git Demystifying git
Demystifying git
 
All about unit testing using (power) mock
All about unit testing using (power) mockAll about unit testing using (power) mock
All about unit testing using (power) mock
 
Павел Филонов, Разделяй и управляй вместе с Conan.io
Павел Филонов, Разделяй и управляй вместе с Conan.ioПавел Филонов, Разделяй и управляй вместе с Conan.io
Павел Филонов, Разделяй и управляй вместе с Conan.io
 

Similar to Clean Unit Test Patterns

Implementing TDD in for .net Core applications
Implementing TDD in for .net Core applicationsImplementing TDD in for .net Core applications
Implementing TDD in for .net Core applicationsAhmad Kazemi
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2Tricode (part of Dept)
 
12 Rational Solo Pruebas 2009
12 Rational Solo Pruebas 200912 Rational Solo Pruebas 2009
12 Rational Solo Pruebas 2009Pepe
 
Unit Testing in .NET Core 7.0 with XUnit.pptx
Unit Testing in .NET Core 7.0 with XUnit.pptxUnit Testing in .NET Core 7.0 with XUnit.pptx
Unit Testing in .NET Core 7.0 with XUnit.pptxKnoldus Inc.
 
An Introduction to unit testing
An Introduction to unit testingAn Introduction to unit testing
An Introduction to unit testingSteven Casey
 
Testing and Mocking Object - The Art of Mocking.
Testing and Mocking Object - The Art of Mocking.Testing and Mocking Object - The Art of Mocking.
Testing and Mocking Object - The Art of Mocking.Deepak Singhvi
 
Testing And Drupal
Testing And DrupalTesting And Drupal
Testing And DrupalPeter Arato
 
Test Driven Development with Sql Server
Test Driven Development with Sql ServerTest Driven Development with Sql Server
Test Driven Development with Sql ServerDavid P. Moore
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And RefactoringNaresh Jain
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Qualityguest268ee8
 
selenium automation software testing course syllabus TheKiranAcademy_compress...
selenium automation software testing course syllabus TheKiranAcademy_compress...selenium automation software testing course syllabus TheKiranAcademy_compress...
selenium automation software testing course syllabus TheKiranAcademy_compress...akashjbk7
 

Similar to Clean Unit Test Patterns (20)

Implementing TDD in for .net Core applications
Implementing TDD in for .net Core applicationsImplementing TDD in for .net Core applications
Implementing TDD in for .net Core applications
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2
 
Unit testing
Unit testingUnit testing
Unit testing
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
12 Rational Solo Pruebas 2009
12 Rational Solo Pruebas 200912 Rational Solo Pruebas 2009
12 Rational Solo Pruebas 2009
 
Unit Testing in .NET Core 7.0 with XUnit.pptx
Unit Testing in .NET Core 7.0 with XUnit.pptxUnit Testing in .NET Core 7.0 with XUnit.pptx
Unit Testing in .NET Core 7.0 with XUnit.pptx
 
Testing w-mocks
Testing w-mocksTesting w-mocks
Testing w-mocks
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
 
TDD Best Practices
TDD Best PracticesTDD Best Practices
TDD Best Practices
 
An Introduction to unit testing
An Introduction to unit testingAn Introduction to unit testing
An Introduction to unit testing
 
Introduction to JUnit
Introduction to JUnitIntroduction to JUnit
Introduction to JUnit
 
Testing and Mocking Object - The Art of Mocking.
Testing and Mocking Object - The Art of Mocking.Testing and Mocking Object - The Art of Mocking.
Testing and Mocking Object - The Art of Mocking.
 
Unit testing - An introduction
Unit testing - An introductionUnit testing - An introduction
Unit testing - An introduction
 
Testing And Drupal
Testing And DrupalTesting And Drupal
Testing And Drupal
 
Simple testable code
Simple testable codeSimple testable code
Simple testable code
 
Test Driven Development with Sql Server
Test Driven Development with Sql ServerTest Driven Development with Sql Server
Test Driven Development with Sql Server
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And Refactoring
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Quality
 
Unit testing, principles
Unit testing, principlesUnit testing, principles
Unit testing, principles
 
selenium automation software testing course syllabus TheKiranAcademy_compress...
selenium automation software testing course syllabus TheKiranAcademy_compress...selenium automation software testing course syllabus TheKiranAcademy_compress...
selenium automation software testing course syllabus TheKiranAcademy_compress...
 

Recently uploaded

Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
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
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
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
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
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
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 

Recently uploaded (20)

Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
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
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
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
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
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
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 

Clean Unit Test Patterns

  • 1. C l e a n U n i t T e s t P a t t e r n s F r a n k A p p e l Blog: www.codeaffine.com Email: fappel@codeaffine.com Twitter: @frank_appel
  • 2. C l e a n U n i t T e s t P a t t e r n s Why bother? Structure Isolation Runners and Rules Assertions Q&A
  • 3. Who I am.. Independent Software Developer Blogger (http://codeaffine.com/blog) Stalwart of agile methods and TDD in particular
  • 4. C l e a n U n i t T e s t P a t t e r n s Why bother? Structure Isolation Runners and Rules Assertions Q&A
  • 6. Why bother? Test of too many concepts
  • 8. Why bother? Mix of integration and unit test
  • 10. Why bother? Missing of clean and recognizable test structure
  • 12. Why bother? Tight coupling of unit under test and dependencies
  • 14. Why bother? Poor maintainability and progression
  • 17. C l e a n U n i t T e s t P a t t e r n s Why bother? Structure Isolation Runners and Rules Assertions Q&A
  • 18. Test Structure Four Phases Pattern
  • 19. Test Structure Four Phases Pattern Setup (Fixture)
  • 20. Test Structure Four Phases Pattern Setup (Fixture) Exercise
  • 21. Test Structure Four Phases Pattern Setup (Fixture) Exercise Verify
  • 22. Test Structure Four Phases Pattern Setup (Fixture) Exercise Verify Teardown: cleaning up the fixture in case it is persistent.
  • 23. Test Structure Four Phases Pattern Setup (Fixture) Exercise Verify Teardown: cleaning up the fixture in case it is persistent.
  • 25. Test Structure Setup Patterns Inline Setup
  • 28. Test Structure Setup Patterns Delegate Setup
  • 31. Test Structure Setup Patterns Implicit Setup
  • 32. Test Structure Reusable Setup Helper Object Mother Test Fixture Registry Implementation either as stateless test helper class or, in case the helper holds references to fixture or SUT objects, as stateful test helper object.
  • 33. Test Structure Implicit Teardown Teardown is all about housekeeping and adds no information at all to a particular test
  • 34. Test Structure Corner Case Tests: Expected Exceptions Traditional approach: ugly try-catch block, mix of phases
  • 35. Test Structure Corner Case Tests: Expected Exceptions
  • 36. Test Structure Corner Case Tests: Expected Exceptions Expected Annotation Method: might swallow setup problems, limited verification capabilities
  • 37. Test Structure Corner Case Tests: Expected Exceptions
  • 38. Test Structure Corner Case Tests: Expected Exceptions ExpectedException Rule: Verification definition before execution phase
  • 39. Test Structure Corner Case Tests: Expected Exceptions
  • 40. Test Structure Corner Case Tests: Expected Exceptions Usage of a little execution utility and Java 8 Lambda expressions
  • 41. C l e a n U n i t T e s t P a t t e r n s Why bother? Structure Isolation Runners and Rules Assertions Q&A
  • 42. Isolation Dependencies: SUT and DOC The tested Unit is usually referred to as system under test (SUT) Components the SUT depends on are denoted as depended-on component (DOC) Test related problems with DOCs DOCs we cannot control might impede decent test verification DOCs might also slow down test execution DOC’s behavior may change unexpectedly e.g. due to the usage of a newer version of a third party library
  • 43. Isolation Isolation – A Unit Tester’s SEP Field Test concerns seperately and keep tests independent of each other! Indirect Inputs and Outputs
  • 44. Isolation Test Double Patterns A unit should be designed in a way that each DOC can be replaced by a so called Test Double, which is a lightweight stand-in component for the DOC. A DOC is provided using dependency injection or a service locator. This ensures a loosely coupled micro-architecture that allows replacement of the DOC with the test double.
  • 45. Isolation Controlling Indirect Inputs with Stubs
  • 46. Isolation Controlling Indirect Inputs with Stubs
  • 47. Isolation Controlling Indirect Inputs with Stubs
  • 48. Isolation Controlling Indirect Inputs with Stubs
  • 49. Isolation Controlling Indirect Inputs with Stubs
  • 50. Isolation Indirect Output Verification with Spies The spy records the number value of the invocation in the test double’s number field. This allows to verify the indirect output as shown here: record verify
  • 52. Isolation What About Mocks? Behavior Verifcation
  • 53. Isolation What About Mocks? Behavior Verifcation Invocation Verification
  • 56. Isolation Spy or Mock? Mocks break the usual test structure Behavior verification is somewhat hidden but Mocks provide a precise stacktrace to the failure cause
  • 57. Isolation Test Double Frameworks JMock, EasyMock mock based Mockito spy based
  • 58. Isolation Test Double Frameworks Only create test doubles for types you own (indication for integration tests and an abstracting adapter layer) A test double should not return another test double (potential violation of law of demeter)
  • 59. C l e a n U n i t T e s t P a t t e r n s Why bother? Structure Isolation Runners and Rules Assertions Q&A
  • 60. Runners Suite and Categories Use @RunWith to specify a particular test processor
  • 61. Runners Suite and Categories
  • 62. Runners Suite and Categories
  • 63. Runners Parameterized Tests Parameterized tests allow to run the same test against multiple data records provided as instance field(s) of the test case fields
  • 65. Runners Parameterized Tests Specification of the Parameterized test processor using @RunWith
  • 67. Runners Parameterized Tests Field initialization takes place by constructor injection. Each data record is provided by a particular collector method annotated with @Parameters data records initializations
  • 69. Rules What are JUnit Rules? Rules provide a possibility to intercept test method calls similar as an AOP framework would do. TemporaryFolder for example removes automatically all created files and directories after a test run. A list of JUnit built-in Rules can be found at: https://github.com/junit-team/junit/wiki/Rules
  • 70. Rules How does it work? y
  • 71. Rules How does it work?
  • 72. Rules How does it work? Test execution produces: before during after
  • 73. Rules How does it work?
  • 74. Rules How does it work?
  • 75. C l e a n U n i t T e s t P a t t e r n s Why bother? Structure Isolation Runners and Rules Assertions Q&A
  • 76. Assertions JUnit Assert The built-in assertion mechanism of JUnit is provided by the class org.junit.Assert: It is quite verbose and somewhat limited with respect to the expressiveness of assertions that require more complex predicates
  • 77. Assertions Hamcrest A third-party library that claims to provide an API for creating flexible expressions of intent is Hamcrest: MatcherAssert.assertThat(...) evaluates the execution result (actual) against a predicate (matcher-expression) MatcherAssert provides an overloaded assertThat method for failure message specification
  • 80. Assertions AssertJ The library AssertJ strives to improves verification by providing fluent assertions API: Assertions.assertThat(...) verifies the execution result (actual) against fluently added conditions The Assert instance provides the method describeAs(String) to specify a particular failure message
  • 83. Assertions Which one to use? JUnit Assert is surely somewhat dated and less object-oriented Hamcrest matchers provide a clean separation of assertion and predicate definition AssertJ assertions score with a compact and easy to use programming style Hamcrest and AssertJ support custom matchers/assertions for domain specific types So now you are spoilt for choice…
  • 84. C l e a n U n i t T e s t P a t t e r n s Why bother? Structure Isolation Runners and Rules Assertions Q&A
  • 85. C l e a n U n i t T e s t P a t t e r n s References xUnit Test Patterns, Gerard Meszaros, 2007 Clean Code, Chapter 9: Unit Tests, Robert C. Martin, 2009 Growing Object-Oriented Software, Guided by Tests, Chapter 8, Steve Freeman, Nat Pryce, 2010 Practical Unit Testing with JUnit and Mockito, Appendix C. Test Spy vs. Mock, Tomek Kaczanowski, 2013 JUnit in a Nutshell: Yet Another JUnit Tutorial, http://www.codeaffine.com/2014/09/24/junit-nutshell-junit-tutorial, Frank Appel 2014 Clean JUnit Throwable-Tests with Java 8 Lambdas, http://www.codeaffine.com/2014/07/28/clean-junit-throwable-tests-with-java-8-lambdas/, Frank Appel 2014 F r a n k A p p e l Blog: www.codeaffine.com Email: fappel@codeaffine.com Twitter: @frank_appel