SlideShare uma empresa Scribd logo
1 de 47
JUG Roma 26 th  September 2006 “ Embrace Unit Testing” Alessio Pace  alessio.pace [AT] gmail.com http://www.jroller.com/page/alessiopace
3 things about me.. ,[object Object],[object Object],[object Object]
About this presentation ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Agenda ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
INTRODUCTION
Programmer life  without  Unit Testing ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
What is Unit Testing ,[object Object],[object Object],[object Object],[object Object]
“A set of Unit Testing rules” ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
The benefits of Unit Testing (1) ,[object Object],[object Object],[object Object]
The benefits of Unit Testing (2) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
The benefits of Unit Testing (3) ,[object Object],[object Object],[object Object],[object Object]
Bad rumours about Unit Testing ,[object Object],[object Object],[object Object]
Answers to the bad rumours (1/2) ,[object Object],[object Object],[object Object],[object Object]
Answers to the bad rumours (2/2) ,[object Object],[object Object],[object Object],[object Object],[object Object]
A short parenthesis on Refactoring ,[object Object],[object Object],[object Object],[object Object],[object Object]
PRACTICAL EXAMPLE
Let's get into a coding example! ,[object Object],[object Object],[object Object],[object Object]
Our example:  a high level description ,[object Object],[object Object],[object Object],[object Object]
Our example:  UML Class Diagram We have to  implement  and  test  the  CachedBookService  class
Constructor implementation of  CachedBookService public class  CachedBookService  implements IBookService { private IBookService  remoteBookService ; public CachedBookService(IBookService bookService){ if(bookService == null){ throw new IllegalArgumentException(); } this.remoteBookService = bookService; } public IBookService getRemoteBookService() { return remoteBookService; } public IBook getBook(String code)  throws NoSuchElementException {   // implementation left out for the moment    throw new NotImplementedException(); } } Ok, let's  test the constructor
How to automatically test the constructor? ,[object Object],[object Object],[object Object],[object Object]
JUnit: description ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Writing a JUnit 4.x test class  ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Testing object state after constructor import static org.junit.Assert.*; import org.junit.Test; public class  CachedBookServiceTest  { @Test  public void  testConstructor () { // anonymous class to test in isolation CachedBookService constructor IBookService bookServiceParameter = new IBookService(){ public IBook getBook(String code) throws NoSuchElementException { return null; } }; CachedBookService cachedBookService =  new CachedBookService(bookServiceParameter); assertNotNull ("Assert not null", cachedBookService.getRemoteBookService()); /* 3 identical ways to test the reference value:  */ assertTrue ("Assert same reference",  bookServiceParameter == cachedBookService.getRemoteBookService()); // assertSame ("Assert same reference", bookServiceParameter,  cachedBookService.getRemoteBookService()); // assertEquals (“Assert same reference”, bookServiceParameter,  cachedBookService.getRemoteBookService()) }
Testing exception is thrown //  CachedBookServiceTest.java @Test(expected=IllegalArgumentException.class) public void  testConstructorWithNullArg () { // should throw IllegaArgumentException with null arg   new CachedBookService( null ); } }
Enjoy the green bar :-)
Now let's implement  getBook()  method public class CachedBookService implements IBookService { private IbookService remoteBookService; private Map<String, IBook> cache; public CachedBookService(IBookService bookService){ if(bookService == null){ throw new IllegalArgumentException(); } this.remoteBookService = bookService; this.cache = new HashMap<String, IBook>(); } public IBook getBook(String code) throws NoSuchElementException { IBook ibook = cache.get(code); if(ibook != null){ return ibook; }else{ IBook result = this.remoteBookService.getBook(code); this.cache.put(code, result); return result; } } Ok, let's  test  getBook()
How to test  getBook()? ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
What are Mock Objects? ,[object Object],[object Object],[object Object],[object Object],[object Object]
Why are Mocks useful? ,[object Object],[object Object],[object Object],[object Object],[object Object]
EasyMock 2.2 ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
How to get a mock object with EasyMock 2.2 ,[object Object],[object Object],[object Object],[object Object],[object Object]
Testing getBook() - 1 st  test method @Test public void  testGetBook () { // (1) create the mock for the collaborating object IBookService   mockBookService = EasyMock.createMock(IBookService.class); // a mock with no behaviour as return value of getBook() IBook mockBook = EasyMock.createMock(IBook.class); // (2) record the expected behaviour EasyMock.expect(mockBookService.getBook(&quot;id123&quot;)).andReturn(mockBook); // (3) switch the mock to replay state EasyMock.replay(mockBookService); CachedBookService cachedBookService =  new CachedBookService(mockBookService);  // (4) perform the call to the class under test which interacts with the mock IBook result = cachedBookService.getBook(&quot;id123&quot;); assertSame(“Assert same reference”, mockBook, result); // (5) verify the mock has been used as expected EasyMock.verify(mockBookService); }
Testing getBook() - 2 nd  test method @Test public void  testGetBookTwoDifferentCodes () { // (1) create the mock for the collaborating object IBookService   mockBookService = EasyMock.createMock(IBookService.class); // a mock with no behaviour as return value of getBook() IBook mockBook = EasyMock.createMock(IBook.class); IBook mockBook2 = EasyMock.createMock(IBook.class); // (2) record two expected calls EasyMock.expect(mockBookService.getBook(&quot;id123&quot;)).andReturn(mockBook); EasyMock.expect(mockBookService.getBook(&quot;id456&quot;)).andReturn(mockBook2); // (3) switch the mock to replay state EasyMock.replay(mockBookService); CachedBookService cachedBookService =  new CachedBookService(mockBookService);  // (4) perform the call to the class under test which interacts with the mock IBook result = cachedBookService.getBook(&quot;id123&quot;); assertSame(“Assert same reference”, mockBook, result); IBook result2 = cachedBookService.getBook(&quot;id456&quot;); assertSame(“Assert same reference”, mockBook2, result2); // (5) verify the mock has been used as expected EasyMock.verify(mockBookService); }
Testing getBook() - 3 rd  test method @Test public void  testGetSameBookTwoTimes () { IBookService mockBookService = EasyMock.createMock(IBookService.class); IBook mockBook = EasyMock.createMock(IBook.class); // record only one call EasyMock.expect(mockBookService.getBook(&quot;id123&quot;)).andReturn(mockBook); EasyMock.replay(mockBookService); CachedBookService cachedBookService = new CachedBookService(mockBookService); IBook result = cachedBookService.getBook(&quot;id123&quot;); assertSame(mockBook, result); IBook secondResult = cachedBookService.getBook(&quot;id123&quot;); assertSame(result, secondResult); EasyMock.verify(mockBookService); }
Adding an IBookXmlSerializer ,[object Object],[object Object]
IBookXmlSerializer
IBookXmlSerializerImpl public class  IBookXmlSerializerImpl  implements IBookXmlSerializer { public String serialize(IBook book) { StringBuilder sb = new StringBuilder(&quot;&quot;); sb.append(&quot;<book>&quot;); sb.append(&quot;  <code>&quot; + book.getCode() + &quot;</code>&quot;); sb.append(&quot;  <title>&quot; + book.getTitle() + &quot;</title>&quot;); sb.append(&quot;  <author>&quot; + book.getAuthor() + &quot;</author>&quot;); sb.append(&quot;</book>&quot;); return sb.toString(); } } Ok, let's  test  serialize()
How to test serialize()? ,[object Object],[object Object],[object Object],[object Object]
Testing XML with XMLUnit ,[object Object],[object Object]
IbookXmlSerializerTest - Part 1 import org.custommonkey.xmlunit.XMLTestCase; public class IBookXmlSerializerImplTest { private IBookXmlSerializer serializer; private IBook book; private XMLTestCase xmlTestCase; @Before public void setUp() throws Exception { this.serializer = new IBookXmlSerializerImpl(); this.book = EasyMock.createMock(IBook.class); this.xmlTestCase = new XMLTestCase(); } // .... The method annotated with  @Before  is executed  before every @Test method execution
IbookXmlSerializerTest - Part 2 @Test public void testSerialize() throws Exception { final String code = &quot;id1&quot;; EasyMock.expect(this.book.getCode()).andReturn(code); final String title = &quot;Unit Testing&quot;; EasyMock.expect(this.book.getTitle()).andReturn(title); final String author = &quot;Mario Rossi&quot;; EasyMock.expect(this.book.getAuthor()).andReturn(author); // switch to replay state EasyMock.replay(this.book); String xml = this.serializer.serialize(book); this.xmlTestCase.assertXpathExists(&quot;/book&quot;, xml); this.xmlTestCase.assertXpathEvaluatesTo(code, &quot;/book/code&quot;, xml); this.xmlTestCase.assertXpathEvaluatesTo(title, &quot;/book/title&quot;, xml); this.xmlTestCase.assertXpathEvaluatesTo(author, &quot;/book/author&quot;, xml); // verify mock EasyMock.verify(this.book); }
If you appreciated Unit Testing... ,[object Object],[object Object],[object Object],[object Object],[object Object]
Test coverage with Cobertura
[object Object]
Some references 1/2 ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Some references 2/2 ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

Mais conteúdo relacionado

Mais procurados

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
 
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
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesDerek Smith
 
.Net Unit Testing with Visual Studio 2010
.Net Unit Testing with Visual Studio 2010.Net Unit Testing with Visual Studio 2010
.Net Unit Testing with Visual Studio 2010kgayda
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated TestingLee Englestone
 
Java Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionJava Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionAlex Su
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit TestingMike Lively
 
Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testingikhwanhayat
 
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...Thomas Weller
 
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible MistakesRoy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible MistakesRoy Osherove
 
How and what to unit test
How and what to unit testHow and what to unit test
How and what to unit testEugenio Lentini
 
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
 
TDD with Visual Studio 2010
TDD with Visual Studio 2010TDD with Visual Studio 2010
TDD with Visual Studio 2010Stefano Paluello
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit TestingJoe Tremblay
 

Mais procurados (20)

Unit testing, principles
Unit testing, principlesUnit testing, principles
Unit testing, principles
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
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
 
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 Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best Practices
 
.Net Unit Testing with Visual Studio 2010
.Net Unit Testing with Visual Studio 2010.Net Unit Testing with Visual Studio 2010
.Net Unit Testing with Visual Studio 2010
 
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
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit Testing
 
Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testing
 
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
 
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible MistakesRoy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
 
Unit test
Unit testUnit test
Unit test
 
Unit testing with java
Unit testing with javaUnit testing with java
Unit testing with java
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
How and what to unit test
How and what to unit testHow and what to unit test
How and what to 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
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
 
TDD with Visual Studio 2010
TDD with Visual Studio 2010TDD with Visual Studio 2010
TDD with Visual Studio 2010
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
 

Destaque

Win at life with unit testing
Win at life with unit testingWin at life with unit testing
Win at life with unit testingmarkstory
 
Tech talks #1- Unit testing and TDD
Tech talks #1- Unit testing and TDDTech talks #1- Unit testing and TDD
Tech talks #1- Unit testing and TDDDUONG Trong Tan
 
Unit testing with Junit
Unit testing with JunitUnit testing with Junit
Unit testing with JunitValerio Maggio
 
JUnit Kung Fu: Getting More Out of Your Unit Tests
JUnit Kung Fu: Getting More Out of Your Unit TestsJUnit Kung Fu: Getting More Out of Your Unit Tests
JUnit Kung Fu: Getting More Out of Your Unit TestsJohn Ferguson Smart Limited
 
Unit testing - the hard parts
Unit testing - the hard partsUnit testing - the hard parts
Unit testing - the hard partsShaun Abram
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practicesnickokiss
 
UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPTsuhasreddy1
 

Destaque (9)

Win at life with unit testing
Win at life with unit testingWin at life with unit testing
Win at life with unit testing
 
Tech talks #1- Unit testing and TDD
Tech talks #1- Unit testing and TDDTech talks #1- Unit testing and TDD
Tech talks #1- Unit testing and TDD
 
Unit testing with Junit
Unit testing with JunitUnit testing with Junit
Unit testing with Junit
 
JUnit Kung Fu: Getting More Out of Your Unit Tests
JUnit Kung Fu: Getting More Out of Your Unit TestsJUnit Kung Fu: Getting More Out of Your Unit Tests
JUnit Kung Fu: Getting More Out of Your Unit Tests
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Best practices unit testing
Best practices unit testing Best practices unit testing
Best practices unit testing
 
Unit testing - the hard parts
Unit testing - the hard partsUnit testing - the hard parts
Unit testing - the hard parts
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
 
UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPT
 

Semelhante a Embrace Unit Testing

Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Qualityguest268ee8
 
Nguyenvandungb seminar
Nguyenvandungb seminarNguyenvandungb seminar
Nguyenvandungb seminardunglinh111
 
Intro To Unit and integration Testing
Intro To Unit and integration TestingIntro To Unit and integration Testing
Intro To Unit and integration TestingPaul Churchward
 
An Introduction To Unit Testing and TDD
An Introduction To Unit Testing and TDDAn Introduction To Unit Testing and TDD
An Introduction To Unit Testing and TDDAhmed Ehab AbdulAziz
 
Coldbox developer training – session 4
Coldbox developer training – session 4Coldbox developer training – session 4
Coldbox developer training – session 4Billie Berzinskas
 
Xp Day 080506 Unit Tests And Mocks
Xp Day 080506 Unit Tests And MocksXp Day 080506 Unit Tests And Mocks
Xp Day 080506 Unit Tests And Mocksguillaumecarre
 
Unit Testing Android Applications
Unit Testing Android ApplicationsUnit Testing Android Applications
Unit Testing Android ApplicationsRody Middelkoop
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven DevelopmentJohn Blum
 
Stopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestStopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestSeb Rose
 
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++Hong Le Van
 
Software Testing
Software TestingSoftware Testing
Software TestingAdroitLogic
 
DotNet unit testing training
DotNet unit testing trainingDotNet unit testing training
DotNet unit testing trainingTom Tang
 
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosUnit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosFlutter Agency
 
J unit presentation
J unit presentationJ unit presentation
J unit presentationPriya Sharma
 
Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@Alex Borsuk
 
Unit Testing in Angular
Unit Testing in AngularUnit Testing in Angular
Unit Testing in AngularKnoldus Inc.
 

Semelhante a Embrace Unit Testing (20)

Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Quality
 
Nguyenvandungb seminar
Nguyenvandungb seminarNguyenvandungb seminar
Nguyenvandungb seminar
 
Intro To Unit and integration Testing
Intro To Unit and integration TestingIntro To Unit and integration Testing
Intro To Unit and integration Testing
 
An Introduction To Unit Testing and TDD
An Introduction To Unit Testing and TDDAn Introduction To Unit Testing and TDD
An Introduction To Unit Testing and TDD
 
Coldbox developer training – session 4
Coldbox developer training – session 4Coldbox developer training – session 4
Coldbox developer training – session 4
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Xp Day 080506 Unit Tests And Mocks
Xp Day 080506 Unit Tests And MocksXp Day 080506 Unit Tests And Mocks
Xp Day 080506 Unit Tests And Mocks
 
Unit Testing Android Applications
Unit Testing Android ApplicationsUnit Testing Android Applications
Unit Testing Android Applications
 
Unit tests and TDD
Unit tests and TDDUnit tests and TDD
Unit tests and TDD
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven Development
 
Stopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestStopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under Test
 
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++
 
Software Testing
Software TestingSoftware Testing
Software Testing
 
DotNet unit testing training
DotNet unit testing trainingDotNet unit testing training
DotNet unit testing training
 
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosUnit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
 
TDD Workshop UTN 2012
TDD Workshop UTN 2012TDD Workshop UTN 2012
TDD Workshop UTN 2012
 
J unit presentation
J unit presentationJ unit presentation
J unit presentation
 
Unit testing basic
Unit testing basicUnit testing basic
Unit testing basic
 
Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@
 
Unit Testing in Angular
Unit Testing in AngularUnit Testing in Angular
Unit Testing in Angular
 

Último

What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
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 slidevu2urc
 
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 DiscoveryTrustArc
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
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
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
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 TerraformAndrey Devyatkin
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
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 FresherRemote DBA Services
 

Último (20)

What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
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
 
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
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
+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...
 
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...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
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
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
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
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
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
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
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
 

Embrace Unit Testing

  • 1. JUG Roma 26 th September 2006 “ Embrace Unit Testing” Alessio Pace alessio.pace [AT] gmail.com http://www.jroller.com/page/alessiopace
  • 2.
  • 3.
  • 4.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 17.
  • 18.
  • 19. Our example: UML Class Diagram We have to implement and test the CachedBookService class
  • 20. Constructor implementation of CachedBookService public class CachedBookService implements IBookService { private IBookService remoteBookService ; public CachedBookService(IBookService bookService){ if(bookService == null){ throw new IllegalArgumentException(); } this.remoteBookService = bookService; } public IBookService getRemoteBookService() { return remoteBookService; } public IBook getBook(String code) throws NoSuchElementException { // implementation left out for the moment throw new NotImplementedException(); } } Ok, let's test the constructor
  • 21.
  • 22.
  • 23.
  • 24. Testing object state after constructor import static org.junit.Assert.*; import org.junit.Test; public class CachedBookServiceTest { @Test public void testConstructor () { // anonymous class to test in isolation CachedBookService constructor IBookService bookServiceParameter = new IBookService(){ public IBook getBook(String code) throws NoSuchElementException { return null; } }; CachedBookService cachedBookService = new CachedBookService(bookServiceParameter); assertNotNull (&quot;Assert not null&quot;, cachedBookService.getRemoteBookService()); /* 3 identical ways to test the reference value: */ assertTrue (&quot;Assert same reference&quot;, bookServiceParameter == cachedBookService.getRemoteBookService()); // assertSame (&quot;Assert same reference&quot;, bookServiceParameter, cachedBookService.getRemoteBookService()); // assertEquals (“Assert same reference”, bookServiceParameter, cachedBookService.getRemoteBookService()) }
  • 25. Testing exception is thrown // CachedBookServiceTest.java @Test(expected=IllegalArgumentException.class) public void testConstructorWithNullArg () { // should throw IllegaArgumentException with null arg new CachedBookService( null ); } }
  • 26. Enjoy the green bar :-)
  • 27. Now let's implement getBook() method public class CachedBookService implements IBookService { private IbookService remoteBookService; private Map<String, IBook> cache; public CachedBookService(IBookService bookService){ if(bookService == null){ throw new IllegalArgumentException(); } this.remoteBookService = bookService; this.cache = new HashMap<String, IBook>(); } public IBook getBook(String code) throws NoSuchElementException { IBook ibook = cache.get(code); if(ibook != null){ return ibook; }else{ IBook result = this.remoteBookService.getBook(code); this.cache.put(code, result); return result; } } Ok, let's test getBook()
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33. Testing getBook() - 1 st test method @Test public void testGetBook () { // (1) create the mock for the collaborating object IBookService mockBookService = EasyMock.createMock(IBookService.class); // a mock with no behaviour as return value of getBook() IBook mockBook = EasyMock.createMock(IBook.class); // (2) record the expected behaviour EasyMock.expect(mockBookService.getBook(&quot;id123&quot;)).andReturn(mockBook); // (3) switch the mock to replay state EasyMock.replay(mockBookService); CachedBookService cachedBookService = new CachedBookService(mockBookService); // (4) perform the call to the class under test which interacts with the mock IBook result = cachedBookService.getBook(&quot;id123&quot;); assertSame(“Assert same reference”, mockBook, result); // (5) verify the mock has been used as expected EasyMock.verify(mockBookService); }
  • 34. Testing getBook() - 2 nd test method @Test public void testGetBookTwoDifferentCodes () { // (1) create the mock for the collaborating object IBookService mockBookService = EasyMock.createMock(IBookService.class); // a mock with no behaviour as return value of getBook() IBook mockBook = EasyMock.createMock(IBook.class); IBook mockBook2 = EasyMock.createMock(IBook.class); // (2) record two expected calls EasyMock.expect(mockBookService.getBook(&quot;id123&quot;)).andReturn(mockBook); EasyMock.expect(mockBookService.getBook(&quot;id456&quot;)).andReturn(mockBook2); // (3) switch the mock to replay state EasyMock.replay(mockBookService); CachedBookService cachedBookService = new CachedBookService(mockBookService); // (4) perform the call to the class under test which interacts with the mock IBook result = cachedBookService.getBook(&quot;id123&quot;); assertSame(“Assert same reference”, mockBook, result); IBook result2 = cachedBookService.getBook(&quot;id456&quot;); assertSame(“Assert same reference”, mockBook2, result2); // (5) verify the mock has been used as expected EasyMock.verify(mockBookService); }
  • 35. Testing getBook() - 3 rd test method @Test public void testGetSameBookTwoTimes () { IBookService mockBookService = EasyMock.createMock(IBookService.class); IBook mockBook = EasyMock.createMock(IBook.class); // record only one call EasyMock.expect(mockBookService.getBook(&quot;id123&quot;)).andReturn(mockBook); EasyMock.replay(mockBookService); CachedBookService cachedBookService = new CachedBookService(mockBookService); IBook result = cachedBookService.getBook(&quot;id123&quot;); assertSame(mockBook, result); IBook secondResult = cachedBookService.getBook(&quot;id123&quot;); assertSame(result, secondResult); EasyMock.verify(mockBookService); }
  • 36.
  • 38. IBookXmlSerializerImpl public class IBookXmlSerializerImpl implements IBookXmlSerializer { public String serialize(IBook book) { StringBuilder sb = new StringBuilder(&quot;&quot;); sb.append(&quot;<book>&quot;); sb.append(&quot; <code>&quot; + book.getCode() + &quot;</code>&quot;); sb.append(&quot; <title>&quot; + book.getTitle() + &quot;</title>&quot;); sb.append(&quot; <author>&quot; + book.getAuthor() + &quot;</author>&quot;); sb.append(&quot;</book>&quot;); return sb.toString(); } } Ok, let's test serialize()
  • 39.
  • 40.
  • 41. IbookXmlSerializerTest - Part 1 import org.custommonkey.xmlunit.XMLTestCase; public class IBookXmlSerializerImplTest { private IBookXmlSerializer serializer; private IBook book; private XMLTestCase xmlTestCase; @Before public void setUp() throws Exception { this.serializer = new IBookXmlSerializerImpl(); this.book = EasyMock.createMock(IBook.class); this.xmlTestCase = new XMLTestCase(); } // .... The method annotated with @Before is executed before every @Test method execution
  • 42. IbookXmlSerializerTest - Part 2 @Test public void testSerialize() throws Exception { final String code = &quot;id1&quot;; EasyMock.expect(this.book.getCode()).andReturn(code); final String title = &quot;Unit Testing&quot;; EasyMock.expect(this.book.getTitle()).andReturn(title); final String author = &quot;Mario Rossi&quot;; EasyMock.expect(this.book.getAuthor()).andReturn(author); // switch to replay state EasyMock.replay(this.book); String xml = this.serializer.serialize(book); this.xmlTestCase.assertXpathExists(&quot;/book&quot;, xml); this.xmlTestCase.assertXpathEvaluatesTo(code, &quot;/book/code&quot;, xml); this.xmlTestCase.assertXpathEvaluatesTo(title, &quot;/book/title&quot;, xml); this.xmlTestCase.assertXpathEvaluatesTo(author, &quot;/book/author&quot;, xml); // verify mock EasyMock.verify(this.book); }
  • 43.
  • 44. Test coverage with Cobertura
  • 45.
  • 46.
  • 47.