SlideShare a Scribd company logo
1 of 67
Download to read offline
www.nickokiss.com
Production code
       Purpose:
          Meet business (functional) requirements
          Meet non-functional (system)
          requirements
Code
       Tests code
       Purpose:
          Testing
          Documentation
          Specification
Production code
        Purpose:
           Meet business (functional) requirements
           Meet non-functional (system) requirements
Code
       Tests code
        Purpose:
           Testing
           Documentation
           Specification




       Different                Different
       purpose        =         best practices
Unit testing best practices

3 steps                 No conditional logic
Fast                    No loops
Consistent              No exception catching
Atomic                  Assertions
Single responsibility   Informative assertion
Tests isolation         messages
Environment isolation   No test logic in production
Classes isolation       code
Fully automated          Separation per business
Self-descriptive        module
                        Separation per type
Unit testing best practices

3 steps                 No conditional logic
Fast                    No loops
Consistent              No exception catching
Atomic                  Assertions
Single responsibility   Informative assertion
Tests isolation         messages
Environment isolation   No test logic in production
Classes isolation       code
Fully automated          Separation per business
Self-descriptive        module
                        Separation per type
3 steps



Prepare an input

Call a method

Check an output
3 steps (5 steps)

Set up

Prepare an input

Call a method

Check an output

Tear down
Unit testing best practices

3 steps                 No conditional logic
Fast                    No loops
Consistent              No exception catching
Atomic                  Assertions
Single responsibility   Informative assertion
Tests isolation         messages
Environment isolation   No test logic in production
Classes isolation       code
Fully automated          Separation per business
Self-descriptive        module
                        Separation per type
Execution time - be fast

Why is it so important?


Frequent execution
   Several times per day [Test-after development]
   Several times per hour [Test driven development]
   Every few minutes [IDE - Execute after save]
Execution in groups
   10 tests = Execution time x 10
   100 tests = Execution time x 100
   Weak link: a slow test slows the whole suite
Execution time - be fast

What are the good numbers?



Expected average execution time in unit testing
   Single test: <200ms
   Small suite: <10s
   All tests suite: <10min
Unit testing best practices

3 steps                 No conditional logic
Fast                    No loops
Consistent              No exception catching
Atomic                  Assertions
Single responsibility   Informative assertion
Tests isolation         messages
Environment isolation   No test logic in production
Classes isolation       code
Fully automated          Separation per business
Self-descriptive        module
                        Separation per type
Consistent
Multiple invocations of the test should consistently return true or
consistently return false, provided no changes was made on code.


      What code can cause problems?

          Date currentDate = new Date();

          int value = random.nextInt(100);



 How to deal with this?
   Mocks
   Dependency injection
Unit testing best practices

3 steps                 No conditional logic
Fast                    No loops
Consistent              No exception catching
Atomic                  Assertions
Single responsibility   Informative assertion
Tests isolation         messages
Environment isolation   No test logic in production
Classes isolation       code
Fully automated          Separation per business
Self-descriptive        module
                        Separation per type
Atomic




Only two possible results: Pass or Fail
No partially successful tests
A test fails -> The whole suite fails
Broken window effect
Unit testing best practices

3 steps                 No conditional logic
Fast                    No loops
Consistent              No exception catching
Atomic                  Assertions
Single responsibility   Informative assertion
Tests isolation         messages
Environment isolation   No test logic in production
Classes isolation       code
Fully automated          Separation per business
Self-descriptive        module
                        Separation per type
Single responsibility

One test should be responsible for one scenario only.


Test behaviour, not methods:

   One method, multiple behaviours                      Multiple tests

   One behaviour, multiple methods                     One test
        A method calls private and protected methods
        A method calls very simple public methods
      (Especially: getters, setters, value objects, simple constructors)

   Multiple asserts in the same test - acceptable as long as
   they check the same behaviour
Single responsibility
    One method, multiple behaviours


testMethod(){                 testMethodCheckBehaviour1(){
    ...                           ...
    assertTrue(behaviour1);       assertTrue(behaviour1);
    assertTrue(behaviour2);   }
    assertTrue(behaviour3);   testMethodCheckBehaviour2(){
}                                 ...
                                  assertTrue(behaviour2);
                              }
                              testMethodCheckBehaviour3(){
                                  ...
                                  assertTrue(behaviour3);
                              }
Single responsibility
  Behaviour1 = condition1 + condition2 + condition3
  Behaviour2 = condition4 + condition5


testMethodCheckBehaviours(){   testMethodCheckBehaviour1(){
    ...    assertTrue              ...
(condition1);    assertTrue        assertTrue(condition1);
(condition2);    assertTrue        assertTrue(condition2);
(condition3);                      assertTrue(condition3);
    ...    assertTrue          }
(condition4);                  testMethodCheckBehaviour2(){
assertTrue(condition5);            ...
}                                  assertTrue(condition4);
                                   assertTrue(condition5);
                               }
Unit testing best practices

3 steps                 No conditional logic
Fast                    No loops
Consistent              No exception catching
Atomic                  Assertions
Single responsibility   Informative assertion
Tests isolation         messages
Environment isolation   No test logic in production
Classes isolation       code
Fully automated          Separation per business
Self-descriptive        module
                        Separation per type
Tests isolation
Tests should be independent from one another


  Different execution order - the same results

  No state sharing

  Instance variables
      JUnit - separated
      TestNG - shared
Unit testing best practices

3 steps                 No conditional logic
Fast                    No loops
Consistent              No exception catching
Atomic                  Assertions
Single responsibility   Informative assertion
Tests isolation         messages
Environment isolation   No test logic in production
Classes isolation       code
Fully automated          Separation per business
Self-descriptive        module
                        Separation per type
Environment isolation
Unit tests should be isolated from any environmental influences




       Database access
       Webservices calls
       JNDI look up
       Environment variables
       Property files
       System date and time
Environment isolation
Production code: A class heavily uses the
environment




            myMethod() {
              ...
              ...
              ...
            }
Environment isolation
                     Under unit testing: It doesn't work!




testMyMethod() {          myMethod() {
  ...                       ...
  myClass.myMethod          ...
(...)                       ...
  ...                     }
}
Environment isolation
                     Solution: Use mocks




testMyMethod() {         myMethod() {
  ...                      ...
  myClass.myMethod         ...
(...)                      ...
  ...                    }
}
Environment isolation
     Solution: Use mocks




Advantages:
   No test logic in production code
   Fast
   Easy to write
   Easy to re-use
Environment isolation
     Solution: Use mocks




Java mocking libraries (open source):
   EasyMock [ www.easymock.org ]
   JMock [ www.jmock.org ]
   Mockito [ www.mockito.org ]
Unit testing best practices

3 steps                 No conditional logic
Fast                    No loops
Consistent              No exception catching
Atomic                  Assertions
Single responsibility   Informative assertion
Tests isolation         messages
Environment isolation   No test logic in production
Classes isolation       code
Fully automated          Separation per business
Self-descriptive        module
                        Separation per type
Classes isolation



The less methods are executed by the test, the better
                                    (better code maintenance)




The less tests execute the method the better
                                   (better tests maintenance)
Classes isolation



           BUT:

high code coverage is a must
                      (ideally 100%)
Classes isolation

  The less methods are
  executed by the test, the
  better
  (better code maintenance)

                              high code coverage
                              is a must
                              (ideally 100%)


The less tests execute
the method the better
(better tests maintenance)
Classes isolation
Let's come back to our previous example to ilustrate the
problem

Step 0: The class under test has no dependencies
Classes isolation
Let's come back to our previous example to ilustrate the
problem

Step 1: The class depends on some other classes
Classes isolation
Let's come back to our previous example to ilustrate the
problem

Step 2: Dependencies of dependencies
Classes isolation
Let's come back to our previous example to ilustrate the
problem

Step 3: Dependencies of dependencies of dependencies
Classes isolation
Let's come back to our previous example to ilustrate the
problem

Step 4, 5, 6,...
Classes isolation
Conclusion: Mocking the environment is not enough
Classes isolation
Solution: Mock dependencies!
Classes isolation
Solution: Mock dependencies!
Classes isolation


Can be hard if code is not testable



How to write testable code?

   Don't call constructors inside a method. Use factories or
   dependency injection

   Use interfaces
Unit testing best practices

3 steps                 No conditional logic
Fast                    No loops
Consistent              No exception catching
Atomic                  Assertions
Single responsibility   Informative assertion
Tests isolation         messages
Environment isolation   No test logic in production
Classes isolation       code
Fully automated          Separation per business
Self-descriptive        module
                        Separation per type
Fully automated
No manual steps involved into testing.

     Automated tests execution
     Automated results gathering
     Automated decision making (success or failure)
     Automated results distribution
        Email
        IM
        System tray icon
        Dashboard web page
        IDE integration
        Lava lamps
Unit testing best practices

3 steps                 No conditional logic
Fast                    No loops
Consistent              No exception catching
Atomic                  Assertions
Single responsibility   Informative assertion
Tests isolation         messages
Environment isolation   No test logic in production
Classes isolation       code
Fully automated          Separation per business
Self-descriptive        module
                        Separation per type
Self-descriptive



Unit test = development level documentation



Unit test = method specification
               which is always up to date
Self-descriptive
Unit test must be easy to read and understand



     Variable names
     Method names
     Class names      }
     No conditional logic
                          Self-descriptive


     No loops
Unit testing best practices

3 steps                 No conditional logic
Fast                    No loops
Consistent              No exception catching
Atomic                  Assertions
Single responsibility   Informative assertion
Tests isolation         messages
Environment isolation   No test logic in production
Classes isolation       code
Fully automated          Separation per business
Self-descriptive        module
                        Separation per type
No conditional logic
Correctly written test contains no "if" or "switch"
statements.


No uncertainty
   All input values should be known
   Method behaviour should be predictible
   Expected output should be strict

Split the test into two (or more) tests instead of adding "if"
or "switch" statement.
No conditional logic
    One test, multiple conditions


testMethodBeforeOrAfter(){     testMethodBefore(){
     ...                           before = true;
  if (before) {                    assertTrue(behaviour1);
    assertTrue(behaviour1);    }
  } else if (after) {          testMethodAfter(){
    assertTrue(behaviour2);        after = true;
  } else { //now                   assertTrue(behaviour2);
    assertTrue(behaviour3);    }
  }                            testMethodNow(){
}                                  before = false;
                                   after = false;
                                   assertTrue(behaviour3);
                               }
Unit testing best practices

3 steps                 No conditional logic
Fast                    No loops
Consistent              No exception catching
Atomic                  Assertions
Single responsibility   Informative assertion
Tests isolation         messages
Environment isolation   No test logic in production
Classes isolation       code
Fully automated          Separation per business
Self-descriptive        module
                        Separation per type
No loops
High quality test contains no "while", "do-while" or "for"
statements.



Typical scenarios involving loops:

   Hundreds of repetitions
   A few repetitions
   Unknown number of repetitions
No loops

 Case 1: Hundreds of repetitions

If some logic in a test has to be repeated hundreds of
times, it probably means that the test is too complicated
and should be simplified.
No loops

Case 2: A few repetitions


Repeating things several times is OK, but then it's better to
type the code explicitly without loops.You can extract the
code which needs to be repeated into method and invoke it
a few times in a row.
No loops

Case 3: Unknown number of repetitions


If you don't know how many times you want to repeat the
code and it makes you difficult to avoid loops, it's very
likely that your test is incorrect and you should rather focus
on specifying more strict input data.
Unit testing best practices

3 steps                 No conditional logic
Fast                    No loops
Consistent              No exception catching
Atomic                  Assertions
Single responsibility   Informative assertion
Tests isolation         messages
Environment isolation   No test logic in production
Classes isolation       code
Fully automated          Separation per business
Self-descriptive        module
                        Separation per type
No exception catching

Catch an exception only if it's expected

Catch only expected type of an exception

Catch expected exception and call "fail" method

Let other exceptions go uncatched
Catching expected exception



testThrowingMyException(){
    try {
      myMethod(param);
      fail("MyException expected");
    } catch(MyException ex) {
      //OK
    }
}
Unit testing best practices

3 steps                 No conditional logic
Fast                    No loops
Consistent              No exception catching
Atomic                  Assertions
Single responsibility   Informative assertion
Tests isolation         messages
Environment isolation   No test logic in production
Classes isolation       code
Fully automated          Separation per business
Self-descriptive        module
                        Separation per type
Assertions

Use various types of assertions provided by a testing
framework

Create your own assertions to check more
complicated, repetitive conditions

Reuse your assertion methods

Loops inside assertions can be a good practice
Unit testing best practices

3 steps                 No conditional logic
Fast                    No loops
Consistent              No exception catching
Atomic                  Assertions
Single responsibility   Informative assertion
Tests isolation         messages
Environment isolation   No test logic in production
Classes isolation       code
Fully automated          Separation per business
Self-descriptive        module
                        Separation per type
Informative assertion messages
By reading an assertion message only, one should be
able to recognize the problem.


It's a good practice to include business logic information
into assertion message.



Assertion messages:

   Improve documentation of the code
   Inform about the problem in case of test failure
Unit testing best practices

3 steps                 No conditional logic
Fast                    No loops
Consistent              No exception catching
Atomic                  Assertions
Single responsibility   Informative assertion
Tests isolation         messages
Environment isolation   No test logic in
Classes isolation       production code
Fully automated          Separation per business
Self-descriptive        module
                        Separation per type
No test logic in production code

Separate unit tests and production code

Don't create methods/fields used only by unit tests

Use "Dependency Injection"
Unit testing best practices

3 steps                 No conditional logic
Fast                    No loops
Consistent              No exception catching
Atomic                  Assertions
Single responsibility   Informative assertion
Tests isolation         messages
Environment isolation   No test logic in production
Classes isolation       code
Fully automated         Separation per business
Self-descriptive        module
                        Separation per type
Separation per business module

Create suites of tests per business module

Use hierarchical approach

Decrease the execution time of suites by splitting
them into smaller ones (per sub-module)

Small suites can be executed more frequently
Unit testing best practices

3 steps                 No conditional logic
Fast                    No loops
Consistent              No exception catching
Atomic                  Assertions
Single responsibility   Informative assertion
Tests isolation         messages
Environment isolation   No test logic in production
Classes isolation       code
Fully automated          Separation per business
Self-descriptive        module
                        Separation per type
Separation per type

Keep unit tests separated from integration tests

   Different purpose of execution

   Different frequency of execution

   Different time of execution

   Different action in case of failure
Thank you!


                Find out more on:

http://www.nickokiss.com/2009/09/unit-testing.html




                   www.nickokiss.com

More Related Content

What's hot (20)

Introduction to JUnit
Introduction to JUnitIntroduction to JUnit
Introduction to JUnit
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration Testing
 
JUNit Presentation
JUNit PresentationJUNit Presentation
JUNit Presentation
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 
UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPT
 
Unit Testing (C#)
Unit Testing (C#)Unit Testing (C#)
Unit Testing (C#)
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Junit
JunitJunit
Junit
 
C++ Unit Test with Google Testing Framework
C++ Unit Test with Google Testing FrameworkC++ Unit Test with Google Testing Framework
C++ Unit Test with Google Testing Framework
 
Workshop unit test
Workshop   unit testWorkshop   unit test
Workshop unit test
 
TDD (Test Driven Design)
TDD (Test Driven Design)TDD (Test Driven Design)
TDD (Test Driven Design)
 
Unit test
Unit testUnit test
Unit test
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated Testing
 
TestNG with selenium
TestNG with seleniumTestNG with selenium
TestNG with selenium
 
Unit testing with java
Unit testing with javaUnit testing with java
Unit testing with java
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
 
TDD Flow: The Mantra in Action
TDD Flow: The Mantra in ActionTDD Flow: The Mantra in Action
TDD Flow: The Mantra in Action
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 

Similar to Unit testing best practices

Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Qualityguest268ee8
 
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 - the hard parts
Unit testing - the hard partsUnit testing - the hard parts
Unit testing - the hard partsShaun Abram
 
Unit testing basics with NUnit and Visual Studio
Unit testing basics with NUnit and Visual StudioUnit testing basics with NUnit and Visual Studio
Unit testing basics with NUnit and Visual StudioAmit Choudhary
 
Unit Testing & TDD Training for Mobile Apps
Unit Testing & TDD Training for Mobile AppsUnit Testing & TDD Training for Mobile Apps
Unit Testing & TDD Training for Mobile AppsMarcelo Busico
 
Solit 2012, TDD и отдельные аспекты тестирования в Java, Антонина Шафранская
Solit 2012, TDD и отдельные аспекты тестирования в Java, Антонина ШафранскаяSolit 2012, TDD и отдельные аспекты тестирования в Java, Антонина Шафранская
Solit 2012, TDD и отдельные аспекты тестирования в Java, Антонина Шафранскаяsolit
 
All about unit testing using (power) mock
All about unit testing using (power) mockAll about unit testing using (power) mock
All about unit testing using (power) mockPranalee Rokde
 
Quality Software With Unit Test
Quality Software With Unit TestQuality Software With Unit Test
Quality Software With Unit Testalice yang
 
Testing As A Bottleneck - How Testing Slows Down Modern Development Processes...
Testing As A Bottleneck - How Testing Slows Down Modern Development Processes...Testing As A Bottleneck - How Testing Slows Down Modern Development Processes...
Testing As A Bottleneck - How Testing Slows Down Modern Development Processes...TEST Huddle
 
Lecture (Software Testing).pptx
Lecture (Software Testing).pptxLecture (Software Testing).pptx
Lecture (Software Testing).pptxskknowledge
 
Principles and patterns for test driven development
Principles and patterns for test driven developmentPrinciples and patterns for test driven development
Principles and patterns for test driven developmentStephen Fuqua
 
Automated Unit Testing for Mere Mortals
Automated Unit Testing for Mere MortalsAutomated Unit Testing for Mere Mortals
Automated Unit Testing for Mere MortalsJess Chadwick
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2Tricode (part of Dept)
 

Similar to Unit testing best practices (20)

Unit testing
Unit testingUnit testing
Unit testing
 
Unit testing
Unit testingUnit testing
Unit testing
 
Testing legacy code
Testing legacy codeTesting legacy code
Testing legacy code
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Quality
 
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 - the hard parts
Unit testing - the hard partsUnit testing - the hard parts
Unit testing - the hard parts
 
Unit testing basics with NUnit and Visual Studio
Unit testing basics with NUnit and Visual StudioUnit testing basics with NUnit and Visual Studio
Unit testing basics with NUnit and Visual Studio
 
Effective unit testing
Effective unit testingEffective unit testing
Effective unit testing
 
Unit Testing & TDD Training for Mobile Apps
Unit Testing & TDD Training for Mobile AppsUnit Testing & TDD Training for Mobile Apps
Unit Testing & TDD Training for Mobile Apps
 
Solit 2012, TDD и отдельные аспекты тестирования в Java, Антонина Шафранская
Solit 2012, TDD и отдельные аспекты тестирования в Java, Антонина ШафранскаяSolit 2012, TDD и отдельные аспекты тестирования в Java, Антонина Шафранская
Solit 2012, TDD и отдельные аспекты тестирования в Java, Антонина Шафранская
 
Junit
JunitJunit
Junit
 
All about unit testing using (power) mock
All about unit testing using (power) mockAll about unit testing using (power) mock
All about unit testing using (power) mock
 
Quality Software With Unit Test
Quality Software With Unit TestQuality Software With Unit Test
Quality Software With Unit Test
 
Testing As A Bottleneck - How Testing Slows Down Modern Development Processes...
Testing As A Bottleneck - How Testing Slows Down Modern Development Processes...Testing As A Bottleneck - How Testing Slows Down Modern Development Processes...
Testing As A Bottleneck - How Testing Slows Down Modern Development Processes...
 
Lecture (Software Testing).pptx
Lecture (Software Testing).pptxLecture (Software Testing).pptx
Lecture (Software Testing).pptx
 
Unit testing basic
Unit testing basicUnit testing basic
Unit testing basic
 
Principles and patterns for test driven development
Principles and patterns for test driven developmentPrinciples and patterns for test driven development
Principles and patterns for test driven development
 
Automated Unit Testing for Mere Mortals
Automated Unit Testing for Mere MortalsAutomated Unit Testing for Mere Mortals
Automated Unit Testing for Mere Mortals
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2
 
Testing w-mocks
Testing w-mocksTesting w-mocks
Testing w-mocks
 

Recently uploaded

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 

Recently uploaded (20)

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 

Unit testing best practices

  • 2. Production code Purpose: Meet business (functional) requirements Meet non-functional (system) requirements Code Tests code Purpose: Testing Documentation Specification
  • 3. Production code Purpose: Meet business (functional) requirements Meet non-functional (system) requirements Code Tests code Purpose: Testing Documentation Specification Different Different purpose = best practices
  • 4. Unit testing best practices 3 steps No conditional logic Fast No loops Consistent No exception catching Atomic Assertions Single responsibility Informative assertion Tests isolation messages Environment isolation No test logic in production Classes isolation code Fully automated Separation per business Self-descriptive module Separation per type
  • 5. Unit testing best practices 3 steps No conditional logic Fast No loops Consistent No exception catching Atomic Assertions Single responsibility Informative assertion Tests isolation messages Environment isolation No test logic in production Classes isolation code Fully automated Separation per business Self-descriptive module Separation per type
  • 6. 3 steps Prepare an input Call a method Check an output
  • 7. 3 steps (5 steps) Set up Prepare an input Call a method Check an output Tear down
  • 8. Unit testing best practices 3 steps No conditional logic Fast No loops Consistent No exception catching Atomic Assertions Single responsibility Informative assertion Tests isolation messages Environment isolation No test logic in production Classes isolation code Fully automated Separation per business Self-descriptive module Separation per type
  • 9. Execution time - be fast Why is it so important? Frequent execution Several times per day [Test-after development] Several times per hour [Test driven development] Every few minutes [IDE - Execute after save] Execution in groups 10 tests = Execution time x 10 100 tests = Execution time x 100 Weak link: a slow test slows the whole suite
  • 10. Execution time - be fast What are the good numbers? Expected average execution time in unit testing Single test: <200ms Small suite: <10s All tests suite: <10min
  • 11. Unit testing best practices 3 steps No conditional logic Fast No loops Consistent No exception catching Atomic Assertions Single responsibility Informative assertion Tests isolation messages Environment isolation No test logic in production Classes isolation code Fully automated Separation per business Self-descriptive module Separation per type
  • 12. Consistent Multiple invocations of the test should consistently return true or consistently return false, provided no changes was made on code. What code can cause problems? Date currentDate = new Date(); int value = random.nextInt(100); How to deal with this? Mocks Dependency injection
  • 13. Unit testing best practices 3 steps No conditional logic Fast No loops Consistent No exception catching Atomic Assertions Single responsibility Informative assertion Tests isolation messages Environment isolation No test logic in production Classes isolation code Fully automated Separation per business Self-descriptive module Separation per type
  • 14. Atomic Only two possible results: Pass or Fail No partially successful tests A test fails -> The whole suite fails Broken window effect
  • 15. Unit testing best practices 3 steps No conditional logic Fast No loops Consistent No exception catching Atomic Assertions Single responsibility Informative assertion Tests isolation messages Environment isolation No test logic in production Classes isolation code Fully automated Separation per business Self-descriptive module Separation per type
  • 16. Single responsibility One test should be responsible for one scenario only. Test behaviour, not methods: One method, multiple behaviours Multiple tests One behaviour, multiple methods One test A method calls private and protected methods A method calls very simple public methods (Especially: getters, setters, value objects, simple constructors) Multiple asserts in the same test - acceptable as long as they check the same behaviour
  • 17. Single responsibility One method, multiple behaviours testMethod(){ testMethodCheckBehaviour1(){ ... ... assertTrue(behaviour1); assertTrue(behaviour1); assertTrue(behaviour2); } assertTrue(behaviour3); testMethodCheckBehaviour2(){ } ... assertTrue(behaviour2); } testMethodCheckBehaviour3(){ ... assertTrue(behaviour3); }
  • 18. Single responsibility Behaviour1 = condition1 + condition2 + condition3 Behaviour2 = condition4 + condition5 testMethodCheckBehaviours(){ testMethodCheckBehaviour1(){ ... assertTrue ... (condition1); assertTrue assertTrue(condition1); (condition2); assertTrue assertTrue(condition2); (condition3); assertTrue(condition3); ... assertTrue } (condition4); testMethodCheckBehaviour2(){ assertTrue(condition5); ... } assertTrue(condition4); assertTrue(condition5); }
  • 19. Unit testing best practices 3 steps No conditional logic Fast No loops Consistent No exception catching Atomic Assertions Single responsibility Informative assertion Tests isolation messages Environment isolation No test logic in production Classes isolation code Fully automated Separation per business Self-descriptive module Separation per type
  • 20. Tests isolation Tests should be independent from one another Different execution order - the same results No state sharing Instance variables JUnit - separated TestNG - shared
  • 21. Unit testing best practices 3 steps No conditional logic Fast No loops Consistent No exception catching Atomic Assertions Single responsibility Informative assertion Tests isolation messages Environment isolation No test logic in production Classes isolation code Fully automated Separation per business Self-descriptive module Separation per type
  • 22. Environment isolation Unit tests should be isolated from any environmental influences Database access Webservices calls JNDI look up Environment variables Property files System date and time
  • 23. Environment isolation Production code: A class heavily uses the environment myMethod() { ... ... ... }
  • 24. Environment isolation Under unit testing: It doesn't work! testMyMethod() { myMethod() { ... ... myClass.myMethod ... (...) ... ... } }
  • 25. Environment isolation Solution: Use mocks testMyMethod() { myMethod() { ... ... myClass.myMethod ... (...) ... ... } }
  • 26. Environment isolation Solution: Use mocks Advantages: No test logic in production code Fast Easy to write Easy to re-use
  • 27. Environment isolation Solution: Use mocks Java mocking libraries (open source): EasyMock [ www.easymock.org ] JMock [ www.jmock.org ] Mockito [ www.mockito.org ]
  • 28. Unit testing best practices 3 steps No conditional logic Fast No loops Consistent No exception catching Atomic Assertions Single responsibility Informative assertion Tests isolation messages Environment isolation No test logic in production Classes isolation code Fully automated Separation per business Self-descriptive module Separation per type
  • 29. Classes isolation The less methods are executed by the test, the better (better code maintenance) The less tests execute the method the better (better tests maintenance)
  • 30. Classes isolation BUT: high code coverage is a must (ideally 100%)
  • 31. Classes isolation The less methods are executed by the test, the better (better code maintenance) high code coverage is a must (ideally 100%) The less tests execute the method the better (better tests maintenance)
  • 32. Classes isolation Let's come back to our previous example to ilustrate the problem Step 0: The class under test has no dependencies
  • 33. Classes isolation Let's come back to our previous example to ilustrate the problem Step 1: The class depends on some other classes
  • 34. Classes isolation Let's come back to our previous example to ilustrate the problem Step 2: Dependencies of dependencies
  • 35. Classes isolation Let's come back to our previous example to ilustrate the problem Step 3: Dependencies of dependencies of dependencies
  • 36. Classes isolation Let's come back to our previous example to ilustrate the problem Step 4, 5, 6,...
  • 37. Classes isolation Conclusion: Mocking the environment is not enough
  • 40. Classes isolation Can be hard if code is not testable How to write testable code? Don't call constructors inside a method. Use factories or dependency injection Use interfaces
  • 41. Unit testing best practices 3 steps No conditional logic Fast No loops Consistent No exception catching Atomic Assertions Single responsibility Informative assertion Tests isolation messages Environment isolation No test logic in production Classes isolation code Fully automated Separation per business Self-descriptive module Separation per type
  • 42. Fully automated No manual steps involved into testing. Automated tests execution Automated results gathering Automated decision making (success or failure) Automated results distribution Email IM System tray icon Dashboard web page IDE integration Lava lamps
  • 43. Unit testing best practices 3 steps No conditional logic Fast No loops Consistent No exception catching Atomic Assertions Single responsibility Informative assertion Tests isolation messages Environment isolation No test logic in production Classes isolation code Fully automated Separation per business Self-descriptive module Separation per type
  • 44. Self-descriptive Unit test = development level documentation Unit test = method specification which is always up to date
  • 45. Self-descriptive Unit test must be easy to read and understand Variable names Method names Class names } No conditional logic Self-descriptive No loops
  • 46. Unit testing best practices 3 steps No conditional logic Fast No loops Consistent No exception catching Atomic Assertions Single responsibility Informative assertion Tests isolation messages Environment isolation No test logic in production Classes isolation code Fully automated Separation per business Self-descriptive module Separation per type
  • 47. No conditional logic Correctly written test contains no "if" or "switch" statements. No uncertainty All input values should be known Method behaviour should be predictible Expected output should be strict Split the test into two (or more) tests instead of adding "if" or "switch" statement.
  • 48. No conditional logic One test, multiple conditions testMethodBeforeOrAfter(){ testMethodBefore(){ ... before = true; if (before) { assertTrue(behaviour1); assertTrue(behaviour1); } } else if (after) { testMethodAfter(){ assertTrue(behaviour2); after = true; } else { //now assertTrue(behaviour2); assertTrue(behaviour3); } } testMethodNow(){ } before = false; after = false; assertTrue(behaviour3); }
  • 49. Unit testing best practices 3 steps No conditional logic Fast No loops Consistent No exception catching Atomic Assertions Single responsibility Informative assertion Tests isolation messages Environment isolation No test logic in production Classes isolation code Fully automated Separation per business Self-descriptive module Separation per type
  • 50. No loops High quality test contains no "while", "do-while" or "for" statements. Typical scenarios involving loops: Hundreds of repetitions A few repetitions Unknown number of repetitions
  • 51. No loops Case 1: Hundreds of repetitions If some logic in a test has to be repeated hundreds of times, it probably means that the test is too complicated and should be simplified.
  • 52. No loops Case 2: A few repetitions Repeating things several times is OK, but then it's better to type the code explicitly without loops.You can extract the code which needs to be repeated into method and invoke it a few times in a row.
  • 53. No loops Case 3: Unknown number of repetitions If you don't know how many times you want to repeat the code and it makes you difficult to avoid loops, it's very likely that your test is incorrect and you should rather focus on specifying more strict input data.
  • 54. Unit testing best practices 3 steps No conditional logic Fast No loops Consistent No exception catching Atomic Assertions Single responsibility Informative assertion Tests isolation messages Environment isolation No test logic in production Classes isolation code Fully automated Separation per business Self-descriptive module Separation per type
  • 55. No exception catching Catch an exception only if it's expected Catch only expected type of an exception Catch expected exception and call "fail" method Let other exceptions go uncatched
  • 56. Catching expected exception testThrowingMyException(){ try { myMethod(param); fail("MyException expected"); } catch(MyException ex) { //OK } }
  • 57. Unit testing best practices 3 steps No conditional logic Fast No loops Consistent No exception catching Atomic Assertions Single responsibility Informative assertion Tests isolation messages Environment isolation No test logic in production Classes isolation code Fully automated Separation per business Self-descriptive module Separation per type
  • 58. Assertions Use various types of assertions provided by a testing framework Create your own assertions to check more complicated, repetitive conditions Reuse your assertion methods Loops inside assertions can be a good practice
  • 59. Unit testing best practices 3 steps No conditional logic Fast No loops Consistent No exception catching Atomic Assertions Single responsibility Informative assertion Tests isolation messages Environment isolation No test logic in production Classes isolation code Fully automated Separation per business Self-descriptive module Separation per type
  • 60. Informative assertion messages By reading an assertion message only, one should be able to recognize the problem. It's a good practice to include business logic information into assertion message. Assertion messages: Improve documentation of the code Inform about the problem in case of test failure
  • 61. Unit testing best practices 3 steps No conditional logic Fast No loops Consistent No exception catching Atomic Assertions Single responsibility Informative assertion Tests isolation messages Environment isolation No test logic in Classes isolation production code Fully automated Separation per business Self-descriptive module Separation per type
  • 62. No test logic in production code Separate unit tests and production code Don't create methods/fields used only by unit tests Use "Dependency Injection"
  • 63. Unit testing best practices 3 steps No conditional logic Fast No loops Consistent No exception catching Atomic Assertions Single responsibility Informative assertion Tests isolation messages Environment isolation No test logic in production Classes isolation code Fully automated Separation per business Self-descriptive module Separation per type
  • 64. Separation per business module Create suites of tests per business module Use hierarchical approach Decrease the execution time of suites by splitting them into smaller ones (per sub-module) Small suites can be executed more frequently
  • 65. Unit testing best practices 3 steps No conditional logic Fast No loops Consistent No exception catching Atomic Assertions Single responsibility Informative assertion Tests isolation messages Environment isolation No test logic in production Classes isolation code Fully automated Separation per business Self-descriptive module Separation per type
  • 66. Separation per type Keep unit tests separated from integration tests Different purpose of execution Different frequency of execution Different time of execution Different action in case of failure
  • 67. Thank you! Find out more on: http://www.nickokiss.com/2009/09/unit-testing.html www.nickokiss.com