Roughly speaking I have a class that implements a thread with only one public method run. That method goes into a loop, acting like a dispatcher to process network messages one by one; 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
WorkerThread.But how can the private methods be tested elegantly then?
Note:
c++, so I tagged it with the more popular statically typed Java as well to get more attention :PSimply put: Don't. Test against the public interface and nothing else. Ultimately that's the only thing that matters.
If you want to see if it's working correctly, the read/write functions should be accessed via an IoInterface which can be mocked out for testing.
Quoting the question:
I really don't want to extract the private methods out to another class, because semantically they are part of this WorkerThread.
And that is wrong. You are violating the Single Responsibility Principle.
Providing "multi threading support" and "doing actual work" are two different things. You should not enforce that "doing the actual work" is a private implementation detail.
In that sense: the rules that you put up for yourself actually caused you to write hard to test code. So, instead of "working around" the symptoms of a bad design - better step back and fix your design.
In other words:
By doing so, will not only improve your design, you will also make it much easier to test: because now, you can unit test "doing the actual work" without any multi-threading complexity. You simply assert that stuff works when done sequentially. Then you test the multi-thread part - on its own; without worrying about the actual work. And in the end, everything comes together nicely.
Instead of you worrying how to test internal implementation details. Which - you don't; the other answer is fully correct there!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With