AUnit  1.3
Unit testing framework for Arduino platforms inspired by ArduinoUnit and Google Test.
/home/brian/dev/AUnit/src/aunit/fake/README.md
1 # Fake Arduino Classes
2 
3 This directory contains fake versions of some Arduino classes for the purposes
4 of unit testing. These header files are *not* included automatically by the
5 `#include <AUnit.h>` preprocessor directive. The various fake classes must be
6 included manually just after the `<AUnit.h>` is included. The fake classes
7 live in the `aunit::fake` namespace.
8 
9 ## FakePrint
10 
11 The `FakePrint` class is an implementation of the
12 [Print](https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/Print.h)
13 class which is the base class of the
14 [HardwareSerial](https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/HardwareSerial.h)
15 and other output classes. The `Serial` global object is an instance of the
16 `HardwareSerial` class. If a user-defined class or method is defined to use an
17 instance of the `Print` object, instead of hardcoding a dependency to the
18 `Serial` instance, then an instance of the `FakePrint` class can be substituted
19 and used to write unit tests for the user-defined class or method.
20 
21 Let's say the user-defined class is called `Greeter` and a method called
22 `greet()` prints something out to `Serial`:
23 
24 ```C++
25 class Greeter {
26  public:
27  Greeter(Print& printer):
28  mPrinter(printer) {}
29 
30  void greet(int n) {
31  mPrinter.print("hello ");
32  mPrinter.print(n);
33  mPrinter.println(" world(s)");
34  }
35 
36  private:
37  Print& mPrinter;
38 };
39 ```
40 
41 If we want to verify that the `Greeter::greet()` method prints what is expected,
42 we inject an instance of `FakePrint` (instead of `Serial`) in a test called
43 `GreeterTest.ino`:
44 
45 ```C++
46 #line 2 "GreeterTest.ino"
47 
48 #include <AUnit.h>
49 #include <aunit/fake/FakePrint.h>
50 
51 using namespace aunit;
52 using namespace aunit::fake;
53 
54 test(GreeterTest, greet) {
55  FakePrint fakePrint;
56  Greeter greeter(fakePrint);
57 
58  greeter.greet(1);
59  assertEqual("hello 1 world(s)\r\n", fakePrint.getBuffer());
60  fakePrint.flush();
61 
62  greeter.greet(2);
63  assertEqual("hello 2 world(s)\r\n", fakePrint.getBuffer());
64  fakePrint.flush();
65 }
66 
67 void setup() {
68  delay(1000);
69  Serial.begin(115200);
70  while (! Serial); // Wait until Serial is ready - Leonardo/Micro
71 }
72 
73 void loop() {
74  TestRunner::run();
75 }
76 ```