vendredi 16 juin 2017

What is a good way to unit test private methods that are not suitable to be extracted as a new class?

Roughly speaking I have a class that implements a thread with only one public method run that goes into a loop, acting like a dispatcher to process network messages one by one. So it's like the following

class WorkerThread {

  public:

    void run() {
      while (!b_shutdown) {
        message = getNextMessage();
        switch(message.type) {
          case WRITE:
            write();
          case READ:
            read();
          // ...
          // more cases to handle
        }
      }
    }


  private:

    void write() { /* logic to test */ }
    void read() { /* logic to test */ }
    // more private methods with logic that needs testing

    // some member variables
};

So the main point is that I really don't want to

  1. Extract the private methods out to another class, because semantically they are part of this WorkerThread.
  2. Make the methods public, because they are not used anywhere outside the class.
  3. Skip the tests, because it is those methods that implements the main logic.

But how can the private methods be tested elegantly then?

Note:

  1. There might have to be a few more public methods to handle the start and termination of the thread, but that is not the concern here.
  2. I think this issue is not restricted to c++, so I tagged it with the more popular statically typed Java as well to get more attention :P

Aucun commentaire:

Enregistrer un commentaire