Simvik

Write a CMock-style mock

A mock that checks a driver makes exactly the bus writes a test expects, in order, and reports what went wrong. A medium embedded C problem (Testing and code…

medium · Testing and code coverage · testing · mocks · cmock · drivers

A fake works like the real thing. A mock also checks how it was called. CMock generates mocks like this one from a header. Write it by hand:

  • mock_expect_write(reg, val, ret) queues an expected call (at most MOCK_MAX at a time) and the value that call returns.
  • bus_write(reg, val) takes the next expectation:
  • if it matches, return its ret;
  • if it does not, print FAIL: expected write(0xRR, 0xVV), got write(0xRR, 0xVV) and still return its ret;
  • if there is none left, print FAIL: unexpected write(0xRR, 0xVV) and return 0.
  • mock_verify() prints FAIL: missing write(0xRR, 0xVV) for each expected call that was never made. It returns the number of failures since the last verify (all three kinds), and clears the mock for the next test.

Use two hex digits, upper case, as in 0x2A. The tests run your mock against a correct sensor driver and against several broken ones.

Starter code

int bus_write(uint8_t reg, uint8_t val) {
  (void)reg; (void)val;
  return 0;
}

void mock_expect_write(uint8_t reg, uint8_t val, int ret) {
  (void)reg; (void)val; (void)ret;
}

int mock_verify(void) {
  return 0;
}

Example tests

The correct driver, then a wrong register value

run("good", init_good, 0);
run("wrong value", init_wrong_value, 0);

Expected output:

good: returned 0, 0 failures
FAIL: expected write(0x20, 0x57), got write(0x20, 0x47)
wrong value: returned 0, 1 failure

Learn it first

More Testing and code coverage problems