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

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. Testyour 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 yourequals 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 yourequals 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 yourequals 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 amethod 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 amethod 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 amethod 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 aconstructor  Uses exposed internal state  Observable side effect  Pitfalls 10
  • 11.
    4. Test agetter (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 agetter (2/3) Which tests are needed and which are not  Compare that result with an expected value 12
  • 13.
    4. Test agetter (3/3) Which tests are needed and which are not An alternative implementation… Too simple to break 13
  • 14.
    5. Test asetter (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 asetter (2/3) Should I test my set methods? If there are no get methods… Command Analyze the side effect 15
  • 16.
    5. Test asetter (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 aninterface (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 aninterface (2/4) How to test all possible Iterator implementations… 18
  • 19.
    6. Test aninterface (3/4) Close for modification test Iterator IteratorTest <interface> Open for extension abstraction is the key 19
  • 20.
    6. Test aninterface (4/4) all possible implementations 20
  • 21.
    7. Test throwingthe right exception (1/3)  to verify that a method throws an expected exception under the appropriate circumstances. 21
  • 22.
    7. Test throwingthe 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 throwingthe right exception (3/3) Ilja PreuB approach OCP 1 2 3 4 23
  • 24.
    8. Let collectionscompare 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 collectionscompare themselves (2/3)  Let the implementation of equals determine whether the collections are equal. 25
  • 26.
    8. Let collectionscompare themselves (3/3) 26
  • 27.
    9. Test abig 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 abig 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 abig object for equality (3/3) the control object N objects 29
  • 30.
    10. Test anobject 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 anobject 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 anobject 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 anobject that instantiates other objects (4/5) refactoring Testable 33
  • 34.
    10. Test anobject 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