You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

831 lines
33 KiB

11 months ago
  1. CMock: A Summary
  2. ================
  3. *[ThrowTheSwitch.org](http://throwtheswitch.org)*
  4. *This documentation is released under a Creative Commons 3.0 Attribution Share-Alike License*
  5. What Exactly Are We Talking About Here?
  6. ---------------------------------------
  7. CMock is a nice little tool which takes your header files and creates
  8. a Mock interface for it so that you can more easily unit test modules
  9. that touch other modules. For each function prototype in your
  10. header, like this one:
  11. int DoesSomething(int a, int b);
  12. ...you get an automatically generated DoesSomething function
  13. that you can link to instead of your real DoesSomething function.
  14. By using this Mocked version, you can then verify that it receives
  15. the data you want, and make it return whatever data you desire,
  16. make it throw errors when you want, and more... Create these for
  17. everything your latest real module touches, and you're suddenly
  18. in a position of power: You can control and verify every detail
  19. of your latest creation.
  20. To make that easier, CMock also gives you a bunch of functions
  21. like the ones below, so you can tell that generated DoesSomething
  22. function how to behave for each test:
  23. void DoesSomething_ExpectAndReturn(int a, int b, int toReturn);
  24. void DoesSomething_ExpectAndThrow(int a, int b, EXCEPTION_T error);
  25. void DoesSomething_StubWithCallback(CMOCK_DoesSomething_CALLBACK YourCallback);
  26. void DoesSomething_IgnoreAndReturn(int toReturn);
  27. You can pile a bunch of these back to back, and it remembers what
  28. you wanted to pass when, like so:
  29. test_CallsDoesSomething_ShouldDoJustThat(void)
  30. {
  31. DoesSomething_ExpectAndReturn(1,2,3);
  32. DoesSomething_ExpectAndReturn(4,5,6);
  33. DoesSomething_ExpectAndThrow(7,8, STATUS_ERROR_OOPS);
  34. CallsDoesSomething( );
  35. }
  36. This test will call CallsDoesSomething, which is the function
  37. we are testing. We are expecting that function to call DoesSomething
  38. three times. The first time, we check to make sure it's called
  39. as DoesSomething(1, 2) and we'll magically return a 3. The second
  40. time we check for DoesSomething(4, 5) and we'll return a 6. The
  41. third time we verify DoesSomething(7, 8) and we'll throw an error
  42. instead of returning anything. If CallsDoesSomething gets
  43. any of this wrong, it fails the test. It will fail if you didn't
  44. call DoesSomething enough, or too much, or with the wrong arguments,
  45. or in the wrong order.
  46. CMock is based on Unity, which it uses for all internal testing.
  47. It uses Ruby to do all the main work (versions 2.0.0 and above).
  48. Installing
  49. ==========
  50. The first thing you need to do to install CMock is to get yourself
  51. a copy of Ruby. If you're on linux or osx, you probably already
  52. have it. You can prove it by typing the following:
  53. ruby --version
  54. If it replied in a way that implies ignorance, then you're going to
  55. need to install it. You can go to [ruby-lang](https://ruby-lang.org)
  56. to get the latest version. You're also going to need to do that if it
  57. replied with a version that is older than 2.0.0. Go ahead. We'll wait.
  58. Once you have Ruby, you have three options:
  59. * Clone the latest [CMock repo on github](https://github.com/ThrowTheSwitch/CMock/)
  60. * Download the latest [CMock zip from github](https://github.com/ThrowTheSwitch/CMock/)
  61. * Install Ceedling (which has it built in!) through your commandline using `gem install ceedling`.
  62. Generated Mock Module Summary
  63. =============================
  64. In addition to the mocks themselves, CMock will generate the
  65. following functions for use in your tests. The expect functions
  66. are always generated. The other functions are only generated
  67. if those plugins are enabled:
  68. Expect:
  69. -------
  70. Your basic staple Expects which will be used for most of your day
  71. to day CMock work. By calling this, you are telling CMock that you
  72. expect that function to be called during your test. It also specifies
  73. which arguments you expect it to be called with, and what return
  74. value you want returned when that happens. You can call this function
  75. multiple times back to back in order to queue up multiple calls.
  76. * `void func(void)` => `void func_Expect(void)`
  77. * `void func(params)` => `void func_Expect(expected_params)`
  78. * `retval func(void)` => `void func_ExpectAndReturn(retval_to_return)`
  79. * `retval func(params)` => `void func_ExpectAndReturn(expected_params, retval_to_return)`
  80. ExpectAnyArgs:
  81. --------------
  82. This behaves just like the Expects calls, except that it doesn't really
  83. care what the arguments are that the mock gets called with. It still counts
  84. the number of times the mock is called and it still handles return values
  85. if there are some. Note that an ExpectAnyArgs call is not generated for
  86. functions that have no arguments, because it would act exactly like the existing
  87. Expect and ExpectAndReturn calls.
  88. * `void func(params)` => `void func_ExpectAnyArgs(void)`
  89. * `retval func(params)` => `void func_ExpectAnyArgsAndReturn(retval_to_return)`
  90. Array:
  91. ------
  92. An ExpectWithArray is another variant of Expect. Like expect, it cares about
  93. the number of times a mock is called, the arguments it is called with, and the
  94. values it is to return. This variant has another feature, though. For anything
  95. that resembles a pointer or array, it breaks the argument into TWO arguments.
  96. The first is the original pointer. The second specify the number of elements
  97. it is to verify of that array. If you specify 1, it'll check one object. If 2,
  98. it'll assume your pointer is pointing at the first of two elements in an array.
  99. If you specify zero elements, it will check just the pointer if
  100. `:smart` mode is configured or fail if `:compare_data` is set.
  101. * `void func(void)` => (nothing. In fact, an additional function is only generated if the params list contains pointers)
  102. * `void func(ptr * param, other)` => `void func_ExpectWithArray(ptr* param, int param_depth, other)`
  103. * `retval func(void)` => (nothing. In fact, an additional function is only generated if the params list contains pointers)
  104. * `retval func(other, ptr* param)` => `void func_ExpectWithArrayAndReturn(other, ptr* param, int param_depth, retval_to_return)`
  105. Ignore:
  106. -------
  107. Maybe you don't care about the number of times a particular function is called or
  108. the actual arguments it is called with. In that case, you want to use Ignore. Ignore
  109. only needs to be called once per test. It will then ignore any further calls to that
  110. particular mock. The IgnoreAndReturn works similarly, except that it has the added
  111. benefit of knowing what to return when that call happens. If the mock is called more
  112. times than IgnoreAndReturn was called, it will keep returning the last value without
  113. complaint. If it's called fewer times, it will also ignore that. You SAID you didn't
  114. care how many times it was called, right?
  115. * `void func(void)` => `void func_Ignore(void)`
  116. * `void func(params)` => `void func_Ignore(void)`
  117. * `retval func(void)` => `void func_IgnoreAndReturn(retval_to_return)`
  118. * `retval func(params)` => `void func_IgnoreAndReturn(retval_to_return)`
  119. StopIgnore:
  120. -------
  121. Maybe you want to ignore a particular function for part of a test but dont want to
  122. ignore it later on. In that case, you want to use StopIgnore which will cancel the
  123. previously called Ignore or IgnoreAndReturn requiring you to Expect or otherwise
  124. handle the call to a function.
  125. * `void func(void)` => `void func_StopIgnore(void)`
  126. * `void func(params)` => `void func_StopIgnore(void)`
  127. * `retval func(void)` => `void func_StopIgnore(void)`
  128. * `retval func(params)` => `void func_StopIgnore(void)`
  129. IgnoreStateless:
  130. ----------------
  131. This plugin is similar to the Ignore plugin, but the IgnoreAndReturn functions are
  132. stateless. So the Ignored function will always return the last specified return value
  133. and does not queue the return values as the IgnoreAndReturn of the default plugin will.
  134. To stop ignoring a function you can call StopIgnore or simply overwrite the Ignore
  135. (resp. IgnoreAndReturn) with an Expect (resp. ExpectAndReturn). Note that calling
  136. Ignore (resp IgnoreAndReturn) will clear your previous called Expect
  137. (resp. ExpectAndReturn), so they are not restored after StopIgnore is called.
  138. You can use this plugin by using `:ignore_stateless` instead of `:ignore` in your
  139. CMock configuration file.
  140. The generated functions are the same as **Ignore** and **StopIgnore** above.
  141. Ignore Arg:
  142. ------------
  143. Maybe you overall want to use Expect and its similar variations, but you don't care
  144. what is passed to a particular argument. This is particularly useful when that argument
  145. is a pointer to a value that is supposed to be filled in by the function. You don't want
  146. to use ExpectAnyArgs, because you still care about the other arguments. Instead, after
  147. an Expect call is made, you can call this function. It tells CMock to ignore
  148. a particular argument for the rest of this test, for this mock function. You may call
  149. multiple instances of this to ignore multiple arguments after each expectation if
  150. desired.
  151. * `void func(params)` => `void func_IgnoreArg_paramName(void)`
  152. ReturnThruPtr:
  153. --------------
  154. Another option which operates on a particular argument of a function is the ReturnThruPtr
  155. plugin. For every argument that resembles a pointer or reference, CMock generates an
  156. instance of this function. Just as the AndReturn functions support injecting one or more
  157. return values into a queue, this function lets you specify one or more return values which
  158. are queued up and copied into the space being pointed at each time the mock is called.
  159. * `void func(param1)` => `void func_ReturnThruPtr_paramName(val_to_return)`
  160. * => `void func_ReturnArrayThruPtr_paramName(cal_to_return, len)`
  161. * => `void func_ReturnMemThruPtr_paramName(val_to_return, size)`
  162. Callback:
  163. ---------
  164. If all those other options don't work, and you really need to do something custom, you
  165. still have a choice. As soon as you stub a callback in a test, it will call the callback
  166. whenever the mock is encountered and return the retval returned from the callback (if any).
  167. * `void func(void)` => `void func_[AddCallback,Stub](CMOCK_func_CALLBACK callback)`
  168. where `CMOCK_func_CALLBACK` looks like: `void func(int NumCalls)`
  169. * `void func(params)` => `void func_[AddCallback,Stub](CMOCK_func_CALLBACK callback)`
  170. where `CMOCK_func_CALLBACK` looks like: `void func(params, int NumCalls)`
  171. * `retval func(void)` => `void func_[AddCallback,Stub](CMOCK_func_CALLBACK callback)`
  172. where `CMOCK_func_CALLBACK` looks like: `retval func(int NumCalls)`
  173. * `retval func(params)` => `void func_[AddCallback,Stub](CMOCK_func_CALLBACK callback)`
  174. where `CMOCK_func_CALLBACK` looks like: `retval func(params, int NumCalls)`
  175. You can choose from two options:
  176. * `func_AddCallback` tells the mock to check its arguments and calling
  177. order (based on any Expects you've set up) before calling the callback.
  178. * `func_Stub` tells the mock to skip all the normal checks and jump directly
  179. to the callback instead. In this case, you are replacing the normal mock calls
  180. with your own custom stub function.
  181. There is also an older name, `func_StubWithCallback`, which is just an alias
  182. for either `func_AddCallback` or `func_Stub` depending on setting of the
  183. `:callback_after_arg_check` toggle. This is deprecated and we recommend using
  184. the two options above.
  185. Cexception:
  186. -----------
  187. Finally, if you are using Cexception for error handling, you can use this to throw errors
  188. from inside mocks. Like Expects, it remembers which call was supposed to throw the error,
  189. and it still checks parameters first.
  190. * `void func(void)` => `void func_ExpectAndThrow(value_to_throw)`
  191. * `void func(params)` => `void func_ExpectAndThrow(expected_params, value_to_throw)`
  192. * `retval func(void)` => `void func_ExpectAndThrow(value_to_throw)`
  193. * `retval func(params)` => `void func_ExpectAndThrow(expected_params, value_to_throw)`
  194. Running CMock
  195. =============
  196. CMock is a Ruby script and class. You can therefore use it directly
  197. from the command line, or include it in your own scripts or rakefiles.
  198. Mocking from the Command Line
  199. -----------------------------
  200. After unpacking CMock, you will find cmock.rb in the 'lib' directory.
  201. This is the file that you want to run. It takes a list of header files
  202. to be mocked, as well as an optional yaml file for a more detailed
  203. configuration (see config options below).
  204. For example, this will create three mocks using the configuration
  205. specified in MyConfig.yml:
  206. ruby cmock.rb -oMyConfig.yml super.h duper.h awesome.h
  207. And this will create two mocks using the default configuration:
  208. ruby cmock.rb ../mocking/stuff/is/fun.h ../try/it/yourself.h
  209. Mocking From Scripts or Rake
  210. ----------------------------
  211. CMock can be used directly from your own scripts or from a rakefile.
  212. Start by including cmock.rb, then create an instance of CMock.
  213. When you create your instance, you may initialize it in one of
  214. three ways.
  215. You may specify nothing, allowing it to run with default settings:
  216. require 'cmock.rb'
  217. cmock = CMock.new
  218. You may specify a YAML file containing the configuration options
  219. you desire:
  220. cmock = CMock.new('../MyConfig.yml')
  221. You may specify the options explicitly:
  222. cmock = Cmock.new(:plugins => [:cexception, :ignore], :mock_path => 'my/mocks/')
  223. Creating Skeletons:
  224. -------------------
  225. Not only is CMock able to generate mock files from a header file, but it is also able
  226. to generate (and update) skeleton C files from headers. It does this by creating a
  227. (mostly) empty implementation for every function that is declared in the header. If you later
  228. add to that header list, just run this feature again and it will add prototypes for the missing
  229. functions!
  230. Like the normal usecase for CMock, this feature can be used from the command line
  231. or from within its ruby API. For example, from the command line, add `--skeleton` to
  232. generate a skeleton instead:
  233. ```
  234. ruby cmock.rb --skeleton ../create/c/for/this.h
  235. ```
  236. Config Options:
  237. ---------------
  238. The following configuration options can be specified in the
  239. yaml file or directly when instantiating.
  240. Passed as Ruby, they look like this:
  241. { :attributes => [“__funky”, “__intrinsic”], :when_ptr => :compare }
  242. Defined in the yaml file, they look more like this:
  243. :cmock:
  244. :attributes:
  245. - __funky
  246. - __intrinsic
  247. :when_ptr: :compare
  248. In all cases, you can just include the things that you want to override
  249. from the defaults. We've tried to specify what the defaults are below.
  250. * `:attributes`:
  251. These are attributes that CMock should ignore for you for testing
  252. purposes. Custom compiler extensions and externs are handy things to
  253. put here. If your compiler is choking on some extended syntax, this
  254. is often a good place to look.
  255. * defaults: ['__ramfunc', '__irq', '__fiq', 'register', 'extern']
  256. * **note:** this option will reinsert these attributes onto the mock's calls.
  257. If that isn't what you are looking for, check out :strippables.
  258. * `:c_calling_conventions`:
  259. Similarly, CMock may need to understand which C calling conventions
  260. might show up in your codebase. If it encounters something it doesn't
  261. recognize, it's not going to mock it. We have the most common covered,
  262. but there are many compilers out there, and therefore many other options.
  263. * defaults: ['__stdcall', '__cdecl', '__fastcall']
  264. * **note:** this option will reinsert these attributes onto the mock's calls.
  265. If that isn't what you are looking for, check out :strippables.
  266. * `:callback_after_arg_check`:
  267. Tell `:callback` plugin to do the normal argument checking **before** it
  268. calls the callback function by setting this to true. When false, the
  269. callback function is called **instead** of the argument verification.
  270. * default: false
  271. * `:callback_include_count`:
  272. Tell `:callback` plugin to include an extra parameter to specify the
  273. number of times the callback has been called. If set to false, the
  274. callback has the same interface as the mocked function. This can be
  275. handy when you're wanting to use callback as a stub.
  276. * default: true
  277. * `:cexception_include`:
  278. Tell `:cexception` plugin where to find CException.h... You only need to
  279. define this if it's not in your build path already... which it usually
  280. will be for the purpose of your builds.
  281. * default: *nil*
  282. * `:enforce_strict_ordering`:
  283. CMock always enforces the order that you call a particular function,
  284. so if you expect GrabNabber(int size) to be called three times, it
  285. will verify that the sizes are in the order you specified. You might
  286. *also* want to make sure that all different functions are called in a
  287. particular order. If so, set this to true.
  288. * default: false
  289. * `:framework`:
  290. Currently the only option is `:unity.` Eventually if we support other
  291. unity test frameworks (or if you write one for us), they'll get added
  292. here.
  293. : default: :unity
  294. * `:includes`:
  295. An array of additional include files which should be added to the
  296. mocks. Useful for global types and definitions used in your project.
  297. There are more specific versions if you care WHERE in the mock files
  298. the includes get placed. You can define any or all of these options.
  299. * `:includes`
  300. * `:includes_h_pre_orig_header`
  301. * `:includes_h_post_orig_header`
  302. * `:includes_c_pre_header`
  303. * `:includes_c_post_header`
  304. * default: nil #for all 5 options
  305. * `:memcmp_if_unknown`:
  306. C developers create a lot of types, either through typedef or preprocessor
  307. macros. CMock isn't going to automatically know what you were thinking all
  308. the time (though it tries its best). If it comes across a type it doesn't
  309. recognize, you have a choice on how you want it to handle it. It can either
  310. perform a raw memory comparison and report any differences, or it can fail
  311. with a meaningful message. Either way, this feature will only happen after
  312. all other mechanisms have failed (The thing encountered isn't a standard
  313. type. It isn't in the :treat_as list. It isn't in a custom unity_helper).
  314. * default: true
  315. * `:mock_path`:
  316. The directory where you would like the mock files generated to be
  317. placed.
  318. * default: mocks
  319. * `:mock_prefix`:
  320. The prefix to prepend to your mock files. For example, if it's `Mock`, a file
  321. “USART.h” will get a mock called “MockUSART.c”. This CAN be used with a suffix
  322. at the same time.
  323. * default: Mock
  324. * `:mock_suffix`:
  325. The suffix to append to your mock files. For example, it it's `_Mock`, a file
  326. "USART.h" will get a mock called "USART_Mock.h". This CAN be used with a prefix
  327. at the same time.
  328. * default: ""
  329. * `:plugins`:
  330. An array of which plugins to enable. ':expect' is always active. Also
  331. available currently:
  332. * `:ignore`
  333. * `:ignore_stateless`
  334. * `:ignore_arg`
  335. * `:expect_any_args`
  336. * `:array`
  337. * `:cexception`
  338. * `:callback`
  339. * `:return_thru_ptr`
  340. * `:strippables`:
  341. An array containing a list of items to remove from the header
  342. before deciding what should be mocked. This can be something simple
  343. like a compiler extension CMock wouldn't recognize, or could be a
  344. regex to reject certain function name patterns. This is a great way to
  345. get rid of compiler extensions when your test compiler doesn't support
  346. them. For example, use `:strippables: ['(?:functionName\s*\(+.*?\)+)']`
  347. to prevent a function `functionName` from being mocked. By default, it
  348. is ignoring all gcc attribute extensions.
  349. * default: `['(?:__attribute__\s*\(+.*?\)+)']`
  350. * `:exclude_setjmp_h`:
  351. Some embedded systems don't have <setjmp.h> available. Setting this to true
  352. removes references to this header file and the ability to use cexception.
  353. * default: false
  354. * `:subdir`:
  355. This is a relative subdirectory for your mocks. Set this to e.g. "sys" in
  356. order to create a mock for `sys/types.h` in `(:mock_path)/sys/`.
  357. * default: ""
  358. * `:treat_as`:
  359. The `:treat_as` list is a shortcut for when you have created typedefs
  360. of standard types. Why create a custom unity helper for UINT16 when
  361. the unity function TEST_ASSERT_EQUAL_HEX16 will work just perfectly?
  362. Just add 'UINT16' => 'HEX16' to your list (actually, don't. We already
  363. did that one for you). Maybe you have a type that is a pointer to an
  364. array of unsigned characters? No problem, just add 'UINT8_T*' =>
  365. 'HEX8*'
  366. * NOTE: unlike the other options, your specifications MERGE with the
  367. default list. Therefore, if you want to override something, you must
  368. reassign it to something else (or to *nil* if you don't want it)
  369. * default:
  370. * 'int': 'INT'
  371. * 'char': 'INT8'
  372. * 'short': 'INT16'
  373. * 'long': 'INT'
  374. * 'int8': 'INT8'
  375. * 'int16': 'INT16'
  376. * 'int32': 'INT'
  377. * 'int8_t': 'INT8'
  378. * 'int16_t': 'INT16'
  379. * 'int32_t': 'INT'
  380. * 'INT8_T': 'INT8'
  381. * 'INT16_T': 'INT16'
  382. * 'INT32_T': 'INT'
  383. * 'bool': 'INT'
  384. * 'bool_t': 'INT'
  385. * 'BOOL': 'INT'
  386. * 'BOOL_T': 'INT'
  387. * 'unsigned int': 'HEX32'
  388. * 'unsigned long': 'HEX32'
  389. * 'uint32': 'HEX32'
  390. * 'uint32_t': 'HEX32'
  391. * 'UINT32': 'HEX32'
  392. * 'UINT32_T': 'HEX32'
  393. * 'void*': 'HEX8_ARRAY'
  394. * 'unsigned short': 'HEX16'
  395. * 'uint16': 'HEX16'
  396. * 'uint16_t': 'HEX16'
  397. * 'UINT16': 'HEX16'
  398. * 'UINT16_T': 'HEX16'
  399. * 'unsigned char': 'HEX8'
  400. * 'uint8': 'HEX8'
  401. * 'uint8_t': 'HEX8'
  402. * 'UINT8': 'HEX8'
  403. * 'UINT8_T': 'HEX8'
  404. * 'char*': 'STRING'
  405. * 'pCHAR': 'STRING'
  406. * 'cstring': 'STRING'
  407. * 'CSTRING': 'STRING'
  408. * 'float': 'FLOAT'
  409. * 'double': 'FLOAT'
  410. * `:treat_as_array`:
  411. A specialized sort of `:treat_as` to be used when you've created a
  412. typedef of an array type, such as `typedef int TenIntegers[10];`. This
  413. is a hash of typedef name to element type. For example:
  414. { "TenIntegers" => "int",
  415. "ArrayOfFloat" => "float" }
  416. Telling CMock about these typedefs allows it to be more intelligent
  417. about parameters of such types, so that you can use features like
  418. ExpectWithArray and ReturnArrayThruPtr with them.
  419. * `:treat_as_void`:
  420. We've seen "fun" legacy systems typedef 'void' with a custom type,
  421. like MY_VOID. Add any instances of those to this list to help CMock
  422. understand how to deal with your code.
  423. * default: []
  424. * `:treat_externs`:
  425. This specifies how you want CMock to handle functions that have been
  426. marked as extern in the header file. Should it mock them?
  427. * `:include` will mock externed functions
  428. * `:exclude` will ignore externed functions (default).
  429. * `:treat_inlines`:
  430. This specifies how you want CMock to handle functions that have been
  431. marked as inline in the header file. Should it mock them?
  432. * `:include` will mock inlined functions
  433. * `:exclude` will ignore inlined functions (default).
  434. CMock will look for the following default patterns (simplified from the actual regex):
  435. - "static inline"
  436. - "inline static"
  437. - "inline"
  438. - "static"
  439. You can override these patterns, check out :inline_function_patterns.
  440. Enabling this feature does require a change in the build system that
  441. is using CMock. To understand why, we need to give some more info
  442. on how we are handling inline functions internally.
  443. Let's say we want to mock a header called example.h. example.h
  444. contains inline functions, we cannot include this header in the
  445. mocks or test code if we want to mock the inline functions simply
  446. because the inline functions contain an implementation that we want
  447. to override in our mocks!
  448. So, to circumvent this, we generate a new header, also named
  449. example.h, in the same directory as mock_example.h/c . This newly
  450. generated header should/is exactly the same as the original header,
  451. only difference is the inline functions are transformed to 'normal'
  452. functions declarations. Placing the new header in the same
  453. directory as mock_example.h/c ensures that they will include the new
  454. header and not the old one.
  455. However, CMock has no control in how the build system is configured
  456. and which include paths the test code is compiled with. In order
  457. for the test code to also see the newly generated header ,and not
  458. the old header with inline functions, the build system has to add
  459. the mock folder to the include paths.
  460. Furthermore, we need to keep the order of include paths in mind. We
  461. have to set the mock folder before the other includes to avoid the
  462. test code including the original header instead of the newly
  463. generated header (without inline functions).
  464. * `:unity_helper_path`:
  465. If you have created a header with your own extensions to unity to
  466. handle your own types, you can set this argument to that path. CMock
  467. will then automagically pull in your helpers and use them. The only
  468. trick is that you make sure you follow the naming convention:
  469. `UNITY_TEST_ASSERT_EQUAL_YourType`. If it finds macros of the right
  470. shape that match that pattern, it'll use them.
  471. * default: []
  472. * `:verbosity`:
  473. How loud should CMock be?
  474. * 0 for errors only
  475. * 1 for errors and warnings
  476. * 2 for normal (default)
  477. * 3 for verbose
  478. * `:weak`:
  479. When set this to some value, the generated mocks are defined as weak
  480. symbols using the configured format. This allows them to be overridden
  481. in particular tests.
  482. * Set to '__attribute ((weak))' for weak mocks when using GCC.
  483. * Set to any non-empty string for weak mocks when using IAR.
  484. * default: ""
  485. * `:when_no_prototypes`:
  486. When you give CMock a header file and ask it to create a mock out of
  487. it, it usually contains function prototypes (otherwise what was the
  488. point?). You can control what happens when this isn't true. You can
  489. set this to `:warn,` `:ignore,` or `:error`
  490. * default: :warn
  491. * `:when_ptr`:
  492. You can customize how CMock deals with pointers (c strings result in
  493. string comparisons... we're talking about **other** pointers here). Your
  494. options are `:compare_ptr` to just verify the pointers are the same,
  495. `:compare_data` or `:smart` to verify that the data is the same.
  496. `:compare_data` and `:smart` behaviors will change slightly based on
  497. if you have the array plugin enabled. By default, they compare a
  498. single element of what is being pointed to. So if you have a pointer
  499. to a struct called ORGAN_T, it will compare one ORGAN_T (whatever that
  500. is).
  501. * default: :smart
  502. * `:array_size_type`:
  503. * `:array_size_name`:
  504. When the `:array` plugin is disabled, these options do nothing.
  505. When the `:array` plugin is enabled, these options allow CMock to recognize
  506. functions with parameters that might refer to an array, like the following,
  507. and treat them more intelligently:
  508. * `void GoBananas(Banana * bananas, int num_bananas)`
  509. * `int write_data(int fd, const uint8_t * data, uint32_t size)`
  510. To recognize functions like these, CMock looks for a parameter list
  511. containing a pointer (which could be an array) followed by something that
  512. could be an array size. "Something", by default, means an `int` or `size_t`
  513. parameter with a name containing "size" or "len".
  514. `:array_size_type` is a list of additional types (besides `int` and `size_t`)
  515. that could be used for an array size parameter. For example, to get CMock to
  516. recognize that `uint32_t size` is an array size, you'd need to say:
  517. cfg[:array_size_type] = ['uint32_t']
  518. `:array_size_name` is a regular expression used to match an array size
  519. parameter by name. By default, it's 'size|len'. To get CMock to recognize a
  520. name like `num_bananas`, you could tell it to also accept names containing
  521. 'num_' like this:
  522. cfg[:array_size_name] = 'size|len|num_'
  523. Parameters must match *both* `:array_size_type` and `:array_size_name` (and
  524. must come right after a pointer parameter) to be treated as an array size.
  525. Once you've told it how to recognize your arrays, CMock will give you `_Expect`
  526. calls that work more like `_ExpectWithArray`, and compare an array of objects
  527. rather than just a single object.
  528. For example, if you write the following, CMock will check that GoBananas is
  529. called and passed an array containing a green banana followed by a yellow
  530. banana:
  531. Banana b[2] = {GreenBanana, YellowBanana};
  532. GoBananas_Expect(b, 2);
  533. In other words, `GoBananas_Expect(b, 2)` now works just the same as:
  534. GoBananas_ExpectWithArray(b, 2, 2);
  535. * `:fail_on_unexpected_calls`:
  536. By default, CMock will fail a test if a mock is called without `_Expect` and `_Ignore`
  537. called first. While this forces test writers to be more explicit in their expectations,
  538. it can clutter tests with `_Expect` or `_Ignore` calls for functions which are not the focus
  539. of the test. While this is a good indicator that this module should be refactored, some
  540. users are not fans of the additional noise.
  541. Therefore, :fail_on_unexpected_calls can be set to false to force all mocks to start with
  542. the assumption that they are operating as `_Ignore` unless otherwise specified.
  543. * default: true
  544. * **note:**
  545. If this option is disabled, the mocked functions will return
  546. a default value (0) when called (and only if they have to return something of course).
  547. * `:inline_function_patterns`:
  548. An array containing a list of strings to detect inline functions.
  549. This option is only taken into account if you enable :treat_inlines.
  550. These strings are interpreted as regex patterns so be sure to escape
  551. certain characters. For example, use `:inline_function_patterns: ['static inline __attribute__ \(\(always_inline\)\)']`
  552. to recognize `static inline __attribute__ ((always_inline)) int my_func(void)`
  553. as an inline function.
  554. The default patterns are are:
  555. * default: ['(static\s+inline|inline\s+static)\s*', '(\bstatic\b|\binline\b)\s*']
  556. * **note:**
  557. The order of patterns is important here!
  558. We go from specific patterns ('static inline') to general patterns ('inline'),
  559. otherwise we would miss functions that use 'static inline' iso 'inline'.
  560. Compiled Options:
  561. -----------------
  562. A number of #defines also exist for customizing the cmock experience.
  563. Feel free to pass these into your compiler or whatever is most
  564. convenient. CMock will otherwise do its best to guess what you want
  565. based on other settings, particularly Unity's settings.
  566. * `CMOCK_MEM_STATIC` or `CMOCK_MEM_DYNAMIC`
  567. Define one of these to determine if you want to dynamically add
  568. memory during tests as required from the heap. If static, you
  569. can control the total footprint of Cmock. If dynamic, you will
  570. need to make sure you make some heap space available for Cmock.
  571. * `CMOCK_MEM_SIZE`
  572. In static mode this is the total amount of memory you are allocating
  573. to Cmock. In Dynamic mode this is the size of each chunk allocated
  574. at once (larger numbers grab more memory but require fewer mallocs).
  575. * `CMOCK_MEM_ALIGN`
  576. The way to align your data to. Not everything is as flexible as
  577. a PC, as most embedded designers know. This defaults to 2, meaning
  578. align to the closest 2^2 -> 4 bytes (32 bits). You can turn off alignment
  579. by setting 0, force alignment to the closest uint16 with 1 or even
  580. to the closest uint64 with 3.
  581. * `CMOCK_MEM_PTR_AS_INT`
  582. This is used internally to hold pointers... it needs to be big
  583. enough. On most processors a pointer is the same as an unsigned
  584. long... but maybe that's not true for yours?
  585. * `CMOCK_MEM_INDEX_TYPE`
  586. This needs to be something big enough to point anywhere in Cmock's
  587. memory space... usually it's a size_t.
  588. Other Tips
  589. ==========
  590. resetTest
  591. ---------
  592. While this isn't strictly a CMock feature, often users of CMock are using
  593. either the test runner generator scripts in Unity or using Ceedling. In
  594. either case, there is a handy function called `resetTest` which gets
  595. generated with your runner. You can then use this handy function in your tests
  596. themselves. Call it during a test to have CMock validate everything to this point
  597. and start over clean. This is really useful when wanting to test a function in
  598. an iterative manner with different arguments.
  599. C++ Support
  600. ---------
  601. C++ unit test/mocking frameworks often use a completely different approach (vs.
  602. CMock) that relies on overloading virtual class members and does not support
  603. directly mocking static class member methods or free functions (i.e., functions
  604. in plain C). One workaround is to wrap the non-virtual functions in an object
  605. that exposes them as virtual methods and modify your code to inject mocks at
  606. run-time... but there is another way!
  607. Simply use CMock to mock the static member methods and a C++ mocking framework
  608. to handle the virtual methods. (Yes, you can mix mocks from CMock and a C++
  609. mocking framework together in the same test!)
  610. Keep in mind that since C++ mocking frameworks often link the real object to the
  611. unit test too, we need to resolve multiple definition errors with something like
  612. the following in the source of the real implementation for any functions that
  613. CMock mocks:
  614. #if defined(TEST)
  615. __attribute__((weak))
  616. #endif
  617. To address potential issues with re-using the same function name in different
  618. namespaces/classes, the generated function names include the namespace(s) and
  619. class. For example:
  620. namespace MyNamespace {
  621. class MyClass {
  622. static int DoesSomething(int a, int b);
  623. };
  624. }
  625. Will generate functions like
  626. void MyNamespace_MyClass_DoesSomething_ExpectAndReturn(int a, int b, int toReturn);
  627. Examples
  628. ========
  629. You can look in the [examples directory](/examples/) for a couple of examples on how
  630. you might tool CMock into your build process. You may also want to consider
  631. using [Ceedling](https://throwtheswitch.org/ceedling). Please note that
  632. these examples are meant to show how the build process works. They have
  633. failing tests ON PURPOSE to show what that would look like. Don't be alarmed. ;)