lundi 27 juin 2016

c++ where to put constant variables private to cc file if I need them for testing

My header file looks like this:

// method.h
class Class {
    public:
        string Method(const int number);
};

My cc file looks like this

// method.cc
#include "method.h"

namespace {
    const char kImportantString[] = "Very long and important string";
}

string Class::Method(const int number) {
    [... computation which depends on kImportantString ...] 
    return some_string;
}

Now for some inputs the Method() should return kImportantString, but for other inputs it must not return kImportantString

Therefore, I would like to create a test file, which would look like this:

// method_test.cc
#include "method.h"

void Test() {
    assert(Method(1) == kImportantString);  // kImportantString is not visible
    assert(Method(2) != kImportantString);  // in this file, how to fix this?
}

But currently the problem is that kImportantString is not within the scope of method_test.cc file.

  • Adding kImportantString to method.h is not ideal, as it is not needed inside the header file.
  • Creating a separate file "utils.h" and putting just one string there seems like an overkill (although might be the best option).
  • Copying kImportantString into a test file is not ideal, because the string is quite long, and later someone might accidentally change it in one file, but not the other.

Hence, my question is:

What's the best way to make kImportantString be visible in the test file, and be invisible in as many other places as possible?

Aucun commentaire:

Enregistrer un commentaire