Full disclosure, my c++ is very old / rusty, so I'm sure this is a simple question, and a matter of my ignorance, but hopefully this question is quickly answered by someone with more c++-fu than I
I have my own MockNamedValueComparator declared in my test file...e.g.
class MyComparator : public MockNamedValueComparator
{
private:
int len;
public:
MyComparator(int len) {
this.len = len;
}
// etc.
}
and then in my setup() I want to reset it each time - this is b/c the int length is passed into the constructor and I use that in my isEqual implementation. For most of the test cases, the length variable is the same, but for some I need to set it explicitly...so I tried
So I tried this:
TEST_GROUP(MyGroup)
{
MyComparator comparator = NULL;
void setup()
{
// usually the length is 3, so each test case can assume that
MyComparator comparator = MyComparator(3);
}
void teardown()
{
mock().checkExpectations();
mock().removeAllComparators();
mock().clear();
}
}
TEST(MyGroup, Test1)
{
// implicitly use MyComparator with length 3
mock().installComparator("MyComparator", comparator);
}
TEST(MyGroup, Test2)
{
// explicitly set my own with different length
comparator = MyComparator(10);
mock().installComparator("MyComparator", comparator);
}
On Mac OS with clang, this works ok, but I get the warning:
warning: in-class initialization of non-static data member is a C++11 extension [-Wc++11-extensions]
..and the tests work ok.
On Linux, it won't compile.
error: ISO C++ forbids initialization of member ‘comparator’ [-fpermissive]
error: making ‘comparator’ static [-fpermissive]
error: invalid in-class initialization of static data member of non-integral type ‘MyComparator’
It looks like I can fix it by adding -fpermissive flag, but I'd prefer to fix it in the code, if possible.
I tried a few different things, like moving the declaration out of TEST_GROUP itself, e.g.
MyComparator comparator;
TEST_GROUP(MyGroup) { void setup() { comparator = MyComparator(3); } }
But then my tests start failing, as if the comparator isn't working.
If I explicitly call the constructor in each TEST macro, it works
TEST(FooTest)
{
comparator = MyComparator(3);
mock().installComparator(...)
}
I was simply trying to reduce the lines of code necessary for my tests, but I'm missing something here with respect to c++ / cpputest macros / scope, etc. I come from java / c background, so my viewpoint is skewed in that respect.
TL;DR: I want to make a per-test global scope variable and re-initialize on each test setup() call -- what am I doing wrong?