Auto-generating C++ gmock classes

246 views
Skip to first unread message

Clemens Arbesser

unread,
Oct 20, 2022, 1:42:25 PM10/20/22
to Chromium-dev
Hi there!
(Not sure if I'm reaching out to the right group here, please LMK if there's a better recipient. Thanks!)
I'm a chromium dev and wanted to know if there is a utility somewhere that would automatically create mock classes for gmock? According to my quick search, there used to be a python script that does that (gmock_gen.py), but I don't see it in the source checkout, nor any replacement. Maybe I missed it? I expected it in tools/tests, FWIW.

Since it was slowing me down, I took a stab at this myself. What I came up with is basically this:
  1. Copy the file to mock and rename as desired.
  2. Do a regular expression search for:
    • virtual ([^\(]+)(\s[^\s]+)\(([\s\n]*?)\)+\s*(const )*= 0;
  3. Replace all occurrences with:
    • MOCK_METHOD($1, $2, ($3), ($4override));
  4. Run the regular formatter (git cl format).
  5. Optionally, manually clean up the result by removing comments etc.
The regex was sufficiently annoying to write that I wanted to share it in case others find it useful. There's some additional considerations in there to ensure this works in vscode (hence the explicit \n). Obviously, there's still some manual work required (copying and renaming the file/class, formatting, cleaning up), but it's good enough to cover my immediate needs, so I'm stopping here.

This comes with the usual disclaimers of hacky solutions: it works on my machine(TM), and I might be missing edge cases.

I would appreciate if you could let me know whether there's a proper way of doing this. Anyway, just thought you might be interested in the above snippet 😅 LMK if you have any questions! 

Best regards,
~ Clemens
Reply all
Reply to author
Forward
0 new messages