简体   繁体   中英

Two abstract classes, deriving from the same base class. How can I access a pointer from one abstract class to the other

I'm writing a helper class for my cppUnit test harness to among other things print test descriptions with spaces. Since various elements are concatenated by the test harness to name the test class, spaces in the test name cause errors. It may sound trivial, but when you are looking through test output of 60 tests which are all, similarly named run on sentences in camel case, spaces are nice.

Since I don't want to touch the harness, I created my helper class so that it derives from the class Test, each individual test is also a class derived from test. I'm pretty bad at polymorphism, so be patient with me. What I am trying to do is access from my helper class, the member getName(), in the unit test class which is a public member inherited from the Test base class.

Here is an excerpt of what I have done so far. It does work, however I want something more clean in the actual calling of this function.

TestHelperClass

class TestHelperClass : public Test
{
  public:
  virtual ~TestHelperClass(){}

  template <typename T>
  static const char* getReadableName(T testClassPtr)
  {
    char * uglyName;
    int ugLen;
    ugLen = strlen(testClassPtr->getName().asCharString());
    uglyName = (char*)malloc(ugLen);
    memcpy(uglyName, testClassPtr->getName().asCharString(), ugLen);
    std::string prettyName;
    // Handle conversion...
    free(uglyName);
    return prettyName.c_str();
  }
};

Unit test

FYI this is a macro taking two arguments a group and a name, and generating a class which inherits the Test class.

TEST(groupNameString, reallyLongTestDescriptionString)
{
  printf("%s\n", TestHelperClass::getReadableName(this));

  // remainder of the unit test.
}

Obviously, I'm far from incomplete. What I want to know is:

  1. Is there a way I can access the pointer to the unit test class without giving function parameters?

  2. Is there any way to not make this a static function?

  3. If the answer is no to one or both of the above, is there a way to use macro's to create a more simple interface for the user, writing the test?

You can make the getReadableName function part of the Test class. Then, your derived class can access it directly.

Test(groupNameString, reallyLongTestDescriptionString)
{
    printf("%s\n", this->getReadableName());

    // remainder of the unit test.
}

You can use the name given in the macro to set a protected variable inside Test class that will be converted in your getReadbleName. You would not need a template, btw.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM