SlideShare ist ein Scribd-Unternehmen logo
1 von 26
Downloaden Sie, um offline zu lesen
Unit Testing Best Practices
Agenda
● Standards vs Principles
● Unit Testing Principles
● Let's Derive Standards
Principles vs Standards
● Principles
● a fundamental, primary, or general law or truth from
which others are derived: the principles of modern
physics.
● Standards
● Put at its simplest, a standard is an agreed,
repeatable way of doing something.
● Usually derived from Principles
Principles and Standards - Example
● Principle
● Code should be Understandable
● Corresponding Standards
● Method Length should be less than XX lines.
● Cyclomatic Complexity of method should be less
than YY.
● Class should not be more YY lines.
● No Magic Numbers.
Standards without Principles
● Misinterpretation
● Method() with complexity 25 might be split into
Method1() - 10, Method2() – 10, Method3() - 5
● Some Standards are dependent on the context
● Code like “public static int ZERO = 0”
● What if the new standards come in?
● Standards are some body's interpretation of
principles and they can change
● Imagine if rule for complexity is decreased from 10
to 5
Disambiguation – Unit Testing
● In this presentation, we use the term unit testing
to refer to xUnit testing (Junit, Nunit etc) done
on individual code units (Methods, Classes).
● We do not refer to the screen integration testing
performed by a developer on a web application.
Unit Testing Organization/Attitude
● More important than Code.
● Lead to Better Design (due to Continuous
Refactoring)
● Best written before Code (TDD ).
● TDD improves Design and Code Quality
● Separated from Production Code
● Find Defects Early
● Continuous Integration
Unit Testing Principles
1.Easy to understand (Typical test should take no
longer than 15 seconds to read.)
2.Test should fail only when there is a problem
with production code.
3.Tests should find all problems with production
code.
4.Tests should have as minimum duplication as
possible.
5.Should run quickly.
Examples we would use
● Amount getClientProductsSum(List<Product>)
● For a list of products, calculate the sum of product
amounts and return total.
● Throws a DifferentCurrenciesException() if the
products have different currencies
Principle 1 : Easy to Understand –
Example 1
@Test
public void testClientProductSum(){
List<Product> products = new ArrayList<Product>();
products.add(new ProductImpl(100, "Product 15", ProductType.BANK_GUARANTEE, new AmountImpl(
new BigDecimal("5.0"), Currency.EURO)));
products.add(new ProductImpl(120, "Product 20", ProductType.BANK_GUARANTEE, new AmountImpl(
new BigDecimal("6.0"), Currency.EURO)));
Amount temp = null;
try {
temp = clientBO.getClientProductsSum(products);
} catch (DifferentCurrenciesException e) {
fail();
}
assertEquals(Currency.EURO, temp.getCurrency());
assertEquals(new BigDecimal("11.0"), temp.getValue());
}
Principle 1 : Easy to Understand –
Example 2
@Test
public void testClientProductSum_AllProductsSameCurrency()
throws DifferentCurrenciesException {
Amount[] amounts = {
new AmountImpl(new BigDecimal("5.0"), Currency.EURO),
new AmountImpl(new BigDecimal("6.0"), Currency.EURO) };
List<Product> products = createProductListWithAmounts(amounts);
Amount actual = clientBO.getClientProductsSum(products);
Amount expected = new AmountImpl(new BigDecimal("11.0"), Currency.EURO);
assertAmount(actual, expected);
}
Principle 1 : Easy to Understand
● Name of the Unit Test
● Should indicate the condition being tested and (if
needed) the result
– testClientProductSum_AllProductsSameCurrency vs testClientProductSum
– testClientProductSum_DifferentCurrencies_ThrowsException vs
testClientProductSum1
– testClientProductSum_NoProducts vs testClientProductSum2
● Keyword test at start of method name is now superfluous.
(Junit 4 does not need it.)
– Methods can as well be named
clientProductSum_DifferentCurrencies_ThrowsException
Principle 1 : Easy to Understand
● Highlight values important to the test
– Test Setup
List<Product> products = new ArrayList<Product>();
products.add(new ProductImpl(100, "Product 15",ProductType.BANK_GUARANTEE, new
AmountImpl(new BigDecimal("5.0"), Currency.EURO)));
products.add(new ProductImpl(120, "Product 20",ProductType.BANK_GUARANTEE, new
AmountImpl(new BigDecimal("6.0"), Currency.EURO)));
COMPARED TO
Amount[] amounts = {
new AmountImpl(new BigDecimal("5.0"), Currency.EURO),
new AmountImpl(new BigDecimal("6.0"), Currency.EURO) };
List<Product> products = createProductListWithAmounts(amounts);
Principle 1 : Easy to Understand
● Highlight values important to the test
– Assertions
Amount expected = new AmountImpl(new BigDecimal("11.0"), Currency.EURO);
assertAmount(expected, actual);
COMPARED TO
Amount temp = clientBO.getClientProductsSum(products);
assertEquals(Currency.EURO, temp.getCurrency());
assertEquals(new BigDecimal("11.0"), temp.getValue());
Principle 1 : Easy to Understand
● One condition per test
● Results in simple code without if's , for's etc.
● If a test fails, you would know the exact condition
which is failing.
● Create useful assert methods to test the condition
– assertAmount(expected, actual);
private void assertAmount(Amount expected, Amount actual) {
assertEquals(expected.getCurrency(), actual.getCurrency());
assertEquals(expected.getValue(), actual.getValue());
}
Principle 1 : Easy to Understand
● No Exception Handling in a test method.
public void testClientProductSum_NoProducts() throws DifferentCurrenciesException
INSTEAD OF
public void testClientProductSum(){
try {
temp = clientBO.getClientProductsSum(products);
} catch (DifferentCurrenciesException e) {
fail();
}
}
Principle 1 : Easy to Understand
● Use annotated ExceptionHandling to test for
exceptions.
@Test(expected = DifferentCurrenciesException.class)
public void testClientProductSum_DifferentCurrencies_ThrowsException() throws Exception
{
CODE THAT THROWS EXCEPTION;
}
INSTEAD OF
@Test
public void testClientProductSum1() {
try {
CODE THAT THROWS EXCEPTION;
fail("DifferentCurrenciesException is expected");
} catch (DifferentCurrenciesException e) {
}}
Principle 1 : Easy to Understand -
Use new features
● Compare Arrays
● assertArrayEquals(expectedArray,actualArray)
● Testing Exceptions
● Annotation (exception = Exception.class)
● Testing Performance
● Annotation (timeout = 2)
– 2 milliseconds
Principle 2 : Fail only when there is
a defect in CUT (Code Under Test)
● No dependancies between test conditions.
● Don't assume the order in which tests would
run.
● Avoid External Dependancies
● Avoid depending on (db, external interface,network
connection,container).. Use Stubs/Mocks.
● Avoid depending on system date and random.
● Avoid hardcoding of paths
(“C:TestDatadataSet1.dat”);//Runs well on my
machine..
Principle 3 : Test's should find all
defect's in code
● Why else do we write test :)
● Test everything that could possibly break.
● Test Exceptions.
● Test Boundary Conditions.
● Use Strong Assertions
● Do not write “Tests for Coverage”
● Favorite maxim from Junit FAQ
● “Test until fear turns to boredom.”
Principle 3 : Test's should find all
defect's in code
● Junit FAQ : Should we test setters and getters?
becomeTimidAndTestEverything
while writingTheSameThingOverAndOverAgain
becomeMoreAggressive
writeFewerTests
writeTestsForMoreInterestingCases
if getBurnedByStupidDefect
feelStupid
becomeTimidAndTestEverything
end
End
● Remember this is a infinite loop :)
Principle 4 : Less Duplication
● No Discussion on this :)
Principle 5 : Test's should run
quickly
● To maximize benefits, tests should be run as
often as possible. Long running tests stop tests
from being run often.
● Avoid reading from
– File System or
– Network
● A temporary solution might be to “collect long
running tests into a separate test suite” and run it
less often.
Principle 5 : Test's should run
quickly
● To maximize benefits, tests should be run as
often as possible. Long running tests stop tests
from being run often.
● Avoid reading from
– File System or
– Network
● A temporary solution might be to “collect long
running tests into a separate test suite” and run it
less often.
Result : Tests as Documentation
● Well written tests act as documentation and can
be used for discussions with Business as well.
● Examples
– testClientProductSum_AllProductsSameCurrency
– testClientProductSum_DifferentCurrencies_ThrowsExcep
tion
– testClientProductSum_NoProducts
Thank You
Questions?

Weitere ähnliche Inhalte

Was ist angesagt?

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
 
Unit Testing Guidelines
Unit Testing GuidelinesUnit Testing Guidelines
Unit Testing Guidelines
Joel Hooks
 
Advanced junit and mockito
Advanced junit and mockitoAdvanced junit and mockito
Advanced junit and mockito
Mathieu Carbou
 

Was ist angesagt? (20)

Workshop unit test
Workshop   unit testWorkshop   unit test
Workshop unit test
 
Unit testing
Unit testingUnit testing
Unit testing
 
Unit Testing Done Right
Unit Testing Done RightUnit Testing Done Right
Unit Testing Done Right
 
Best practices unit testing
Best practices unit testing Best practices unit testing
Best practices unit testing
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
 
Junit
JunitJunit
Junit
 
Java Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionJava Unit Test and Coverage Introduction
Java Unit Test and Coverage Introduction
 
JUNit Presentation
JUNit PresentationJUNit Presentation
JUNit Presentation
 
Java Unit Testing
Java Unit TestingJava Unit Testing
Java Unit Testing
 
Unit Testing Guidelines
Unit Testing GuidelinesUnit Testing Guidelines
Unit Testing Guidelines
 
Thread & concurrancy
Thread & concurrancyThread & concurrancy
Thread & concurrancy
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best Practices
 
Introduction to JUnit
Introduction to JUnitIntroduction to JUnit
Introduction to JUnit
 
Unit testing, principles
Unit testing, principlesUnit testing, principles
Unit testing, principles
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
Software testing basics and its types
Software testing basics and its typesSoftware testing basics and its types
Software testing basics and its types
 
Advanced junit and mockito
Advanced junit and mockitoAdvanced junit and mockito
Advanced junit and mockito
 
Unit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran JanardhanaUnit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran Janardhana
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 
Simple Unit Testing With Netbeans 6.1
Simple Unit Testing With Netbeans 6.1Simple Unit Testing With Netbeans 6.1
Simple Unit Testing With Netbeans 6.1
 

Ähnlich wie Unit testing best practices with JUnit

Rules Programming tutorial
Rules Programming tutorialRules Programming tutorial
Rules Programming tutorial
Srinath Perera
 
Unit testing (workshop)
Unit testing (workshop)Unit testing (workshop)
Unit testing (workshop)
Foyzul Karim
 
Test driven development
Test driven developmentTest driven development
Test driven development
John Walsh
 

Ähnlich wie Unit testing best practices with JUnit (20)

Rules Programming tutorial
Rules Programming tutorialRules Programming tutorial
Rules Programming tutorial
 
Test Driven
Test DrivenTest Driven
Test Driven
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Effective Unit Test Style Guide
Effective Unit Test Style GuideEffective Unit Test Style Guide
Effective Unit Test Style Guide
 
Unit testing (workshop)
Unit testing (workshop)Unit testing (workshop)
Unit testing (workshop)
 
SE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and JunitSE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and Junit
 
Testing Spring Applications
Testing Spring ApplicationsTesting Spring Applications
Testing Spring Applications
 
Behaviour Driven Development and Thinking About Testing
Behaviour Driven Development and Thinking About TestingBehaviour Driven Development and Thinking About Testing
Behaviour Driven Development and Thinking About Testing
 
Bdd and-testing
Bdd and-testingBdd and-testing
Bdd and-testing
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)
 
Unit Testing and TDD 2017
Unit Testing and TDD 2017Unit Testing and TDD 2017
Unit Testing and TDD 2017
 
Writing Tests with the Unity Test Framework
Writing Tests with the Unity Test FrameworkWriting Tests with the Unity Test Framework
Writing Tests with the Unity Test Framework
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
"Unit Testing for Mobile App" by Fandy Gotama (OLX Indonesia)
"Unit Testing for Mobile App" by Fandy Gotama  (OLX Indonesia)"Unit Testing for Mobile App" by Fandy Gotama  (OLX Indonesia)
"Unit Testing for Mobile App" by Fandy Gotama (OLX Indonesia)
 
Tech In Asia PDC 2017 - Best practice unit testing in mobile apps
Tech In Asia PDC 2017 - Best practice unit testing in mobile appsTech In Asia PDC 2017 - Best practice unit testing in mobile apps
Tech In Asia PDC 2017 - Best practice unit testing in mobile apps
 
Test Driven Development en Go con Ginkgo y Gomega
Test Driven Development en Go con Ginkgo y GomegaTest Driven Development en Go con Ginkgo y Gomega
Test Driven Development en Go con Ginkgo y Gomega
 
SE2018_Lec 20_ Test-Driven Development (TDD)
SE2018_Lec 20_ Test-Driven Development (TDD)SE2018_Lec 20_ Test-Driven Development (TDD)
SE2018_Lec 20_ Test-Driven Development (TDD)
 
Shift-Left Testing: QA in a DevOps World by David Laulusa
Shift-Left Testing: QA in a DevOps World by David LaulusaShift-Left Testing: QA in a DevOps World by David Laulusa
Shift-Left Testing: QA in a DevOps World by David Laulusa
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
A la découverte des google/mock (aka gmock)
A la découverte des google/mock (aka gmock)A la découverte des google/mock (aka gmock)
A la découverte des google/mock (aka gmock)
 

Mehr von inTwentyEight Minutes

Mockito tutorial for beginners
Mockito tutorial for beginnersMockito tutorial for beginners
Mockito tutorial for beginners
inTwentyEight Minutes
 
J2ee (java ee) tutorial for beginners
J2ee (java ee) tutorial for beginnersJ2ee (java ee) tutorial for beginners
J2ee (java ee) tutorial for beginners
inTwentyEight Minutes
 
C interview questions and answers
C interview questions and answersC interview questions and answers
C interview questions and answers
inTwentyEight Minutes
 

Mehr von inTwentyEight Minutes (16)

Spring tutorial for beginners with examples
Spring tutorial for beginners with examplesSpring tutorial for beginners with examples
Spring tutorial for beginners with examples
 
Solid principles - Object oriendte
Solid principles - Object oriendteSolid principles - Object oriendte
Solid principles - Object oriendte
 
Programming examples for beginners
Programming examples for beginnersProgramming examples for beginners
Programming examples for beginners
 
Mockito tutorial for beginners
Mockito tutorial for beginnersMockito tutorial for beginners
Mockito tutorial for beginners
 
Maven tutorial for beginners
Maven tutorial for beginnersMaven tutorial for beginners
Maven tutorial for beginners
 
JUnit tutorial for beginners
JUnit tutorial for beginnersJUnit tutorial for beginners
JUnit tutorial for beginners
 
JSP tutorial for beginners
JSP tutorial for beginnersJSP tutorial for beginners
JSP tutorial for beginners
 
Java servlets tutorial for beginners
Java servlets tutorial for beginnersJava servlets tutorial for beginners
Java servlets tutorial for beginners
 
J2ee (java ee) design patterns and architecture
J2ee (java ee) design patterns and architectureJ2ee (java ee) design patterns and architecture
J2ee (java ee) design patterns and architecture
 
J2ee (java ee) tutorial for beginners
J2ee (java ee) tutorial for beginnersJ2ee (java ee) tutorial for beginners
J2ee (java ee) tutorial for beginners
 
Installing java, eclipse and maven
Installing java, eclipse and mavenInstalling java, eclipse and maven
Installing java, eclipse and maven
 
Indian IT Industry at Crossroads : What should developers and managers do?
Indian IT Industry at Crossroads  : What should developers and managers do?Indian IT Industry at Crossroads  : What should developers and managers do?
Indian IT Industry at Crossroads : What should developers and managers do?
 
Eclipse tutorial for beginners
Eclipse tutorial for beginnersEclipse tutorial for beginners
Eclipse tutorial for beginners
 
Design patterns for beginners
Design patterns for beginnersDesign patterns for beginners
Design patterns for beginners
 
C tutorial for beginners - with puzzles
C tutorial for beginners - with puzzlesC tutorial for beginners - with puzzles
C tutorial for beginners - with puzzles
 
C interview questions and answers
C interview questions and answersC interview questions and answers
C interview questions and answers
 

Kürzlich hochgeladen

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
MateoGardella
 

Kürzlich hochgeladen (20)

fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 

Unit testing best practices with JUnit

  • 1. Unit Testing Best Practices
  • 2. Agenda ● Standards vs Principles ● Unit Testing Principles ● Let's Derive Standards
  • 3. Principles vs Standards ● Principles ● a fundamental, primary, or general law or truth from which others are derived: the principles of modern physics. ● Standards ● Put at its simplest, a standard is an agreed, repeatable way of doing something. ● Usually derived from Principles
  • 4. Principles and Standards - Example ● Principle ● Code should be Understandable ● Corresponding Standards ● Method Length should be less than XX lines. ● Cyclomatic Complexity of method should be less than YY. ● Class should not be more YY lines. ● No Magic Numbers.
  • 5. Standards without Principles ● Misinterpretation ● Method() with complexity 25 might be split into Method1() - 10, Method2() – 10, Method3() - 5 ● Some Standards are dependent on the context ● Code like “public static int ZERO = 0” ● What if the new standards come in? ● Standards are some body's interpretation of principles and they can change ● Imagine if rule for complexity is decreased from 10 to 5
  • 6. Disambiguation – Unit Testing ● In this presentation, we use the term unit testing to refer to xUnit testing (Junit, Nunit etc) done on individual code units (Methods, Classes). ● We do not refer to the screen integration testing performed by a developer on a web application.
  • 7. Unit Testing Organization/Attitude ● More important than Code. ● Lead to Better Design (due to Continuous Refactoring) ● Best written before Code (TDD ). ● TDD improves Design and Code Quality ● Separated from Production Code ● Find Defects Early ● Continuous Integration
  • 8. Unit Testing Principles 1.Easy to understand (Typical test should take no longer than 15 seconds to read.) 2.Test should fail only when there is a problem with production code. 3.Tests should find all problems with production code. 4.Tests should have as minimum duplication as possible. 5.Should run quickly.
  • 9. Examples we would use ● Amount getClientProductsSum(List<Product>) ● For a list of products, calculate the sum of product amounts and return total. ● Throws a DifferentCurrenciesException() if the products have different currencies
  • 10. Principle 1 : Easy to Understand – Example 1 @Test public void testClientProductSum(){ List<Product> products = new ArrayList<Product>(); products.add(new ProductImpl(100, "Product 15", ProductType.BANK_GUARANTEE, new AmountImpl( new BigDecimal("5.0"), Currency.EURO))); products.add(new ProductImpl(120, "Product 20", ProductType.BANK_GUARANTEE, new AmountImpl( new BigDecimal("6.0"), Currency.EURO))); Amount temp = null; try { temp = clientBO.getClientProductsSum(products); } catch (DifferentCurrenciesException e) { fail(); } assertEquals(Currency.EURO, temp.getCurrency()); assertEquals(new BigDecimal("11.0"), temp.getValue()); }
  • 11. Principle 1 : Easy to Understand – Example 2 @Test public void testClientProductSum_AllProductsSameCurrency() throws DifferentCurrenciesException { Amount[] amounts = { new AmountImpl(new BigDecimal("5.0"), Currency.EURO), new AmountImpl(new BigDecimal("6.0"), Currency.EURO) }; List<Product> products = createProductListWithAmounts(amounts); Amount actual = clientBO.getClientProductsSum(products); Amount expected = new AmountImpl(new BigDecimal("11.0"), Currency.EURO); assertAmount(actual, expected); }
  • 12. Principle 1 : Easy to Understand ● Name of the Unit Test ● Should indicate the condition being tested and (if needed) the result – testClientProductSum_AllProductsSameCurrency vs testClientProductSum – testClientProductSum_DifferentCurrencies_ThrowsException vs testClientProductSum1 – testClientProductSum_NoProducts vs testClientProductSum2 ● Keyword test at start of method name is now superfluous. (Junit 4 does not need it.) – Methods can as well be named clientProductSum_DifferentCurrencies_ThrowsException
  • 13. Principle 1 : Easy to Understand ● Highlight values important to the test – Test Setup List<Product> products = new ArrayList<Product>(); products.add(new ProductImpl(100, "Product 15",ProductType.BANK_GUARANTEE, new AmountImpl(new BigDecimal("5.0"), Currency.EURO))); products.add(new ProductImpl(120, "Product 20",ProductType.BANK_GUARANTEE, new AmountImpl(new BigDecimal("6.0"), Currency.EURO))); COMPARED TO Amount[] amounts = { new AmountImpl(new BigDecimal("5.0"), Currency.EURO), new AmountImpl(new BigDecimal("6.0"), Currency.EURO) }; List<Product> products = createProductListWithAmounts(amounts);
  • 14. Principle 1 : Easy to Understand ● Highlight values important to the test – Assertions Amount expected = new AmountImpl(new BigDecimal("11.0"), Currency.EURO); assertAmount(expected, actual); COMPARED TO Amount temp = clientBO.getClientProductsSum(products); assertEquals(Currency.EURO, temp.getCurrency()); assertEquals(new BigDecimal("11.0"), temp.getValue());
  • 15. Principle 1 : Easy to Understand ● One condition per test ● Results in simple code without if's , for's etc. ● If a test fails, you would know the exact condition which is failing. ● Create useful assert methods to test the condition – assertAmount(expected, actual); private void assertAmount(Amount expected, Amount actual) { assertEquals(expected.getCurrency(), actual.getCurrency()); assertEquals(expected.getValue(), actual.getValue()); }
  • 16. Principle 1 : Easy to Understand ● No Exception Handling in a test method. public void testClientProductSum_NoProducts() throws DifferentCurrenciesException INSTEAD OF public void testClientProductSum(){ try { temp = clientBO.getClientProductsSum(products); } catch (DifferentCurrenciesException e) { fail(); } }
  • 17. Principle 1 : Easy to Understand ● Use annotated ExceptionHandling to test for exceptions. @Test(expected = DifferentCurrenciesException.class) public void testClientProductSum_DifferentCurrencies_ThrowsException() throws Exception { CODE THAT THROWS EXCEPTION; } INSTEAD OF @Test public void testClientProductSum1() { try { CODE THAT THROWS EXCEPTION; fail("DifferentCurrenciesException is expected"); } catch (DifferentCurrenciesException e) { }}
  • 18. Principle 1 : Easy to Understand - Use new features ● Compare Arrays ● assertArrayEquals(expectedArray,actualArray) ● Testing Exceptions ● Annotation (exception = Exception.class) ● Testing Performance ● Annotation (timeout = 2) – 2 milliseconds
  • 19. Principle 2 : Fail only when there is a defect in CUT (Code Under Test) ● No dependancies between test conditions. ● Don't assume the order in which tests would run. ● Avoid External Dependancies ● Avoid depending on (db, external interface,network connection,container).. Use Stubs/Mocks. ● Avoid depending on system date and random. ● Avoid hardcoding of paths (“C:TestDatadataSet1.dat”);//Runs well on my machine..
  • 20. Principle 3 : Test's should find all defect's in code ● Why else do we write test :) ● Test everything that could possibly break. ● Test Exceptions. ● Test Boundary Conditions. ● Use Strong Assertions ● Do not write “Tests for Coverage” ● Favorite maxim from Junit FAQ ● “Test until fear turns to boredom.”
  • 21. Principle 3 : Test's should find all defect's in code ● Junit FAQ : Should we test setters and getters? becomeTimidAndTestEverything while writingTheSameThingOverAndOverAgain becomeMoreAggressive writeFewerTests writeTestsForMoreInterestingCases if getBurnedByStupidDefect feelStupid becomeTimidAndTestEverything end End ● Remember this is a infinite loop :)
  • 22. Principle 4 : Less Duplication ● No Discussion on this :)
  • 23. Principle 5 : Test's should run quickly ● To maximize benefits, tests should be run as often as possible. Long running tests stop tests from being run often. ● Avoid reading from – File System or – Network ● A temporary solution might be to “collect long running tests into a separate test suite” and run it less often.
  • 24. Principle 5 : Test's should run quickly ● To maximize benefits, tests should be run as often as possible. Long running tests stop tests from being run often. ● Avoid reading from – File System or – Network ● A temporary solution might be to “collect long running tests into a separate test suite” and run it less often.
  • 25. Result : Tests as Documentation ● Well written tests act as documentation and can be used for discussions with Business as well. ● Examples – testClientProductSum_AllProductsSameCurrency – testClientProductSum_DifferentCurrencies_ThrowsExcep tion – testClientProductSum_NoProducts