Skip to content

Instantly share code, notes, and snippets.

@wmacevoy
Created June 14, 2018 22:33
Show Gist options
  • Save wmacevoy/7ef9468ff95f3d8d459f48f2e76029e1 to your computer and use it in GitHub Desktop.
Save wmacevoy/7ef9468ff95f3d8d459f48f2e76029e1 to your computer and use it in GitHub Desktop.
Using templates for efficient mocks for testing arduino components....
#include <ArduinoUnit.h>
// This is pretty advanced, you need to use template specialization to
// create mocks with no runtime overhead (other than space to represent
// the mocked environment, if you choose to use it (probably in a test).
struct RealImpl {
static void pMode(int pin, int mode) { pinMode(pin,mode); }
static void dWrite(int pin, bool value) { digitalWrite(pin,value); }
static int dRead(int pin) { return digitalRead(pin); }
};
// You can have as many mock implementions as are useful
struct MockImpl {
static void pMode(int pin, int mode) { /* ignore */ }
static void dWrite(int pin, bool value) { /* whatever */ }
static int dRead(int pin) { return 0 /* whatever */; }
};
template <class impl> struct MotorTemplate {
static void setup(int pin) {
impl::pMode(pin,OUTPUT);
impl::dWrite(pin,LOW);
}
// *other things */
};
typedef MotorTemplate<RealImpl> Motor; // motor with real io
void useMotor() {
Motor::setup(1);
// ...
}
typedef MotorTemplate<MockImpl> MockMotor; // motor with mock io
test(motor) {
MockMotor::setup(1);
// ...
}
void setup() {
}
void loop() {
Test::run();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment