Lecture Notes for Extreme Programming

28 June 2001 - Unit Testing Example


  1. demonstrate a unit test, show an example of refactoring

  2. here's an (incomplete) object

    class shared_managed_population {
    
      public:
    
        pair interval_to_process(void) {
          const int slice = disclosures.size() / thread_count
          const int start = (slice*thread_number - 1) + 1
          const int end = max(start + slice, disclosures.size())
          return make_pair(start, end);
          }
    
      private:
    
        vector disclosures;
        int thread_number;
        int thread_count;
      };
    
    

  3. what does it do

    1. divide a set of jobs (disclosures) into equal-sized pieces

    2. assign one of the pieces to a thread

    3. return the starting and ending indices of the assigned piece

  4. why is this hard to test

    1. each test requires its own instance of the shared_managed_population object

    2. the values of the member variables have to be set up for each instance

  5. here's a refactoring of the object

    class shared_managed_population {
    
      public:
    
        pair interval_to_process(void) {
          return interval_for_thread(
            thread_number, thread_count, disclosures.size());
          }
    
      private:
    
        pair interval_for_thread(
          int thread_no, int thread_cnt, int collection_size) {
    
          const int slice = collection_size / thread_cnt
          const int start = (slice*thread_no - 1) + 1
          const int end = max(start + slice, collection_size)
          return make_pair(start, end);
          }
    
        vector disclosures;
        int thread_number;
        int thread_count;
      };
    
    

  6. why is the refactored object easier to test

    1. interval_to_process doesn't do anything - nothing to test

    2. interval_for_thread works through parameters - easy to test

    3. testing requires one object instance, changing tests is easy

  7. what is the refactoring

    1. rewrite code to avoid global variables

    2. member variables are globals within the class


This page last modified on 2 July 2001.