1
Variable.h
....
#define BLAH = "blahstring"
.....

Hi, How do we mock a variable under #define? Google mock docs talks about mostly methods and objects, but not mocking constants. Closest I can think of delegating call to fake class have it returned test value.

I have header file with list of variables, I want to mock it so that when calling BLAH in test, I get "mockblahstring" instead of "blahstring".

Any example code would help.

thanks.

273K
  • 29,503
  • 10
  • 41
  • 64
Alsina
  • 387
  • 1
  • 2
  • 15
  • 1
    With `#undef` you might change the macro definition - see http://stackoverflow.com/questions/9274500/redefining-or-changing-macro-value. However it might not have effect on already compiled files and files where your change is not visible. And the frank answer to your question is: do not do that - there is no much sense in changing constants when doing unit testing... – PiotrNycz Dec 20 '16 at 13:24

1 Answers1

1

A #define is not a constant.

It is a macro (see here for further reading). The compiler kicks in and replaces all occurrences of that macro long before any gmock library gets "its fingers" on it.

In other words: your compiled object does not contain any BLAH "object". It only contains the corresponding string in all those places where you wrote down BLAH.

In that sense: there is no way in mocking "entities" that simply don't exist any more.

The real answer here: that is one of the many reasons why you absolutely never ever should use preprocessor macros as "constants". Because, they aren't constants! There are still places where they make sense, but definitely not as replacement for constants.

In that sense: you should better step back and learn about such basic essentials before doing anything else.

Community
  • 1
  • 1
GhostCat
  • 137,827
  • 25
  • 176
  • 248