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 mostMOCK_MAXat 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 itsret; - if there is none left, print
FAIL: unexpected write(0xRR, 0xVV)and return 0. mock_verify()printsFAIL: 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 failureLearn it first
- Testing and code coverage · Unit tests on the host, mocks, HIL, coverage and static analysis.
More Testing and code coverage problems
- Test with a fake GPIO · Write a fake that records pin writes and delays, so code can be tested off target.
- A fake I2C device for driver tests · Write a fake I2C bus with one register-mapped device, so a sensor driver can be tested on a PC.
- Write tests that catch the bugs · Write a test suite for a scaling function. It is graded by running it against buggy versions it must reject.