SlideShare una empresa de Scribd logo
1 de 21
Descargar para leer sin conexión
Unit Testing Fundamentals

        Richard Paul
       Kiwiplan NZ Ltd
        27 Feb 2009
What is Unit Testing?

You all know what unit testing is, but here is a definition:

In computer programming, unit testing is a method of testing
that verifies the individual units of source code are working
properly...
 -- http://en.wikipedia.org/wiki/Unit_testing
Benefits of Unit Testing

Automated regression tests, ensure code continues to work

Executable, evolving documentation of how the code works.

Allows code to be less brittle allowing for refactoring without
fear.

Test code in isolation of the rest of the system (which may not
be written yet).

Fewer bugs!
Unit Testing vs Functional Testing

Unit tests are written from a programmer's perspective. They
ensure that a particular method of a class successfully
performs a set of specific tasks.

Functional tests are written from a user's perspective. These
tests confirm that the system does what users are expecting it
to.

-- http://www.ibm.com/developerworks/library/j-test.html
Structure of a Unit Test
  Test method per test case.
  Each test should run in isolation.
Unit Testing Best Practices

Unit tests should run fast.
   Allows developers to code fast.
   Don't hit the database unless you really need to.

Tests should assert only what is required to exercise the code.
   Over-specification leads to excessive test maintenance.

Unit tests should be developed in parallel to the code.

Unit tests should be run automatically every time code is
checked in.
       Using a continuous integration machine e.g.Hudson.
       Provides quick feedback for any integration problems.
Test Driven Development (TDD)
TDD Advantages

You are encouraged to think about how your object is to be
used.

Develop faster, no compile/deploy cycle to check code works.

Debugging a unit test is much simpler than a deployed
application.

Set of regression tests allowing you to refactor as you develop
without fear of breaking previous functionality.

Unit tests are likely to cover more edge cases as the object
model is fresh in your mind.
Expose a Seam

A seam is a line at which the code being tested can be
isolated.

Collaborators on the other side of the seam should be
replaceable to ensure we can isolate the code we wish to test.

Code that exposes a seam is generally loosely coupled.
Exposing a Seam




At runtime, production classes are used.
Mocking out collaborators




Replaced production classes with mocks for testing.
Anti-patterns - Static Methods




Use of static methods means there is no way to replace the
collaborators in the test, resulting in overly complex tests.
Locally instantiated collaborators




The class under test instantiates Class 1 and Class 2. We
can't replace these classes in the test so we have no seam.
Anti-pattern Further Reading

Static Methods are Death to Testability
http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/

To quot;newquot; or not to quot;newquot;…
http://misko.hevery.com/2008/09/30/to-new-or-not-to-new/




You may have noticed, Miško Hevery is my hero.
Mocking Frameworks

Mocking frameworks provide a convenient means for ensuring
unit tests remained focused by providing the ability to 'mock
out' other objects.

Frameworks include:
Java
   Mockito
   EasyMock
   JMock
.Net
   Moq (requires .Net 3.5)
   Rhino
   TypeMock
Example - Accessing a Collaborator

In order to provide a seam for code that uses services there
needs to exist a way to swap out the service used.

Dependency Injection
  Java
     Spring Framework
     Guice
  .Net
     Springframework.Net
     Castle MicroKernel/Windsor

Wikipedia has a huge list of existing frameworks.

Service Access - Poor mans dependency injection
Example - Dependency Injection

Required resources are injected into the class that requires
them.

 Constructor Injection




      Setter Injection
Example - Service Access

If you don't have access to a dependency injection container,
some of the testing benefits can be gained using a singleton
approach.




In your test setup you can then set itemService to a mocked
version to expose the seam.
Live Example

Java: Eclipse, JUnit 4.5, Mockito 1.7

VB.Net: Visual Studio 2005, NUnit 2.4, Rhino mocks 3.5




For more Mockito (Java) examples see http://maven/blog/?
p=76
Test Coverage

Keep the bar green AND the coverage green.

Java
   EMMA - has an eclipse plugin EclEmma




.Net
   NCover - commercial, has Visual Studio support
Summary

Each test case should be clearly defined in a separate test.

Tests provide executable documentation of how code works.

Test maintainability is important as tests make up a large
portion of the code base.
   Document the use case the test covers.
   Over-specification leads to more maintenance.

Exposing a seam keeps code loosely coupled and simplifies
testing through the use of mock objects.

Test Driven Development focuses development on how the
code is used and reduces build/deploy iterations = Faster.

Más contenido relacionado

La actualidad más candente

Java Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionJava Unit Test and Coverage Introduction
Java Unit Test and Coverage Introduction
Alex Su
 
Moq presentation
Moq presentationMoq presentation
Moq presentation
LynxStar
 
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
Jacinto Limjap
 
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
Dror Helper
 
Unit Testing Guidelines
Unit Testing GuidelinesUnit Testing Guidelines
Unit Testing Guidelines
Joel Hooks
 

La actualidad más candente (20)

Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testing
 
Unit Testing 101
Unit Testing 101Unit Testing 101
Unit Testing 101
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated Testing
 
Java Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionJava Unit Test and Coverage Introduction
Java Unit Test and Coverage Introduction
 
Workshop unit test
Workshop   unit testWorkshop   unit test
Workshop unit test
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDD
 
Unit Testing Done Right
Unit Testing Done RightUnit Testing Done Right
Unit Testing Done Right
 
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
 
Moq presentation
Moq presentationMoq presentation
Moq presentation
 
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
 
How and what to unit test
How and what to unit testHow and what to unit test
How and what to unit test
 
Unit testing
Unit testingUnit testing
Unit testing
 
Unit Test + Functional Programming = Love
Unit Test + Functional Programming = LoveUnit Test + Functional Programming = Love
Unit Test + Functional Programming = Love
 
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
 
Unit Testing (C#)
Unit Testing (C#)Unit Testing (C#)
Unit Testing (C#)
 
Beginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NETBeginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NET
 
Unit Testing Guidelines
Unit Testing GuidelinesUnit Testing Guidelines
Unit Testing Guidelines
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration Testing
 
Unit test
Unit testUnit test
Unit test
 

Similar a Unit Testing Fundamentals

Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@
Alex Borsuk
 
Automated Testing Of EPiServer CMS Sites
Automated Testing Of EPiServer CMS SitesAutomated Testing Of EPiServer CMS Sites
Automated Testing Of EPiServer CMS Sites
joelabrahamsson
 

Similar a Unit Testing Fundamentals (20)

Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++
 
Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@
 
Testing Hourglass at Jira Frontend - by Alexey Shpakov, Sr. Developer @ Atlas...
Testing Hourglass at Jira Frontend - by Alexey Shpakov, Sr. Developer @ Atlas...Testing Hourglass at Jira Frontend - by Alexey Shpakov, Sr. Developer @ Atlas...
Testing Hourglass at Jira Frontend - by Alexey Shpakov, Sr. Developer @ Atlas...
 
TDD Workshop UTN 2012
TDD Workshop UTN 2012TDD Workshop UTN 2012
TDD Workshop UTN 2012
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
 
Writing useful automated tests for the single page applications you build
Writing useful automated tests for the single page applications you buildWriting useful automated tests for the single page applications you build
Writing useful automated tests for the single page applications you build
 
Microsoft Fakes, Unit Testing the (almost) Untestable Code
Microsoft Fakes, Unit Testing the (almost) Untestable CodeMicrosoft Fakes, Unit Testing the (almost) Untestable Code
Microsoft Fakes, Unit Testing the (almost) Untestable Code
 
Unit Tests with Microsoft Fakes
Unit Tests with Microsoft FakesUnit Tests with Microsoft Fakes
Unit Tests with Microsoft Fakes
 
Unit tests and TDD
Unit tests and TDDUnit tests and TDD
Unit tests and TDD
 
Automated Testing Of EPiServer CMS Sites
Automated Testing Of EPiServer CMS SitesAutomated Testing Of EPiServer CMS Sites
Automated Testing Of EPiServer CMS Sites
 
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
Unit testing Unit testing
Unit testing
 
Mule testing
Mule testingMule testing
Mule testing
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
TDD - Agile
TDD - Agile TDD - Agile
TDD - Agile
 
Test driven development(tdd)
Test driven development(tdd)Test driven development(tdd)
Test driven development(tdd)
 
Automation Testing of Web based Application with Selenium and HP UFT (QTP)
Automation Testing of Web based Application with Selenium and HP UFT (QTP)Automation Testing of Web based Application with Selenium and HP UFT (QTP)
Automation Testing of Web based Application with Selenium and HP UFT (QTP)
 
Unit testing, principles
Unit testing, principlesUnit testing, principles
Unit testing, principles
 
Unit testing
Unit testingUnit testing
Unit testing
 
Unit testing & TDD concepts with best practice guidelines.
Unit testing & TDD concepts with best practice guidelines.Unit testing & TDD concepts with best practice guidelines.
Unit testing & TDD concepts with best practice guidelines.
 

Más de Richard Paul

Cucumber on the JVM with Groovy
Cucumber on the JVM with GroovyCucumber on the JVM with Groovy
Cucumber on the JVM with Groovy
Richard Paul
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics
Richard Paul
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
Richard Paul
 

Más de Richard Paul (9)

Cucumber on the JVM with Groovy
Cucumber on the JVM with GroovyCucumber on the JVM with Groovy
Cucumber on the JVM with Groovy
 
Acceptance testing with Geb
Acceptance testing with GebAcceptance testing with Geb
Acceptance testing with Geb
 
Acceptance tests
Acceptance testsAcceptance tests
Acceptance tests
 
jQuery Behaviours
jQuery BehavioursjQuery Behaviours
jQuery Behaviours
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency Injection
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVC
 
Using Dojo
Using DojoUsing Dojo
Using Dojo
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 

Último

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
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
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
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
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
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
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
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...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 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
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 

Unit Testing Fundamentals

  • 1. Unit Testing Fundamentals Richard Paul Kiwiplan NZ Ltd 27 Feb 2009
  • 2. What is Unit Testing? You all know what unit testing is, but here is a definition: In computer programming, unit testing is a method of testing that verifies the individual units of source code are working properly... -- http://en.wikipedia.org/wiki/Unit_testing
  • 3. Benefits of Unit Testing Automated regression tests, ensure code continues to work Executable, evolving documentation of how the code works. Allows code to be less brittle allowing for refactoring without fear. Test code in isolation of the rest of the system (which may not be written yet). Fewer bugs!
  • 4. Unit Testing vs Functional Testing Unit tests are written from a programmer's perspective. They ensure that a particular method of a class successfully performs a set of specific tasks. Functional tests are written from a user's perspective. These tests confirm that the system does what users are expecting it to. -- http://www.ibm.com/developerworks/library/j-test.html
  • 5. Structure of a Unit Test Test method per test case. Each test should run in isolation.
  • 6. Unit Testing Best Practices Unit tests should run fast. Allows developers to code fast. Don't hit the database unless you really need to. Tests should assert only what is required to exercise the code. Over-specification leads to excessive test maintenance. Unit tests should be developed in parallel to the code. Unit tests should be run automatically every time code is checked in. Using a continuous integration machine e.g.Hudson. Provides quick feedback for any integration problems.
  • 8. TDD Advantages You are encouraged to think about how your object is to be used. Develop faster, no compile/deploy cycle to check code works. Debugging a unit test is much simpler than a deployed application. Set of regression tests allowing you to refactor as you develop without fear of breaking previous functionality. Unit tests are likely to cover more edge cases as the object model is fresh in your mind.
  • 9. Expose a Seam A seam is a line at which the code being tested can be isolated. Collaborators on the other side of the seam should be replaceable to ensure we can isolate the code we wish to test. Code that exposes a seam is generally loosely coupled.
  • 10. Exposing a Seam At runtime, production classes are used.
  • 11. Mocking out collaborators Replaced production classes with mocks for testing.
  • 12. Anti-patterns - Static Methods Use of static methods means there is no way to replace the collaborators in the test, resulting in overly complex tests.
  • 13. Locally instantiated collaborators The class under test instantiates Class 1 and Class 2. We can't replace these classes in the test so we have no seam.
  • 14. Anti-pattern Further Reading Static Methods are Death to Testability http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/ To quot;newquot; or not to quot;newquot;… http://misko.hevery.com/2008/09/30/to-new-or-not-to-new/ You may have noticed, Miško Hevery is my hero.
  • 15. Mocking Frameworks Mocking frameworks provide a convenient means for ensuring unit tests remained focused by providing the ability to 'mock out' other objects. Frameworks include: Java Mockito EasyMock JMock .Net Moq (requires .Net 3.5) Rhino TypeMock
  • 16. Example - Accessing a Collaborator In order to provide a seam for code that uses services there needs to exist a way to swap out the service used. Dependency Injection Java Spring Framework Guice .Net Springframework.Net Castle MicroKernel/Windsor Wikipedia has a huge list of existing frameworks. Service Access - Poor mans dependency injection
  • 17. Example - Dependency Injection Required resources are injected into the class that requires them. Constructor Injection Setter Injection
  • 18. Example - Service Access If you don't have access to a dependency injection container, some of the testing benefits can be gained using a singleton approach. In your test setup you can then set itemService to a mocked version to expose the seam.
  • 19. Live Example Java: Eclipse, JUnit 4.5, Mockito 1.7 VB.Net: Visual Studio 2005, NUnit 2.4, Rhino mocks 3.5 For more Mockito (Java) examples see http://maven/blog/? p=76
  • 20. Test Coverage Keep the bar green AND the coverage green. Java EMMA - has an eclipse plugin EclEmma .Net NCover - commercial, has Visual Studio support
  • 21. Summary Each test case should be clearly defined in a separate test. Tests provide executable documentation of how code works. Test maintainability is important as tests make up a large portion of the code base. Document the use case the test covers. Over-specification leads to more maintenance. Exposing a seam keeps code loosely coupled and simplifies testing through the use of mock objects. Test Driven Development focuses development on how the code is used and reduces build/deploy iterations = Faster.