SlideShare a Scribd company logo
JUnit Recipes:
Elementary tests
   Zheng-Wen Shen
     2007/12/06



                    1
Brief contents
    Part 1: The Building Blocks
    1.   Fundamentals
    2.   Elementary tests
    3.   Organizing and building JUnit tests
    4.   Managing test suites
    5.   Working with test data
    6.   Running JUnit tests
    7.   Reporting JUnit results
    8.   Troubleshooting JUnit
    Part 2: Testing J2EE
    Part 3: More JUnit Techniques

                                               2
Elementary tests
1. Test your equals methods
2. Test a method that returns nothing
3. Test a constructor
4. Test a getter
5. Test a setter
6. Test an interface
7. Test throwing the right exception
8. Let collections compare themselves
9. Test a big object for equality
10.Test an object that instantiates other   objects

                                                      3
1. Test your equals methods (1/3)
                      Test the implementation of equals()

 Value         Object: represents a value
       String, Integer, Double, Money, Timestamp,
        etc.
Money   a= new Money(100,0);
Money   b= new Money(100,0);            a
Money   c= new Money(50,0);                           b
Money   d= new Money(50,0);           100, 0
                                                    100, 0
a.equals( b ); // true
a.equals( c ); // false
c.equals( d ); // true                  c
c.equals( a ); // false
                                      50, 0           d
                                                    50, 0


                                                             4
1. Test your equals methods (2/3)
               Test the implementation of equals()

 The   contract of equals()
     Equivalence relations (RST)
       • Reflexive property
       • Symmetric property
       • Transitive property
     Consistent
     No object equals null



                                                     5
1. Test your equals methods (3/3)
                 Test the implementation of equals()




 equal to a
not equal to a
“looks equal”




 JUnit utility

                          RST, consistent, no object is equal null…



                                                                      6
2. Test a method that returns nothing
                                        (1/3)

   “How  do I test a method that return void?”
   If a method returns no value, it must have
    some observable side effect!

xyz obj = new xyz();                       xyz object state
obj.change();   //   transit   to   A
obj.change();   //   transit   to   B   Start        A
obj.change();   //   transit   to   C
obj.change();   //   transit   to   D



                                                B             C

                                                                  7
2. Test a method that returns nothing
                                    (2/3)

             To test the Collection.add(Object)
         1.      Create an empty collection
         2.      The collection should not contain the item in question
         3.      Add the item in question
         4.      Now the collection should contain the item in question


                   1
                   2
return nothing     3
                   4


                                                                    8
2. Test a method that returns nothing
                            (3/3)

          We are testing behavior, and not methods.
          If code does the wrong thing but no test
           fails, does it have as defect?

  
NOTE       The tests are the specification!!
            We describe what our code does by providing
             the tests our code passes.


                                                      9
3. Test a constructor

   Uses exposed internal state



   Observable side effect



   Pitfalls

                                       10
4. Test a getter (1/3)
    Which tests are needed and which are not

   Do not test methods that too simple to
    break!!




     too simple




                                               11
4. Test a getter (2/3)
    Which tests are needed and which are not

   Compare that result with an expected
    value




                                               12
4. Test a getter (3/3)
         Which tests are needed and which are not
  An alternative implementation…




Too simple to break




                                                    13
5. Test a setter (1/3)
                 Should I test my set methods?
         Basic set methods are too simple to break
         Effective way to test if you have to:

pattern                                     1
             2
             3
             4


      1.    Name the test method appropriately
      2.    Create an instance of your bean class
      3.    If newPropertyValue is a complex property, then initialize
            newPropertyValue.
      4.    If property is a more complex object than string, then you need
            to ensure that equals() is appropriately implemented
                                                                          14
5. Test a setter (2/3)
          Should I test my set methods?
                             If there are no get methods…




Command

                              Analyze the side effect



                                                        15
5. Test a setter (3/3)
              Should I test my set methods?
    BankTransferAction action = new BankTransferAction();
    action.setSourceAccountId("source");
    action.setTargetAccountId("target");
    action.setAmount(Money.dollars(100));


                                                             Bank

“Spy”
                                                            Subclass
                                                            Of Bank
                                                             (Spy)




                                                                16
6. Test an interface (1/4)
        to test all possible implementations
   Open-Closed Principle (OCP)
       software entities (classes, modules,
        functions, etc.) should be open for extension,
        but closed for modification
   Open for extension: the behavior of the
    module can be extended
   Closed for Modification: The source code
    of such a module is inviolate

                                                     17
6. Test an interface (2/4)
How to test all possible Iterator implementations…




                                                     18
6. Test an interface (3/4)

Close for modification                       test     Iterator
                         IteratorTest
                                                    <interface>
 Open for extension


                    abstraction is the key




                                                                  19
6. Test an interface (4/4)




                   all possible implementations




                                           20
7. Test throwing the right exception    (1/3)


   to verify that a method throws an
    expected exception under the appropriate
    circumstances.




                                            21
7. Test throwing the right exception                    (2/3)

1.   Identify the code that might throw the exception and
     place it in a try block.
2.   After invoking the method that might throw an
     exception, place a fail() statement
3.   Add a catch block for the expected exception.
4.   Verify that the exception object’s properties are the
     ones you expect, if desired.

         1
         2

     3
             4
                                                             22
7. Test throwing the right exception       (3/3)


                            Ilja PreuB approach

     OCP



           1
               2


           3
               4




                                                  23
8. Let collections compare themselves (1/3)
          to verify the contents of a collection
       To check for the items you expect, one by
        one.




One by one




                                                    24
8. Let collections compare themselves (2/3)

 Let
    the implementation of equals
 determine whether the collections are
 equal.




                                               25
8. Let collections compare themselves (3/3)




                                              26
9. Test a big object for equality (1/3)
test a Value Object with many key properties
     EqualsTester: for test the equals method



 equal to a
not equal to a
“looks equal”
                                          Money
                                          100, 0

 JUnit utility


                                                 27
9. Test a big object for equality (2/3)

           To test n+3 objects:
             two that are equal
             n that are different from those two
             the last one which is sublcass
                                BigObject
                        Key1, Key2, Key3, Key4,…




4 objects



                                                        28
9. Test a big object for equality (3/3)



                      the control object




                              N objects




                                           29
10. Test an object that instantiates
         other objects (1/5)
   You want to test an object in isolation, but
    it instantiates other objects that make
    testing difficult or expensive.
                          aggregation
      test
             Deployment                 Deployer




                                                   30
10. Test an object that instantiates
         other objects (2/5)
   How do you create an alternate
    implementation of this object’s
    collaborator?
   How do you pass it in to the object?

                           Deployer
     test
            Deployment

                            Deployer’
                          (Test Object)

                          predictable      31
10. Test an object that instantiates
         other objects (3/5)
 Create   a Test Object out of an interface
     Implement the interface the simplest way you
      can
     EasyMock (www.easymock.org)
 Create   a Test Object out of a class
     A fake method returns some predictable,
      meaningful, hard-coded value
     A stub method does nothing meaningful—only
      what is required to compile
                                                 32
10. Test an object that instantiates
             other objects (4/5)



                       refactoring
Testable




                                       33
10. Test an object that instantiates
               other objects (5/5)
 Mock




Test case



Test throwing
      the
right exception




                                         34
Brief contents
    Part 1: The Building Blocks
    1.   Fundamentals
    2.   Elementary tests
    3.   Organizing and building JUnit tests   See U next time!!
    4.   Managing test suites
    5.   Working with test data
    6.   Running JUnit tests
    7.   Reporting JUnit results
    8.   Troubleshooting JUnit
    Part 2: Testing J2EE
    Part 3: More JUnit Techniques

                                                              35

More Related Content

What's hot

OCA Java SE 8 Exam Chapter 6 Exceptions
OCA Java SE 8 Exam Chapter 6 ExceptionsOCA Java SE 8 Exam Chapter 6 Exceptions
OCA Java SE 8 Exam Chapter 6 Exceptions
İbrahim Kürce
 
Exception
ExceptionException
Exception
Sandeep Chawla
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
Vadym Lotar
 
Workshop unit test
Workshop   unit testWorkshop   unit test
Workshop unit test
Francesco Garavaglia
 
Mockito intro
Mockito introMockito intro
Mockito intro
Cristian R. Silva
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Lovely Professional University
 
OCA Java SE 8 Exam Chapter 5 Class Design
OCA Java SE 8 Exam Chapter 5 Class DesignOCA Java SE 8 Exam Chapter 5 Class Design
OCA Java SE 8 Exam Chapter 5 Class Design
İbrahim Kürce
 
Unit Testing Done Right
Unit Testing Done RightUnit Testing Done Right
Unit Testing Done Right
Brian Fenton
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
Bharath K
 
Effective Java - Chapter 3: Methods Common to All Objects
Effective Java - Chapter 3: Methods Common to All ObjectsEffective Java - Chapter 3: Methods Common to All Objects
Effective Java - Chapter 3: Methods Common to All Objects
İbrahim Kürce
 
Exception handling
Exception handlingException handling
Exception handling
Iblesoft
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
SURIT DATTA
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
Keshav Kumar
 
Unit Testing Best Practices
Unit Testing Best PracticesUnit Testing Best Practices
Unit Testing Best Practices
Tomaš Maconko
 
Java object oriented programming - OOPS
Java object oriented programming - OOPSJava object oriented programming - OOPS
Java object oriented programming - OOPS
rithustutorials
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
saman Iftikhar
 
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
 
Kill the mutants - A better way to test your tests
Kill the mutants - A better way to test your testsKill the mutants - A better way to test your tests
Kill the mutants - A better way to test your tests
Roy van Rijn
 
Effective Java Second Edition
Effective Java Second EditionEffective Java Second Edition
Effective Java Second Edition
losalamos
 
Exceptions
ExceptionsExceptions
Exceptions
motthu18
 

What's hot (20)

OCA Java SE 8 Exam Chapter 6 Exceptions
OCA Java SE 8 Exam Chapter 6 ExceptionsOCA Java SE 8 Exam Chapter 6 Exceptions
OCA Java SE 8 Exam Chapter 6 Exceptions
 
Exception
ExceptionException
Exception
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 
Workshop unit test
Workshop   unit testWorkshop   unit test
Workshop unit test
 
Mockito intro
Mockito introMockito intro
Mockito intro
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
OCA Java SE 8 Exam Chapter 5 Class Design
OCA Java SE 8 Exam Chapter 5 Class DesignOCA Java SE 8 Exam Chapter 5 Class Design
OCA Java SE 8 Exam Chapter 5 Class Design
 
Unit Testing Done Right
Unit Testing Done RightUnit Testing Done Right
Unit Testing Done Right
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Effective Java - Chapter 3: Methods Common to All Objects
Effective Java - Chapter 3: Methods Common to All ObjectsEffective Java - Chapter 3: Methods Common to All Objects
Effective Java - Chapter 3: Methods Common to All Objects
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
 
Unit Testing Best Practices
Unit Testing Best PracticesUnit Testing Best Practices
Unit Testing Best Practices
 
Java object oriented programming - OOPS
Java object oriented programming - OOPSJava object oriented programming - OOPS
Java object oriented programming - OOPS
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
Java Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionJava Unit Test and Coverage Introduction
Java Unit Test and Coverage Introduction
 
Kill the mutants - A better way to test your tests
Kill the mutants - A better way to test your testsKill the mutants - A better way to test your tests
Kill the mutants - A better way to test your tests
 
Effective Java Second Edition
Effective Java Second EditionEffective Java Second Edition
Effective Java Second Edition
 
Exceptions
ExceptionsExceptions
Exceptions
 

Viewers also liked

20060411 face recognition using face arg matching
20060411 face recognition using face arg matching20060411 face recognition using face arg matching
20060411 face recognition using face arg matching
Will Shen
 
E commerce goiania_ maio 2010 [compatibility mode]
E commerce   goiania_ maio 2010 [compatibility mode]E commerce   goiania_ maio 2010 [compatibility mode]
E commerce goiania_ maio 2010 [compatibility mode]
Sandra Turchi
 
Junit Recipes - Intro
Junit Recipes - IntroJunit Recipes - Intro
Junit Recipes - Intro
Will Shen
 
New Legal Framework on Identity Theft 2012
New Legal Framework on Identity Theft 2012New Legal Framework on Identity Theft 2012
New Legal Framework on Identity Theft 2012
- Mark - Fullbright
 
20050314 specification based regression test selection with risk analysis
20050314 specification based regression test selection with risk analysis20050314 specification based regression test selection with risk analysis
20050314 specification based regression test selection with risk analysis
Will Shen
 
20070514 introduction to test ng and its application for test driven gui deve...
20070514 introduction to test ng and its application for test driven gui deve...20070514 introduction to test ng and its application for test driven gui deve...
20070514 introduction to test ng and its application for test driven gui deve...
Will Shen
 
Day 6-notes-mesh-analysis
Day 6-notes-mesh-analysisDay 6-notes-mesh-analysis
Day 6-notes-mesh-analysis
sana9292
 

Viewers also liked (7)

20060411 face recognition using face arg matching
20060411 face recognition using face arg matching20060411 face recognition using face arg matching
20060411 face recognition using face arg matching
 
E commerce goiania_ maio 2010 [compatibility mode]
E commerce   goiania_ maio 2010 [compatibility mode]E commerce   goiania_ maio 2010 [compatibility mode]
E commerce goiania_ maio 2010 [compatibility mode]
 
Junit Recipes - Intro
Junit Recipes - IntroJunit Recipes - Intro
Junit Recipes - Intro
 
New Legal Framework on Identity Theft 2012
New Legal Framework on Identity Theft 2012New Legal Framework on Identity Theft 2012
New Legal Framework on Identity Theft 2012
 
20050314 specification based regression test selection with risk analysis
20050314 specification based regression test selection with risk analysis20050314 specification based regression test selection with risk analysis
20050314 specification based regression test selection with risk analysis
 
20070514 introduction to test ng and its application for test driven gui deve...
20070514 introduction to test ng and its application for test driven gui deve...20070514 introduction to test ng and its application for test driven gui deve...
20070514 introduction to test ng and its application for test driven gui deve...
 
Day 6-notes-mesh-analysis
Day 6-notes-mesh-analysisDay 6-notes-mesh-analysis
Day 6-notes-mesh-analysis
 

Similar to Junit Recipes - Elementary tests (2/2)

Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock Tutorial
Sbin m
 
Unit testing basic
Unit testing basicUnit testing basic
Unit testing basic
Yuri Anischenko
 
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
Pranalee Rokde
 
Easy mock
Easy mockEasy mock
Easy mock
Ramakrishna kapa
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
JWORKS powered by Ordina
 
Easy mockppt
Easy mockpptEasy mockppt
Easy mockppt
subha chandra
 
Software testing definition
Software testing definitionSoftware testing definition
Software testing definition
Hiro Mia
 
SE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and JunitSE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and Junit
Amr E. Mohamed
 
Integration testing
Integration testingIntegration testing
Integration testing
Tsegabrehan Am
 
Mocking with Mockito
Mocking with MockitoMocking with Mockito
Mocking with Mockito
Paul Churchward
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMock
Ying Zhang
 
What's software testing
What's software testingWhat's software testing
What's software testing
Li-Wei Cheng
 
Java Unit Test - JUnit
Java Unit Test - JUnitJava Unit Test - JUnit
Java Unit Test - JUnit
Aktuğ Urun
 
Testing Spring Boot application in post-JUnit 4 world
Testing Spring Boot application in post-JUnit 4 worldTesting Spring Boot application in post-JUnit 4 world
Testing Spring Boot application in post-JUnit 4 world
Yura Nosenko
 
Testing
TestingTesting
Testing
nazeer pasha
 
White box
White boxWhite box
White box
Hasam Panezai
 
White box
White boxWhite box
White box
sephalika
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Quality
guest268ee8
 
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
All Things Open
 
L2624 labriola
L2624 labriolaL2624 labriola
L2624 labriola
michael.labriola
 

Similar to Junit Recipes - Elementary tests (2/2) (20)

Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock Tutorial
 
Unit testing basic
Unit testing basicUnit testing basic
Unit testing basic
 
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
 
Easy mock
Easy mockEasy mock
Easy mock
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
 
Easy mockppt
Easy mockpptEasy mockppt
Easy mockppt
 
Software testing definition
Software testing definitionSoftware testing definition
Software testing definition
 
SE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and JunitSE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and Junit
 
Integration testing
Integration testingIntegration testing
Integration testing
 
Mocking with Mockito
Mocking with MockitoMocking with Mockito
Mocking with Mockito
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMock
 
What's software testing
What's software testingWhat's software testing
What's software testing
 
Java Unit Test - JUnit
Java Unit Test - JUnitJava Unit Test - JUnit
Java Unit Test - JUnit
 
Testing Spring Boot application in post-JUnit 4 world
Testing Spring Boot application in post-JUnit 4 worldTesting Spring Boot application in post-JUnit 4 world
Testing Spring Boot application in post-JUnit 4 world
 
Testing
TestingTesting
Testing
 
White box
White boxWhite box
White box
 
White box
White boxWhite box
White box
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Quality
 
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
 
L2624 labriola
L2624 labriolaL2624 labriola
L2624 labriola
 

More from Will Shen

20180717 Introduction of Seamless BLE Connection Migration System (SeamBlue)
20180717 Introduction of Seamless BLE Connection Migration System (SeamBlue)20180717 Introduction of Seamless BLE Connection Migration System (SeamBlue)
20180717 Introduction of Seamless BLE Connection Migration System (SeamBlue)
Will Shen
 
16格筆記讀書法
16格筆記讀書法16格筆記讀書法
16格筆記讀書法
Will Shen
 
Bade Smells in Code
Bade Smells in CodeBade Smells in Code
Bade Smells in Code
Will Shen
 
Intro To BOOST.Spirit
Intro To BOOST.SpiritIntro To BOOST.Spirit
Intro To BOOST.Spirit
Will Shen
 
20060411 Analytic Hierarchy Process (AHP)
20060411 Analytic Hierarchy Process (AHP)20060411 Analytic Hierarchy Process (AHP)
20060411 Analytic Hierarchy Process (AHP)
Will Shen
 
20050713 critical paths for gui regression testing
20050713 critical paths for gui regression testing20050713 critical paths for gui regression testing
20050713 critical paths for gui regression testing
Will Shen
 
20041113 A Test Generation Tool for Specifications in the Form of State Machine
20041113 A Test Generation Tool for Specifications in the Form of State Machine20041113 A Test Generation Tool for Specifications in the Form of State Machine
20041113 A Test Generation Tool for Specifications in the Form of State Machine
Will Shen
 
20051019 automating regression testing for evolving gui software
20051019 automating regression testing for evolving gui software20051019 automating regression testing for evolving gui software
20051019 automating regression testing for evolving gui software
Will Shen
 
20060712 automated model based testing of community-driven open-source gui ap...
20060712 automated model based testing of community-driven open-source gui ap...20060712 automated model based testing of community-driven open-source gui ap...
20060712 automated model based testing of community-driven open-source gui ap...
Will Shen
 
20041221 gui testing survey
20041221 gui testing survey20041221 gui testing survey
20041221 gui testing survey
Will Shen
 
20060927 application facades
20060927 application facades20060927 application facades
20060927 application facades
Will Shen
 
20111018 boost and gtest
20111018 boost and gtest20111018 boost and gtest
20111018 boost and gtest
Will Shen
 
Data collection for field studies
Data collection for field studiesData collection for field studies
Data collection for field studies
Will Shen
 

More from Will Shen (13)

20180717 Introduction of Seamless BLE Connection Migration System (SeamBlue)
20180717 Introduction of Seamless BLE Connection Migration System (SeamBlue)20180717 Introduction of Seamless BLE Connection Migration System (SeamBlue)
20180717 Introduction of Seamless BLE Connection Migration System (SeamBlue)
 
16格筆記讀書法
16格筆記讀書法16格筆記讀書法
16格筆記讀書法
 
Bade Smells in Code
Bade Smells in CodeBade Smells in Code
Bade Smells in Code
 
Intro To BOOST.Spirit
Intro To BOOST.SpiritIntro To BOOST.Spirit
Intro To BOOST.Spirit
 
20060411 Analytic Hierarchy Process (AHP)
20060411 Analytic Hierarchy Process (AHP)20060411 Analytic Hierarchy Process (AHP)
20060411 Analytic Hierarchy Process (AHP)
 
20050713 critical paths for gui regression testing
20050713 critical paths for gui regression testing20050713 critical paths for gui regression testing
20050713 critical paths for gui regression testing
 
20041113 A Test Generation Tool for Specifications in the Form of State Machine
20041113 A Test Generation Tool for Specifications in the Form of State Machine20041113 A Test Generation Tool for Specifications in the Form of State Machine
20041113 A Test Generation Tool for Specifications in the Form of State Machine
 
20051019 automating regression testing for evolving gui software
20051019 automating regression testing for evolving gui software20051019 automating regression testing for evolving gui software
20051019 automating regression testing for evolving gui software
 
20060712 automated model based testing of community-driven open-source gui ap...
20060712 automated model based testing of community-driven open-source gui ap...20060712 automated model based testing of community-driven open-source gui ap...
20060712 automated model based testing of community-driven open-source gui ap...
 
20041221 gui testing survey
20041221 gui testing survey20041221 gui testing survey
20041221 gui testing survey
 
20060927 application facades
20060927 application facades20060927 application facades
20060927 application facades
 
20111018 boost and gtest
20111018 boost and gtest20111018 boost and gtest
20111018 boost and gtest
 
Data collection for field studies
Data collection for field studiesData collection for field studies
Data collection for field studies
 

Recently uploaded

“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
Edge AI and Vision Alliance
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid ResearchHarnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
Neo4j
 
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving
 
Principle of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptxPrinciple of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptx
BibashShahi
 
AppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSFAppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSF
Ajin Abraham
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Neo4j
 
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
Edge AI and Vision Alliance
 
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
Fwdays
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
Ivo Velitchkov
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
saastr
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
ScyllaDB
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
Alex Pruden
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
Jason Yip
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
AstuteBusiness
 

Recently uploaded (20)

“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid ResearchHarnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
 
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024
 
Principle of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptxPrinciple of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptx
 
AppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSFAppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSF
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
 
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
 
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
 
Artificial Intelligence and Electronic Warfare
Artificial Intelligence and Electronic WarfareArtificial Intelligence and Electronic Warfare
Artificial Intelligence and Electronic Warfare
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
 

Junit Recipes - Elementary tests (2/2)

  • 1. JUnit Recipes: Elementary tests Zheng-Wen Shen 2007/12/06 1
  • 2. Brief contents  Part 1: The Building Blocks 1. Fundamentals 2. Elementary tests 3. Organizing and building JUnit tests 4. Managing test suites 5. Working with test data 6. Running JUnit tests 7. Reporting JUnit results 8. Troubleshooting JUnit  Part 2: Testing J2EE  Part 3: More JUnit Techniques 2
  • 3. Elementary tests 1. Test your equals methods 2. Test a method that returns nothing 3. Test a constructor 4. Test a getter 5. Test a setter 6. Test an interface 7. Test throwing the right exception 8. Let collections compare themselves 9. Test a big object for equality 10.Test an object that instantiates other objects 3
  • 4. 1. Test your equals methods (1/3) Test the implementation of equals()  Value Object: represents a value  String, Integer, Double, Money, Timestamp, etc. Money a= new Money(100,0); Money b= new Money(100,0); a Money c= new Money(50,0); b Money d= new Money(50,0); 100, 0 100, 0 a.equals( b ); // true a.equals( c ); // false c.equals( d ); // true c c.equals( a ); // false 50, 0 d 50, 0 4
  • 5. 1. Test your equals methods (2/3) Test the implementation of equals()  The contract of equals()  Equivalence relations (RST) • Reflexive property • Symmetric property • Transitive property  Consistent  No object equals null 5
  • 6. 1. Test your equals methods (3/3) Test the implementation of equals() equal to a not equal to a “looks equal” JUnit utility RST, consistent, no object is equal null… 6
  • 7. 2. Test a method that returns nothing (1/3)  “How do I test a method that return void?”  If a method returns no value, it must have some observable side effect! xyz obj = new xyz(); xyz object state obj.change(); // transit to A obj.change(); // transit to B Start A obj.change(); // transit to C obj.change(); // transit to D B C 7
  • 8. 2. Test a method that returns nothing (2/3)  To test the Collection.add(Object) 1. Create an empty collection 2. The collection should not contain the item in question 3. Add the item in question 4. Now the collection should contain the item in question 1 2 return nothing 3 4 8
  • 9. 2. Test a method that returns nothing (3/3)  We are testing behavior, and not methods.  If code does the wrong thing but no test fails, does it have as defect?  NOTE The tests are the specification!!  We describe what our code does by providing the tests our code passes. 9
  • 10. 3. Test a constructor  Uses exposed internal state  Observable side effect  Pitfalls 10
  • 11. 4. Test a getter (1/3) Which tests are needed and which are not  Do not test methods that too simple to break!! too simple 11
  • 12. 4. Test a getter (2/3) Which tests are needed and which are not  Compare that result with an expected value 12
  • 13. 4. Test a getter (3/3) Which tests are needed and which are not An alternative implementation… Too simple to break 13
  • 14. 5. Test a setter (1/3) Should I test my set methods?  Basic set methods are too simple to break  Effective way to test if you have to: pattern 1 2 3 4 1. Name the test method appropriately 2. Create an instance of your bean class 3. If newPropertyValue is a complex property, then initialize newPropertyValue. 4. If property is a more complex object than string, then you need to ensure that equals() is appropriately implemented 14
  • 15. 5. Test a setter (2/3) Should I test my set methods? If there are no get methods… Command Analyze the side effect 15
  • 16. 5. Test a setter (3/3) Should I test my set methods? BankTransferAction action = new BankTransferAction(); action.setSourceAccountId("source"); action.setTargetAccountId("target"); action.setAmount(Money.dollars(100)); Bank “Spy” Subclass Of Bank (Spy) 16
  • 17. 6. Test an interface (1/4) to test all possible implementations  Open-Closed Principle (OCP)  software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification  Open for extension: the behavior of the module can be extended  Closed for Modification: The source code of such a module is inviolate 17
  • 18. 6. Test an interface (2/4) How to test all possible Iterator implementations… 18
  • 19. 6. Test an interface (3/4) Close for modification test Iterator IteratorTest <interface> Open for extension abstraction is the key 19
  • 20. 6. Test an interface (4/4) all possible implementations 20
  • 21. 7. Test throwing the right exception (1/3)  to verify that a method throws an expected exception under the appropriate circumstances. 21
  • 22. 7. Test throwing the right exception (2/3) 1. Identify the code that might throw the exception and place it in a try block. 2. After invoking the method that might throw an exception, place a fail() statement 3. Add a catch block for the expected exception. 4. Verify that the exception object’s properties are the ones you expect, if desired. 1 2 3 4 22
  • 23. 7. Test throwing the right exception (3/3) Ilja PreuB approach OCP 1 2 3 4 23
  • 24. 8. Let collections compare themselves (1/3) to verify the contents of a collection  To check for the items you expect, one by one. One by one 24
  • 25. 8. Let collections compare themselves (2/3)  Let the implementation of equals determine whether the collections are equal. 25
  • 26. 8. Let collections compare themselves (3/3) 26
  • 27. 9. Test a big object for equality (1/3) test a Value Object with many key properties  EqualsTester: for test the equals method equal to a not equal to a “looks equal” Money 100, 0 JUnit utility 27
  • 28. 9. Test a big object for equality (2/3)  To test n+3 objects:  two that are equal  n that are different from those two  the last one which is sublcass BigObject Key1, Key2, Key3, Key4,… 4 objects 28
  • 29. 9. Test a big object for equality (3/3) the control object N objects 29
  • 30. 10. Test an object that instantiates other objects (1/5)  You want to test an object in isolation, but it instantiates other objects that make testing difficult or expensive. aggregation test Deployment Deployer 30
  • 31. 10. Test an object that instantiates other objects (2/5)  How do you create an alternate implementation of this object’s collaborator?  How do you pass it in to the object? Deployer test Deployment Deployer’ (Test Object) predictable 31
  • 32. 10. Test an object that instantiates other objects (3/5)  Create a Test Object out of an interface  Implement the interface the simplest way you can  EasyMock (www.easymock.org)  Create a Test Object out of a class  A fake method returns some predictable, meaningful, hard-coded value  A stub method does nothing meaningful—only what is required to compile 32
  • 33. 10. Test an object that instantiates other objects (4/5) refactoring Testable 33
  • 34. 10. Test an object that instantiates other objects (5/5) Mock Test case Test throwing the right exception 34
  • 35. Brief contents  Part 1: The Building Blocks 1. Fundamentals 2. Elementary tests 3. Organizing and building JUnit tests See U next time!! 4. Managing test suites 5. Working with test data 6. Running JUnit tests 7. Reporting JUnit results 8. Troubleshooting JUnit  Part 2: Testing J2EE  Part 3: More JUnit Techniques 35