SlideShare une entreprise Scribd logo
1  sur  36
Unit testing with JUnit
       Tom Zimmermann
Testing


Testing is the activity of finding out whether a
piece of code (a method, class, or program)
produces the intended behavior.




                               taken from “Objects First with Java”
Edsger Dijkstra

        Program testing can be used
     to show the presence of bugs, but
       never to show their absence!
I don’t make
  mistakes!
I don’t make
  mistakes!
Test phases
Unit testing on individual units of
source code (=smallest testable part).

Integration testing on groups of
individual software modules.

System testing on a complete,
integrated system (evaluate
compliance with requirements)
JUnit




Kent Beck           Erich Gamma
JUnit




        taken from “JUnit: A Cook’s Tour”
Tests in JUnit
Tests are realized as public void testX() methods.
A test typically calls a few methods, then checks if
the state matches the expectation. If not, it fails.
Example: Call empty() on the shopping cart and
check the state with isEmpty()
// Tests the emptying of the cart.
public void testEmpty() {

    _bookCart.empty();

    assertTrue(_bookCart.isEmpty());
}
JUnit Checklist

 Initialize
 Write test cases
 Write a test suite
 Execute test suite
Example: Shopping cart


                   Add product
               1
Example: Shopping cart


                          Add product
                      1




     Remove product
 2
Example: Shopping cart
    Set of products
1




                                Add product
                            1




           Remove product
       2
Example: Shopping cart
    Set of products
1

    Number of products
2



                                Add product
                            1




           Remove product
       2
Example: Shopping cart
    Set of products
1

    Number of products
2

    Balance
3

                                Add product
                            1




           Remove product
       2
Part 1: Initialize
Constructor + Set up and tear down of fixture.
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

public class ShoppingCartTest extends TestCase {


   private ShoppingCart _bookCart;


   // Creates a new test case

   public ShoppingCartTest(String name) {

   
 super(name);

   }
Test fixture
// Creates test environment (fixture).
// Called before every testX() method.
protected void setUp() {

    _bookCart = new ShoppingCart();


   Product book = new Product(quot;Harry Potterquot;, 23.95);

   _bookCart.addItem(book);
}

// Releases test environment (fixture).
// Called after every testX() method.
protected void tearDown() {

    _bookCart = null;
}
Part 2: Write test cases
Help methods inherited from TestCase:
            – triggers a failure named msg
fail(msg)

                      – triggers a failure, when condition b is false
assertTrue(msg, b)

                               – triggers a failure, when v1 ≠ v2
assertEquals(msg, v1, v2)

                                  – triggers a failure, when |v1−v2|> ε
assertEquals(msg, v1, v2, ε)

                            – triggers a failure, when object is not null
assertNull(msg, object)

                                – triggers a failure, when object is null
assertNonNull(msg, object)

The parameter msg is optional.
Test: Add product
// Tests adding a product to the cart.
public void testProductAdd() {

    Product book = new Product(quot;Refactoringquot;, 53.95);

    _bookCart.addItem(book);


   assertTrue(_bookCart.contains(book));


   double expected = 23.95 + book.getPrice();

   double current = _bookCart.getBalance();


   assertEquals(expected, current, 0.0);


   int expectedCount = 2;

   int currentCount = _bookCart.getItemCount();


   assertEquals(expectedCount, currentCount);
}
Test: Add product
// Tests adding a product to the cart.
public void testProductAdd() {

    Product book = new Product(quot;Refactoringquot;, 53.95);

    _bookCart.addItem(book);


   assertTrue(_bookCart.contains(book));


   double expected = 23.95 + book.getPrice();

   double current = _bookCart.getBalance();


   assertEquals(expected, current, 0.0);


   int expectedCount = 2;

   int currentCount = _bookCart.getItemCount();


   assertEquals(expectedCount, currentCount);
}
Test: Remove product
// Tests removing a product from the cart.
public void testProductRemove() throws NotFoundException {

    Product book = new Product(quot;Harry Potterquot;, 23.95);

    _bookCart.removeItem(book);


   assertTrue(!_bookCart.contains(book));


   double expected = 23.95 - book.getPrice();

   double current = _bookCart.getBalance();


   assertEquals(expected, current, 0.0);


   int expectedCount = 0;

   int currentCount = _bookCart.getItemCount();


   assertEquals(expectedCount, currentCount);
}
Test: Remove product
// Tests removing a product from the cart.
public void testProductRemove() throws NotFoundException {

    Product book = new Product(quot;Harry Potterquot;, 23.95);

    _bookCart.removeItem(book);


   assertTrue(!_bookCart.contains(book));


   double expected = 23.95 - book.getPrice();

   double current = _bookCart.getBalance();


   assertEquals(expected, current, 0.0);


   int expectedCount = 0;

   int currentCount = _bookCart.getItemCount();


   assertEquals(expectedCount, currentCount);
}
Test: Exception handling

// Tests removing an unknown product from the cart.
public void testProductNotFound() {

    try {

    
 Product book = new Product(quot;Bonesquot;, 4.95);

    
 _bookCart.removeItem(book);


    
 fail(quot;Should raise a NotFoundExceptionquot;);

    } catch (NotFoundException nfe) {

    
 // Should always take this path

    }
}
Test: Exception handling

// Tests removing an unknown product from the cart.
public void testProductNotFound() {

    try {

    
 Product book = new Product(quot;Bonesquot;, 4.95);

    
 _bookCart.removeItem(book);


    
 fail(quot;Should raise a NotFoundExceptionquot;);

    } catch (NotFoundException nfe) {

    
 // Should always take this path

    }
}
Part 3: Write a test suite
The method suite() assembles the test methods
into a test suite – using reflection all methods
named testX() will be part of the test suite.
public static Test suite() {

    // Here: add all testX() methods to the suite (reflection).
    TestSuite suite = new TestSuite(ShoppingCartTest.class);

    //   Alternative: add methods manually (prone to error)
    //   TestSuite suite = new TestSuite();
    //   suite.addTest(new ShoppingCartTest(quot;testEmptyquot;));
    //   suite.addTest(new ShoppingCartTest(quot;testProductAddquot;));
    //   suite.addTest(...);

    return suite;
}
Part 4: Execute test suite
// Returns the name of the test case.
public String toString() {
  return getName();
}

// Main method: Call GUI
public static void main(String args[]) {
  String[] tcName = { ShoppingCartTest.class.getName() };
  junit.swingui.TestRunner.main(tcName);
  // junit.textui.TestRunner.main(tcName);
}


Execute the main() method to run the tests:
$ java ShoppingCartTest
Demo
I know I should test,
   but everything?
Best practices

Tests should be written before the code.
Test everything that could reasonably break.
If it can't break on its own, it's too simple to
break (like most get and set methods).
Run all your unit tests as often as possible.
Best practices (cont.)

                     Whenever you are tempted to
                 type something into a print statement
                or a debugger expression, write it as
                         a test instead.



Martin Fowler
Bits of research
Delta debugging




   Yesterday, my
 program worked.
Today, it does not.

                      Zeller (ESEC/FSE 1999), Burger et al. (ETX 2003)
Delta debugging




   Yesterday, my                     The change in
 program worked.                     Line 42 makes
Today, it does not.                 the program fail.
                      Zeller (ESEC/FSE 1999), Burger et al. (ETX 2003)
Continuous testing


 Continuously run tests in the background
   rapid feedback about test failures




                    Saff and Ernst (ISSRE 2003, ISSTA 2004)
Continuous testing


 Continuously run tests in the background
   rapid feedback about test failures




                    Saff and Ernst (ISSRE 2003, ISSTA 2004)
Summary
Testing                 Literature @ junit.org
  Unit testing            JUnit Test Infected.
  Integration testing     JUnit A Cook's Tour.
  System testing
                        Self-study questions
JUnit                     How can we test protected
  Test cases              and private methods?
  Test suites             What distinguishes a good
  Fixtures                test suite from a bad one?
                          Think of situations that are
Best practices            difficult to test.

Contenu connexe

Tendances (20)

Junit
JunitJunit
Junit
 
Introduction to JUnit
Introduction to JUnitIntroduction to JUnit
Introduction to JUnit
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
 
Junit
JunitJunit
Junit
 
Junit
JunitJunit
Junit
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
테스트자동화와 TDD
테스트자동화와 TDD테스트자동화와 TDD
테스트자동화와 TDD
 
05 junit
05 junit05 junit
05 junit
 
Mockito
MockitoMockito
Mockito
 
Unit testing framework
Unit testing frameworkUnit testing framework
Unit testing framework
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 
Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And Mocking
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Test Driven Development (TDD)
Test Driven Development (TDD)Test Driven Development (TDD)
Test Driven Development (TDD)
 
Mock your way with Mockito
Mock your way with MockitoMock your way with Mockito
Mock your way with Mockito
 
UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPT
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Unit Test
Unit TestUnit Test
Unit Test
 

Similaire à Unit testing with JUnit

GeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good TestsGeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good TestsTomek Kaczanowski
 
Confitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good TestsConfitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good TestsTomek Kaczanowski
 
J unit presentation
J unit presentationJ unit presentation
J unit presentationPriya Sharma
 
Junit4&testng presentation
Junit4&testng presentationJunit4&testng presentation
Junit4&testng presentationSanjib Dhar
 
Pragmatic unittestingwithj unit
Pragmatic unittestingwithj unitPragmatic unittestingwithj unit
Pragmatic unittestingwithj unitliminescence
 
How to write clean tests
How to write clean testsHow to write clean tests
How to write clean testsDanylenko Max
 
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 JanardhanaRavikiran J
 
Security Testing
Security TestingSecurity Testing
Security TestingKiran Kumar
 
Unit testing
Unit testingUnit testing
Unit testingjeslie
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentAll Things Open
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good TestsTomek Kaczanowski
 

Similaire à Unit testing with JUnit (20)

Junit With Eclipse
Junit With EclipseJunit With Eclipse
Junit With Eclipse
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
3 j unit
3 j unit3 j unit
3 j unit
 
GeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good TestsGeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good Tests
 
Confitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good TestsConfitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good Tests
 
J unit presentation
J unit presentationJ unit presentation
J unit presentation
 
Junit4&testng presentation
Junit4&testng presentationJunit4&testng presentation
Junit4&testng presentation
 
Junit
JunitJunit
Junit
 
8-testing.pptx
8-testing.pptx8-testing.pptx
8-testing.pptx
 
Pragmatic unittestingwithj unit
Pragmatic unittestingwithj unitPragmatic unittestingwithj unit
Pragmatic unittestingwithj unit
 
How to write clean tests
How to write clean testsHow to write clean tests
How to write clean tests
 
TestNG vs Junit
TestNG vs JunitTestNG vs Junit
TestNG vs Junit
 
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
 
Security Testing
Security TestingSecurity Testing
Security Testing
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Junit 4.0
Junit 4.0Junit 4.0
Junit 4.0
 
Unit testing
Unit testingUnit testing
Unit testing
 
Junit and testNG
Junit and testNGJunit and testNG
Junit and testNG
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End Development
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 

Plus de Thomas Zimmermann

Software Analytics = Sharing Information
Software Analytics = Sharing InformationSoftware Analytics = Sharing Information
Software Analytics = Sharing InformationThomas Zimmermann
 
Predicting Method Crashes with Bytecode Operations
Predicting Method Crashes with Bytecode OperationsPredicting Method Crashes with Bytecode Operations
Predicting Method Crashes with Bytecode OperationsThomas Zimmermann
 
Analytics for smarter software development
Analytics for smarter software development Analytics for smarter software development
Analytics for smarter software development Thomas Zimmermann
 
Characterizing and Predicting Which Bugs Get Reopened
Characterizing and Predicting Which Bugs Get ReopenedCharacterizing and Predicting Which Bugs Get Reopened
Characterizing and Predicting Which Bugs Get ReopenedThomas Zimmermann
 
Data driven games user research
Data driven games user researchData driven games user research
Data driven games user researchThomas Zimmermann
 
Not my bug! Reasons for software bug report reassignments
Not my bug! Reasons for software bug report reassignmentsNot my bug! Reasons for software bug report reassignments
Not my bug! Reasons for software bug report reassignmentsThomas Zimmermann
 
Empirical Software Engineering at Microsoft Research
Empirical Software Engineering at Microsoft ResearchEmpirical Software Engineering at Microsoft Research
Empirical Software Engineering at Microsoft ResearchThomas Zimmermann
 
Security trend analysis with CVE topic models
Security trend analysis with CVE topic modelsSecurity trend analysis with CVE topic models
Security trend analysis with CVE topic modelsThomas Zimmermann
 
Analytics for software development
Analytics for software developmentAnalytics for software development
Analytics for software developmentThomas Zimmermann
 
Characterizing and predicting which bugs get fixed
Characterizing and predicting which bugs get fixedCharacterizing and predicting which bugs get fixed
Characterizing and predicting which bugs get fixedThomas Zimmermann
 
Changes and Bugs: Mining and Predicting Development Activities
Changes and Bugs: Mining and Predicting Development ActivitiesChanges and Bugs: Mining and Predicting Development Activities
Changes and Bugs: Mining and Predicting Development ActivitiesThomas Zimmermann
 
Cross-project defect prediction
Cross-project defect predictionCross-project defect prediction
Cross-project defect predictionThomas Zimmermann
 
Changes and Bugs: Mining and Predicting Development Activities
Changes and Bugs: Mining and Predicting Development ActivitiesChanges and Bugs: Mining and Predicting Development Activities
Changes and Bugs: Mining and Predicting Development ActivitiesThomas Zimmermann
 
Predicting Defects using Network Analysis on Dependency Graphs
Predicting Defects using Network Analysis on Dependency GraphsPredicting Defects using Network Analysis on Dependency Graphs
Predicting Defects using Network Analysis on Dependency GraphsThomas Zimmermann
 
Quality of Bug Reports in Open Source
Quality of Bug Reports in Open SourceQuality of Bug Reports in Open Source
Quality of Bug Reports in Open SourceThomas Zimmermann
 
Predicting Subsystem Defects using Dependency Graph Complexities
Predicting Subsystem Defects using Dependency Graph Complexities Predicting Subsystem Defects using Dependency Graph Complexities
Predicting Subsystem Defects using Dependency Graph Complexities Thomas Zimmermann
 
Got Myth? Myths in Software Engineering
Got Myth? Myths in Software EngineeringGot Myth? Myths in Software Engineering
Got Myth? Myths in Software EngineeringThomas Zimmermann
 

Plus de Thomas Zimmermann (20)

Software Analytics = Sharing Information
Software Analytics = Sharing InformationSoftware Analytics = Sharing Information
Software Analytics = Sharing Information
 
MSR 2013 Preview
MSR 2013 PreviewMSR 2013 Preview
MSR 2013 Preview
 
Predicting Method Crashes with Bytecode Operations
Predicting Method Crashes with Bytecode OperationsPredicting Method Crashes with Bytecode Operations
Predicting Method Crashes with Bytecode Operations
 
Analytics for smarter software development
Analytics for smarter software development Analytics for smarter software development
Analytics for smarter software development
 
Characterizing and Predicting Which Bugs Get Reopened
Characterizing and Predicting Which Bugs Get ReopenedCharacterizing and Predicting Which Bugs Get Reopened
Characterizing and Predicting Which Bugs Get Reopened
 
Klingon Countdown Timer
Klingon Countdown TimerKlingon Countdown Timer
Klingon Countdown Timer
 
Data driven games user research
Data driven games user researchData driven games user research
Data driven games user research
 
Not my bug! Reasons for software bug report reassignments
Not my bug! Reasons for software bug report reassignmentsNot my bug! Reasons for software bug report reassignments
Not my bug! Reasons for software bug report reassignments
 
Empirical Software Engineering at Microsoft Research
Empirical Software Engineering at Microsoft ResearchEmpirical Software Engineering at Microsoft Research
Empirical Software Engineering at Microsoft Research
 
Security trend analysis with CVE topic models
Security trend analysis with CVE topic modelsSecurity trend analysis with CVE topic models
Security trend analysis with CVE topic models
 
Analytics for software development
Analytics for software developmentAnalytics for software development
Analytics for software development
 
Characterizing and predicting which bugs get fixed
Characterizing and predicting which bugs get fixedCharacterizing and predicting which bugs get fixed
Characterizing and predicting which bugs get fixed
 
Changes and Bugs: Mining and Predicting Development Activities
Changes and Bugs: Mining and Predicting Development ActivitiesChanges and Bugs: Mining and Predicting Development Activities
Changes and Bugs: Mining and Predicting Development Activities
 
Cross-project defect prediction
Cross-project defect predictionCross-project defect prediction
Cross-project defect prediction
 
Changes and Bugs: Mining and Predicting Development Activities
Changes and Bugs: Mining and Predicting Development ActivitiesChanges and Bugs: Mining and Predicting Development Activities
Changes and Bugs: Mining and Predicting Development Activities
 
Predicting Defects using Network Analysis on Dependency Graphs
Predicting Defects using Network Analysis on Dependency GraphsPredicting Defects using Network Analysis on Dependency Graphs
Predicting Defects using Network Analysis on Dependency Graphs
 
Quality of Bug Reports in Open Source
Quality of Bug Reports in Open SourceQuality of Bug Reports in Open Source
Quality of Bug Reports in Open Source
 
Meet Tom and his Fish
Meet Tom and his FishMeet Tom and his Fish
Meet Tom and his Fish
 
Predicting Subsystem Defects using Dependency Graph Complexities
Predicting Subsystem Defects using Dependency Graph Complexities Predicting Subsystem Defects using Dependency Graph Complexities
Predicting Subsystem Defects using Dependency Graph Complexities
 
Got Myth? Myths in Software Engineering
Got Myth? Myths in Software EngineeringGot Myth? Myths in Software Engineering
Got Myth? Myths in Software Engineering
 

Dernier

Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
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
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
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
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 

Dernier (20)

Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
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
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
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
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 

Unit testing with JUnit

  • 1. Unit testing with JUnit Tom Zimmermann
  • 2. Testing Testing is the activity of finding out whether a piece of code (a method, class, or program) produces the intended behavior. taken from “Objects First with Java”
  • 3. Edsger Dijkstra Program testing can be used to show the presence of bugs, but never to show their absence!
  • 4. I don’t make mistakes!
  • 5. I don’t make mistakes!
  • 6. Test phases Unit testing on individual units of source code (=smallest testable part). Integration testing on groups of individual software modules. System testing on a complete, integrated system (evaluate compliance with requirements)
  • 7. JUnit Kent Beck Erich Gamma
  • 8. JUnit taken from “JUnit: A Cook’s Tour”
  • 9. Tests in JUnit Tests are realized as public void testX() methods. A test typically calls a few methods, then checks if the state matches the expectation. If not, it fails. Example: Call empty() on the shopping cart and check the state with isEmpty() // Tests the emptying of the cart. public void testEmpty() { _bookCart.empty(); assertTrue(_bookCart.isEmpty()); }
  • 10. JUnit Checklist Initialize Write test cases Write a test suite Execute test suite
  • 11. Example: Shopping cart Add product 1
  • 12. Example: Shopping cart Add product 1 Remove product 2
  • 13. Example: Shopping cart Set of products 1 Add product 1 Remove product 2
  • 14. Example: Shopping cart Set of products 1 Number of products 2 Add product 1 Remove product 2
  • 15. Example: Shopping cart Set of products 1 Number of products 2 Balance 3 Add product 1 Remove product 2
  • 16. Part 1: Initialize Constructor + Set up and tear down of fixture. import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; public class ShoppingCartTest extends TestCase { private ShoppingCart _bookCart; // Creates a new test case public ShoppingCartTest(String name) { super(name); }
  • 17. Test fixture // Creates test environment (fixture). // Called before every testX() method. protected void setUp() { _bookCart = new ShoppingCart(); Product book = new Product(quot;Harry Potterquot;, 23.95); _bookCart.addItem(book); } // Releases test environment (fixture). // Called after every testX() method. protected void tearDown() { _bookCart = null; }
  • 18. Part 2: Write test cases Help methods inherited from TestCase: – triggers a failure named msg fail(msg) – triggers a failure, when condition b is false assertTrue(msg, b) – triggers a failure, when v1 ≠ v2 assertEquals(msg, v1, v2) – triggers a failure, when |v1−v2|> ε assertEquals(msg, v1, v2, ε) – triggers a failure, when object is not null assertNull(msg, object) – triggers a failure, when object is null assertNonNull(msg, object) The parameter msg is optional.
  • 19. Test: Add product // Tests adding a product to the cart. public void testProductAdd() { Product book = new Product(quot;Refactoringquot;, 53.95); _bookCart.addItem(book); assertTrue(_bookCart.contains(book)); double expected = 23.95 + book.getPrice(); double current = _bookCart.getBalance(); assertEquals(expected, current, 0.0); int expectedCount = 2; int currentCount = _bookCart.getItemCount(); assertEquals(expectedCount, currentCount); }
  • 20. Test: Add product // Tests adding a product to the cart. public void testProductAdd() { Product book = new Product(quot;Refactoringquot;, 53.95); _bookCart.addItem(book); assertTrue(_bookCart.contains(book)); double expected = 23.95 + book.getPrice(); double current = _bookCart.getBalance(); assertEquals(expected, current, 0.0); int expectedCount = 2; int currentCount = _bookCart.getItemCount(); assertEquals(expectedCount, currentCount); }
  • 21. Test: Remove product // Tests removing a product from the cart. public void testProductRemove() throws NotFoundException { Product book = new Product(quot;Harry Potterquot;, 23.95); _bookCart.removeItem(book); assertTrue(!_bookCart.contains(book)); double expected = 23.95 - book.getPrice(); double current = _bookCart.getBalance(); assertEquals(expected, current, 0.0); int expectedCount = 0; int currentCount = _bookCart.getItemCount(); assertEquals(expectedCount, currentCount); }
  • 22. Test: Remove product // Tests removing a product from the cart. public void testProductRemove() throws NotFoundException { Product book = new Product(quot;Harry Potterquot;, 23.95); _bookCart.removeItem(book); assertTrue(!_bookCart.contains(book)); double expected = 23.95 - book.getPrice(); double current = _bookCart.getBalance(); assertEquals(expected, current, 0.0); int expectedCount = 0; int currentCount = _bookCart.getItemCount(); assertEquals(expectedCount, currentCount); }
  • 23. Test: Exception handling // Tests removing an unknown product from the cart. public void testProductNotFound() { try { Product book = new Product(quot;Bonesquot;, 4.95); _bookCart.removeItem(book); fail(quot;Should raise a NotFoundExceptionquot;); } catch (NotFoundException nfe) { // Should always take this path } }
  • 24. Test: Exception handling // Tests removing an unknown product from the cart. public void testProductNotFound() { try { Product book = new Product(quot;Bonesquot;, 4.95); _bookCart.removeItem(book); fail(quot;Should raise a NotFoundExceptionquot;); } catch (NotFoundException nfe) { // Should always take this path } }
  • 25. Part 3: Write a test suite The method suite() assembles the test methods into a test suite – using reflection all methods named testX() will be part of the test suite. public static Test suite() { // Here: add all testX() methods to the suite (reflection). TestSuite suite = new TestSuite(ShoppingCartTest.class); // Alternative: add methods manually (prone to error) // TestSuite suite = new TestSuite(); // suite.addTest(new ShoppingCartTest(quot;testEmptyquot;)); // suite.addTest(new ShoppingCartTest(quot;testProductAddquot;)); // suite.addTest(...); return suite; }
  • 26. Part 4: Execute test suite // Returns the name of the test case. public String toString() { return getName(); } // Main method: Call GUI public static void main(String args[]) { String[] tcName = { ShoppingCartTest.class.getName() }; junit.swingui.TestRunner.main(tcName); // junit.textui.TestRunner.main(tcName); } Execute the main() method to run the tests: $ java ShoppingCartTest
  • 27. Demo
  • 28. I know I should test, but everything?
  • 29. Best practices Tests should be written before the code. Test everything that could reasonably break. If it can't break on its own, it's too simple to break (like most get and set methods). Run all your unit tests as often as possible.
  • 30. Best practices (cont.) Whenever you are tempted to type something into a print statement or a debugger expression, write it as a test instead. Martin Fowler
  • 32. Delta debugging Yesterday, my program worked. Today, it does not. Zeller (ESEC/FSE 1999), Burger et al. (ETX 2003)
  • 33. Delta debugging Yesterday, my The change in program worked. Line 42 makes Today, it does not. the program fail. Zeller (ESEC/FSE 1999), Burger et al. (ETX 2003)
  • 34. Continuous testing Continuously run tests in the background rapid feedback about test failures Saff and Ernst (ISSRE 2003, ISSTA 2004)
  • 35. Continuous testing Continuously run tests in the background rapid feedback about test failures Saff and Ernst (ISSRE 2003, ISSTA 2004)
  • 36. Summary Testing Literature @ junit.org Unit testing JUnit Test Infected. Integration testing JUnit A Cook's Tour. System testing Self-study questions JUnit How can we test protected Test cases and private methods? Test suites What distinguishes a good Fixtures test suite from a bad one? Think of situations that are Best practices difficult to test.