Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Should have used a proper mock
// This is an example unit test for a function `kv_store_write_protocol_cmd`
// The purpose is to show that `kv_store_write` should have been implemented
// as a mock using a mocking framework, rather than a roll-your-own mock.
#include "CppUTest/TestHarness.h"
#include "CppUTestExt/MockSupport.h"
extern "C" {
#include <string.h>
#include <stddef.h>
#include "kv_store/kv_store_protocol_handlers.h"
#include "kv_store/kv_store.h"
static char s_key_written[1024];
static uint8_t s_val_written[1024];
static uint32_t s_val_len;
// This is a hand-made mock, which should probably instead
// be written with a mock library
bool kv_store_write(
const char *key,
const void *val,
uint32_t len) {
// Copy all data into buffers we can read later.
strcpy(s_key_written, key, strlen(key));
memcpy(s_val_written, val, len);
s_val_len = len;
return true;
TEST(TestKvStoreProtocolHandlers, Write) {
// Key: "hello"
// Val: "world"
const uint8_t in_bytes[] = {
'h', 'e', 'l', 'l', 'o', '\0', // Key
'w', 'o', 'r', 'l', 'd' // Value
const uint8_t kv_val_bytes[] = {
'w', 'o', 'r', 'l', 'd'
// This calls kv_store_write
in_bytes, sizeof(in_bytes),
s_resp_buffer, &s_resp_buffer_len);
STRCMP_EQUAL("hello", s_key_written,);
MEMCMP_EQUAL(kv_val_bytes, s_val_written, sizeof(kv_val_bytes));
LONGS_EQUAL(sizeof(kv_val_bytes), s_val_len);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment