Another mock example using StubWithCallback

Auto-generated mock files in Ceedling provide Ignore and Expect functions as well as the StubWithCallback function. Here is an example of StubWithCallback use case: external EEPROM can be accessed via specific SPI commands such as read byte and write byte. It means that there is no direct way to access EEPROM contents. It would be nice to access EEPROM during unit testing. To do this, define simulated EEPROM in host RAM and the read byte function and write byte function should be implemented as StubWIthCallback.

I learned this Ceedling feature from this blog post(

First of all, create interface_flash.h:


Second, create eeprom_controller module, ceedling module:create[eeprom_controller].


eeprom_read_byte() calls flash_read() and eeprom_write_byte()calls flash_write() and EEPROM size is defined 8KB(0x2000). These wrapper functions will be implemented next post.

Third, flash_read() and flash_write() should be known as mock function so that it needs to include "mock_interface_flash.h" in line#4 below. Then, implement mock_read() and mock_write() in test_eeprom_controller.c. mock_read() is replacing flash_read() during unit testing. mock_write() is replacing flash_write() during unit testing. This replacement during unit testing is done by StubWithCallback in Ceedling. Implementation is in test file line#37, 38 below. Also, Simulated EEPROM in the host needs to be defined in test file line#6 below.


Fourth, write a test for SutbWithCallback. This test is necessary to prove mock functions are working as expected. line#49 should update mock_eeprom[0] = 0xAA. line#52 should set read_data = mock_eeprom[0]. line#53 assertion for mock_eeprom[0] = 0xAA.


The next post will show Test Driven Development process while implementing eeprom_read_byte function and eeprom_write_byte function in eeprom_controller.c. It will evolve with test_eeprom_controller.c.

Did you find this article valuable?

Support Hyunwoo Choi by becoming a sponsor. Any amount is appreciated!