unit testing static objects

Viewed 62

I have classes that are configurable via composition.

For example:

objects.cpp:
dog::config cfg = { .bark = loud; }
static dog my_dog(cfg);

In order to be MISRA compliant (3-4-1), the object dog requires the static storage specifier.

It is easy to unit test the class dog, and I can provide it with whatever configuration I want.

The problem is, in my production project, I want to test my_dog to ensure it was configured correctly, and that the way in which it was configured works as expected. In addition, this will allow dog to interact with other configurable objects such as newspaper, and allow for some higher-level testing.

I am not sure if this is possible without modifying the objects.cpp to include test code, which I don't want to do. If I were to remove static it would be easy, but I can't do that. I also have multiple instances of dog with different configurations, so I don't make the configuration variables reside internally somehow.

Any ideas?

1 Answers

As mentioned in th comments you can create a static access proxy to you object:

static dog *dogProxy::getDog() { 
    static dog my_dog(cfg);
    return &dog;
}
...

dog *uut = dogProxy::getDog();

But this can have a bad effect to your code. People could try to use this vor your production code. So defining a special preprocessor for test code makes sense.

#ifdef UNITTEST
static dog *dogProxy::getDog() { 
    static dog my_dog(cfg);
    return &dog;
}
#endif
   
Related