Testing C++ classes

C++ classes have some specifics, which require use of persistent variables, and a bit different test case organization.

Creating an object

To test a class, we must first instantiate it to get an object. Class instantiation in C++ is made basically in two steps: Note: It is not enough to initialize class members manually by assigning values to each of them, because constructor might set also some other items, for example vtable. In testIDEA the two actions are made by: We use a persistent variable to make the object available for the following tests, which can use the variable to get pointer to the object (this).

Testing methods

To test a method of an object, we call it like any other function, but pass pointer to object (this) as first parameter.

Example

Suppose we have a class declared as:
      class Vehicle
      {
      private:
          int m_num_wheels;
          int m_weight;

      public:
          Vehicle(int num_wheels, int weight);
  
          int get_num_wheels();
          void set_weight(int w);
      };
    
First we create a test case, which creates an object. Allocation is done by persitent variable:

 

Then we call constructor in the same test case:

 

The object is created now and it exists as a persistent variable per_v. If we'd like to test values of attributes, we could add expressions in the Expected section.

Now let's test method get_num_wheels(). Note that we specified this parameter as address of persistent variable per_v:

 

Verify the result:

 

It is a good practice to make test case, which declares persistent variable and calls constructor a base test case, and test cases which implement tests on the created object as derived test cases. Of course the last test case which uses the object should also delete the persistent variable. The complete tests cases shown above in YAML, which you can paste to testIDEA:

      persistVars:
        decl:
          per_v: Vehicle
      func:
      - Vehicle::Vehicle
      - - '&per_v'
        - 4
        - 1500
      tests:
      - imports:
          persistVars:
            inherit: false
        persistVars:
          delete:
          - per_v
        func:
        - Vehicle::get_num_wheels
        - - '&per_v'
        - rv
        assert:
          expressions:
          - rv == 4