[{"data":1,"prerenderedAt":23},["ShallowReactive",2],{"page:\u002Fresource-library\u002Fembedded-tdd-mocking":3},{"path":4,"layout":5,"title":6,"description":7,"ogImage":8,"post":9,"html":22},"\u002Fresource-library\u002Fembedded-tdd-mocking","post","Embedded TDD: Mocking","Mocks check expected call sequences; fakes stand in with their own state. How both break hardware dependencies and inject errors in embedded unit tests.","\u002Fimages\u002Fresource-library\u002Fembedded-tdd-mocking\u002Fc-source-bcm2835-gpio-fsel-social.jpg",{"author":10,"published":11,"updated":12,"tags":13,"image":20,"imageAlt":21},"Austin Glaser","2017-05-04",null,[14,17],{"name":15,"slug":16},"Embedded systems and software","embedded-software",{"name":18,"slug":19},"Testing and quality","testing","\u002Fimages\u002Fresource-library\u002Fembedded-tdd-mocking\u002Fc-source-bcm2835-gpio-fsel.webp","Close-up of C source code calling bcm2835 gpio_fsel and gpio_set_pud","\u003Cp>\"Mocking\" (or \"faking\") is the process by which a different version of a software module is\n  substituted in a test for that which will be used at runtime. It can be an extremely valuable tool\n  for managing abstraction layers and, especially, for managing hardware dependency.\u003C\u002Fp>\n\u003Cp>I've mentioned mocking in passing in several previous posts. This one will deal with the topic in\n  detail. In general, I'll be covering the what, why, and why not of the topic.\u003C\u002Fp>\n\u003Cp>I won't spend a great deal of time on the \u003Cem>how\u003C\u002Fem>, since that's highly dependent on the set\n  of tools you'll use. However, I will again call out the \u003Ca href=\"http:\u002F\u002Fwww.throwtheswitch.org\u002F\"\n  target=\"_blank\" rel=\"noopener\">Throw The Switch\u003C\u002Fa> collection, and especially \u003Ca\n  href=\"http:\u002F\u002Fwww.throwtheswitch.org\u002Fcmock\" target=\"_blank\" rel=\"noopener\">CMock\u003C\u002Fa>. I use these\n  on a daily basis, and while they have their share of problems I've found them to be better than\n  any other testing tools I've tried for the C language.\u003C\u002Fp>\n\u003Cp>Now, enough plugs -- let's get down to business.\u003C\u002Fp>\n\u003Ch2>What?\u003C\u002Fh2>\n\u003Cp>The term \"mock\" has some ambiguity. When I use it, however, I mean something fairly specific.\u003C\u002Fp>\n\u003Ch2>Mocks\u003C\u002Fh2>\n\u003Cp>A mock is a software module which:\u003C\u002Fp>\n\u003Cul>\n\u003Cli>Implements the interface of another module in the system\u003C\u002Fli>\n\u003Cli>Is intended only to be used during unit testing\u003C\u002Fli>\n\u003Cli>Allows unit tests to define expected sequences of function calls, and their arguments\u003C\u002Fli>\n\u003Cli>Allows unit tests to inject data through the return values of expected functions\u003C\u002Fli>\u003C\u002Ful>\n\u003Cp>Additionally, mocks will almost always be automatically generated rather than manually written --\n  though I don't consider this a hard and fast property.\u003C\u002Fp>\n\u003Ch2>Fakes\u003C\u002Fh2>\n\u003Cp>Another term which will come up in this discussion is a \"fake.\" Fakes share some similarity with\n  mocks, but for this discussion there are some important distinctions.\u003C\u002Fp>\n\u003Cp>A fake is a software module which:\u003C\u002Fp>\n\u003Cul>\n\u003Cli>Implements the interface of another module in the system\u003C\u002Fli>\n\u003Cli>Is intended only to be used during unit testing\u003C\u002Fli>\n\u003Cli>Maintains some internal state\u003C\u002Fli>\n\u003Cli>Allows unit tests to examine and directly modify this internal state\u003C\u002Fli>\n\u003Cli>Modifies this state based on function calls to the public interface\u003C\u002Fli>\u003C\u002Ful>\n\u003Cp>In general, fakes are written manually.\u003C\u002Fp>\n\u003Ch2>An example\u003C\u002Fh2>\n\u003Cp>Let's take as an explanatory example a module which, in production, talks to an EEPROM chip.\n  We'll keep it simple -- it'll have two methods, \u003Ccode>uint8_t eeprom_read(uint32_t address)\u003C\u002Fcode>\n  and \u003Ccode>void eeprom_write(uint32_t address, uint8_t val)\u003C\u002Fcode>.\u003C\u002Fp>\n\u003Cpre>\u003Ccode>\u002F* eeprom.h *\u002F\n\nuint8_t eeprom_read(uint32_t address);\nvoid eeprom_write(uint32_t address, uint8_t value);\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Cp>We want to test the \u003Ccode>increment\u003C\u002Fcode> module, which does some simple and mindless stuff:\u003C\u002Fp>\n\u003Cpre>\u003Ccode>\u002F* increment.h *\u002F\n\nvoid increment_eeprom_value(uint32_t address);\n\n\u002F* increment.c *\u002F\n\nvoid increment_eeprom_value(uint32_t address)\n{\n    uint8_t val = eeprom_read(address);\n    eeprom_write(address, val + 1);\n}\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Cp>When testing a module which calls these methods, we can't directly use the \u003Ccode>eeprom\u003C\u002Fcode>\n  module since no equivalent chip is accessible to our development environment. We can write our\n  test using either a fake or a mock.\u003C\u002Fp>\n\u003Cp>In the below examples, I use the syntax valid for CMock and Unity (a test framework). It should\n  be fairly self-explanatory, but for clarification you can consult \u003Ca\n  href=\"https:\u002F\u002Fgithub.com\u002FThrowTheSwitch\u002FUnity\u002Fblob\u002Fmaster\u002Fdocs\u002FUnityAssertionsReference.pdf\"\n  target=\"_blank\" rel=\"noopener\">the\u003C\u002Fa> \u003Ca\n  href=\"https:\u002F\u002Fgithub.com\u002FThrowTheSwitch\u002FCMock\u002Fblob\u002Fmaster\u002Fdocs\u002FCMock_Summary.md\" target=\"_blank\"\n  rel=\"noopener\">documentation\u003C\u002Fa>.\u003C\u002Fp>\n\u003Cp>When using a mock, we'd express the exact sequence of reads and writes we expect. Thusly:\u003C\u002Fp>\n\u003Cpre>\u003Ccode>\u002F* test_increment.c *\u002F\n\n#include \"increment.h\"\n#include \"mock_eeprom.h\" \u002F* Automatically generated *\u002F\n\nvoid test_increments_a_value(void)\n{\n    eeprom_read_ExpectAndReturn(0x500, 32);\n    eeprom_write_Expect(0x500, 33);\n\n    increment_eeprom_value(0x500);\n}\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Cp>For a simple module like this, it's clean and straightforward. However, as the function under\n  test gets more and more complex, it might not make sense to put expectations on the precise\n  sequence of reads and writes that happen -- after all, what you \u003Cem>really\u003C\u002Fem> care about is the\n  starting and ending state of the EEPROM's memory. So maybe we'll write a fake instead, which\n  stores the EEPROM's state as an array in memory. Here's what it might look like:\u003C\u002Fp>\n\u003Cpre>\u003Ccode>\u002F* fake_eeprom.h *\u002F\n\n#define FAKE_EEPROM_SIZE 1024\n\nextern uint8_t fake_eeprom_mem[FAKE_EEPROM_SIZE];\n\nvoid fake_eeprom_reset(void);\n\n\u002F* fake_eeprom.c *\u002F\n\n#include &lt;string.h&gt;\n\nuint8_t fake_eeprom_mem[FAKE_EEPROM_SIZE];\n\nvoid fake_eeprom_reset(void)\n{\n    memset(fake_eeprom_mem, 0xFF, sizeof(fake_eeprom_mem));\n}\n\nuint8_t eeprom_read(uint32_t address)\n{\n    return fake_eeprom_mem[address];\n}\n\nvoid eeprom_read(uint32_t address, uint8_t val)\n{\n    fake_eeprom_mem[address] = val;\n}\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Cp>Our test, now, can look like the following:\u003C\u002Fp>\n\u003Cpre>\u003Ccode>\u002F* test_increment.c *\u002F\n\n#include \"increment.h\"\n#include \"fake_eeprom.h\"\n\nvoid test_increments_a_value(void)\n{\n    fake_eeprom_reset();\n    fake_eeprom_mem[0x500] = 32;\n\n    increment_eeprom_value(0x500);\n\n    TEST_ASSERT_EQUAL_UINT8(33, fake_eeprom_mem[0x500]);\n}\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Cp>Of course, real tests and modules will generally be much more complex.\u003C\u002Fp>\n\u003Cp>The line between mocks and fakes is not always clear -- in real applications, one tends to blend\n  into the other. Nor is it always easy to determine which strategy should be used in a given\n  situation.\u003C\u002Fp>\n\u003Ch2>Why?\u003C\u002Fh2>\n\u003Cp>Mocking is the single factor which allows effective and complete unit testing of embedded\n  systems. In short, it allows us to break the hardware dependency of the code we're writing. But\n  it's important to keep in mind when, where, and how to use it. Here's a partial list of some of\n  its powerful advantages:\u003C\u002Fp>\n\u003Ch2>Breaking hardware dependency\u003C\u002Fh2>\n\u003Cp>This is first, because it's arguably the most important. Mocking allows us to simulate the\n  behavior of software modules which, in their native form, access hardware registers, perform IO,\n  or call non-native assembly code. If they were compiled and run directly on the development\n  system, they would either not compile or access protected memory.\u003C\u002Fp>\n\u003Ch2>Injecting errors\u003C\u002Fh2>\n\u003Cp>Mocking provides a wonderful way to inject hard-to-produce errors into modules-under-test and\n  ensure they're handled properly. Simulating a malfunctioning peripheral bus or a\n  hopefully-unreachable software state would be difficult to do in a reproducible manner on the\n  target hardware, but with a mock or a fake it can be as simple as controlling the return value\n  from the stubbed functions.\u003C\u002Fp>\n\u003Ch2>Managing complexity\u003C\u002Fh2>\n\u003Cp>Unit tests which must exercise the entire \"stack\" of a top-level module will quickly get\n  obscenely complex. To manage this, it may make the most sense to test such modules\n  \"level-by-level,\" where each abstraction layer is only tested against its use of the interfaces\n  below it.\u003C\u002Fp>\n\u003Cp>However, when you encounter such a situation in your code (especially when the layers of\n  abstraction really start piling up), it may be time to reconsider your overall architecture.\n  Often, it's possible to invert your dependencies, or to \"unstack\" the various software modules,\n  making them independent by inserting some simplistic and easily tested glue code.\u003C\u002Fp>\n\u003Ch2>Testing glue\u003C\u002Fh2>\n\u003Cp>\"Glue code\" is extremely simple code used to join different modules together. As mentioned above,\n  it can often be a worthwhile alternative to having two modules directly call one another. The\n  inherently simplistic nature of glue code makes it amenable to tests which simply ensure that, for\n  instance, the data coming out of one function gets passed into another.\u003C\u002Fp>\n\u003Cp>Below is a simplistic example of glue code:\u003C\u002Fp>\n\u003Cpre>\u003Ccode>\u002F* sensor.h *\u002F\n\nuint16_t sensor_read(void);\n\n\u002F* filter.h *\u002F\n\nuint16_t filter_update(uint16_t raw);\n\n\u002F* glue.h *\u002F\n\nuint16_t sensor_filtered(void);\n\n\u002F* glue.c *\u002F\n\nuint16_t sensor_filtered(void)\n{\n    return filter_update(sensor_read());\n}\n\n\u002F* test_glue.c *\u002F\n\n#include \"glue.h\"\n#include \"mock_sensor.h\"\n#include \"mock_filter.h\"\n\nvoid test_sensor_filtered(void)\n{\n    sensor_read_ExpectAndReturn(32);\n    filter_update_ExpectAndReturn(32, 54);\n\n    TEST_ASSERT_EQUAL_UINT16(54, sensor_filtered());\n}\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Cp>Of course, in a real project you probably wouldn't call the module \u003Ccode>glue\u003C\u002Fcode>; it might\n  live in \u003Ccode>main.c\u003C\u002Fcode> or somewhere else appropriate.\u003C\u002Fp>\n\u003Ch2>Why not?\u003C\u002Fh2>\n\u003Cp>Despite all the good reasons to use mocks, it's critical to keep in mind that any time a unit\n  test relies on this technique it's making assumptions about the behavior of the mocked module. As\n  these assumptions become more pervasive, your unit tests will become less and less useful.\u003C\u002Fp>\n\u003Cp>On the other hand, some level of assumption is \u003Cem>always\u003C\u002Fem> necessary. These are, after all,\n  just unit tests -- their stated purpose is to test code units in isolation from one another.\n  Integration tests, or full-blown functional testing, are critical to ensuring your system works as\n  expected top-to-bottom. But restructuring your code to minimize the necessity of mocking can often\n  increase the efficacy of your unit tests -- while generally decreasing dependencies and thus\n  making reuse easier.\u003C\u002Fp>\n\u003Cp>Below is a brief list of possible techniques, each of which could be expanded to a blog post in\n  its own right:\u003C\u002Fp>\n\u003Cul>\n\u003Cli>Inverting dependencies, moving I\u002FO and hardware dependency to the top layer\u003C\u002Fli>\n\u003Cli>Breaking dependencies. That is, if module A calls module B, modify the code so that both are\n  self-contained and a thin glue module passes values between them where necessary\u003C\u002Fli>\n\u003Cli>Eliminating hardware dependency. Writing portable code that doesn't \u003Cem>need\u003C\u002Fem> to be mocked,\n  and can be tested in isolation\u003C\u002Fli>\u003C\u002Ful>\n\u003Ch2>Conclusion\u003C\u002Fh2>\n\u003Cp>This post is a whirlwind tour of mocking, faking, and various situations. It's a good reference\n  to keep in the back of your mind as you dive into projects -- and may prove more useful if\n  returned to after you've had hands-on experience with some real-world situations.\u003C\u002Fp>",1795194793295]