V
V
Vi Vola2018-03-10 19:34:35
Qt
Vi Vola, 2018-03-10 19:34:35

TDD, how to test private methods?

How to test private methods while keeping them private?
There was an idea to create a successor class and re-declare methods public there and use them in tests, but as far as I understand this does not work.

class A {
public:
    A() {}
    void setPublic() { cout << "A: setPublic" << endl; }    
protected:
    virtual void setProtected() { cout << "A: setProtected" << endl; }
private:
};

class B: public A {
public:
    B() : A() {}
    void setProtected() override;
};

int main() {
    B b;
    b.setPublic();
    b.setProtected(); // ошибка
    return 0;
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vitaly, 2018-03-11
@hakain

Here the question arises, why do you directly test class methods that are not accessible from the public interface? When you write unit tests for a class, the private methods will be tested through the public ones. If not, then they can be deleted, because. the class doesn't use them :)
As a last resort, the test class can be made a friend of the class whose private methods you are going to test. I just don't understand why.

I
Ighor July, 2018-03-10
@IGHOR

In class A or B, create a temporary public method in which to call the private one.

K
Kamil Khamitov, 2018-03-18
@Kobalt_x

In B void setProtected() override { A::setProtected(); }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question