Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

c++ - Testing through inherited class using protected members

Let us assume that you've got a class in C++, for example with an internal state machine that is hard to test. Assume that you have a proper architecture with mocks for all classes used by the class under test. The class under test has some public interface and some non-public internal implementation.

You want to properly unit test this class. In order to make sure that all parts of it work correctly you would like to create some example conditions that you would not allow through the public interface. However, you want to test whether, under these circumstances, the system reacts correctly or not.

One possibility would be to make your member variables protected, so that an inherited class, specifically created for unit testing, is able to extend the public interface to control those variables during testing. You could then, for example, set the system to a certain state, set some internal variables and make sure that e.g. the state transition is according to your requirements.

From a design point of view: Is it justifiable to make non-public members protected in order to be able to get them more testable? What are your opinions? Are there better alternative design decisions?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I had a similar issue. To be honest , I don't see a point why you should not also test the private part of a class.

My solution to this was using the pre-compiler only for the private statement.

#ifndef UNITTEST
private:
#endif // UNITTEST

Of course we could argue now, that I am manipulating the original class itself and I am not any longer testing properly in real conditions , but if you are testing one class and not several within this one unit test I see no issue.

This question about the protected is a bit like the question about making methods virtual for the sake of mocking. You have to decide case by case.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...