mardi 8 octobre 2019

C++ testing private callback methods

I have a class, which registers private methods of itself with other classes to be used as callbacks. This utilises std::bind to create an std::function that points to the private method.

Example: (names are not actual class names)

class DataProcessor {
private:
    void callback() {
        // Do something
    };
public:
    DataProcessor(IDataSupplier supplier) {
        supplier.subscribe(std::bind(&DataProcessor::callback, this));
    };
};

Now I want to verify that the callback function performs the correct actions. I use gtest for my tests, and create a mock of IDataSupplier with gmock to create this object with.

I can't call DataProcessor::callback() directly, since it is private when viewed from the test. I would prefer not to change DataProcessor for my test.

Normally, the callback is accessible because IDataSupplier has access to the std::function object that wraps the private method. Because I have a mocked version of IDataSupplier, I don't think I'm able to capture the callback that was given to it (and again, it feels wrong to have to rely on this; what if gmock stops allowing me to get the provided std::function?)

So my questions boil down to these two:

  1. Am I doing A Bad Thing (tm) by trying to test a private callback method?
  2. How should I approach testing this callback, if I should do it at all?

Aucun commentaire:

Enregistrer un commentaire