Elly Fong-Jones | c965059 | 2019-08-12 17:34:16 | [diff] [blame] | 1 | # The ForTesting Methods Pattern |
| 2 | |
| 3 | The ForTesting pattern involves creating public helper methods on a class to |
| 4 | provide access to test-only functionality, and giving them a specific type of |
| 5 | name (`XForTesting` or `XForTest`) to provide a signal at the call site that they |
| 6 | are not intended for regular use. |
| 7 | |
| 8 | ## Use this pattern when: |
| 9 | |
| 10 | You have a widely-used object that you need to expose a small amount of test |
| 11 | functionality on. |
| 12 | |
| 13 | ## Don't use this pattern when: |
| 14 | |
| 15 | * You have lots of different ForTesting methods: consider the [TestApi] pattern |
| 16 | instead. |
| 17 | * Only a small set of test cases need access: consider the [friend the tests] |
| 18 | pattern instead, to avoid polluting the public API. |
| 19 | |
| 20 | ## Alternatives / See also: |
| 21 | |
| 22 | * [Friend the tests] |
| 23 | * [TestApi] |
| 24 | * [ForTesting in the style guide](../../styleguide/c++/c++.md) |
| 25 | |
| 26 | ## How to use this pattern: |
| 27 | |
Jan Wilken Dörrie | d02749a | 2020-10-26 15:51:03 | [diff] [blame] | 28 | ```cpp |
Elly Fong-Jones | c965059 | 2019-08-12 17:34:16 | [diff] [blame] | 29 | class Foo { |
| 30 | public: |
| 31 | // ... regular public API ... |
| 32 | |
| 33 | void DoStuffForTesting(); |
| 34 | }; |
| 35 | ``` |
| 36 | |
| 37 | The ForTesting suffix indicates to code reviewers that the method should not be |
| 38 | called in production code. There is a very similar antipattern in which the |
| 39 | suffix is missing: |
| 40 | |
Jan Wilken Dörrie | d02749a | 2020-10-26 15:51:03 | [diff] [blame] | 41 | ```cpp |
Elly Fong-Jones | c965059 | 2019-08-12 17:34:16 | [diff] [blame] | 42 | class Foo { |
| 43 | public: |
| 44 | // ... regular public API ... |
| 45 | |
| 46 | // Do not call! Only for testing! |
| 47 | void DoStuff(); |
| 48 | }; |
| 49 | ``` |
| 50 | |
| 51 | [testapi]: testapi.md |
| 52 | [friend the tests]: friend-the-tests.md |