Browse Source

Add "Testing C"

master
Causal Agent 6 months ago
parent
commit
bfca708ded
Signed by: Curtis McEnroe <june@causal.agency> GPG Key ID: CEA2F97ADCFCD77C
2 changed files with 80 additions and 0 deletions
  1. 79
    0
      005-testing-c.7
  2. 1
    0
      Makefile

+ 79
- 0
005-testing-c.7 View File

@@ -0,0 +1,79 @@
1
+.Dd December 21, 2018
2
+.Dt TESTING-C 7
3
+.Os "Causal Agency"
4
+.
5
+.Sh NAME
6
+.Nm Testing C
7
+.Nd a simple unit testing setup
8
+.
9
+.Sh DESCRIPTION
10
+This is a simple approach
11
+to unit testing in C
12
+that I've used in a couple projects.
13
+At the bottom of a C file
14
+with some code I want to test,
15
+I add:
16
+.
17
+.Bd -literal -offset indent
18
+#ifdef TEST
19
+#include <assert.h>
20
+
21
+int main(void) {
22
+	assert(...);
23
+	assert(...);
24
+}
25
+
26
+#endif
27
+.Ed
28
+.
29
+.Pp
30
+This file normally produces a
31
+.Pa .o
32
+to be linked into the main binary.
33
+For testing,
34
+I produce separate binaries
35
+and run them with
36
+.Xr make 1 :
37
+.
38
+.Bd -literal -offset indent
39
+TESTS = foo.t bar.t
40
+
41
+\&.SUFFIXES: .t
42
+
43
+\&.c.t:
44
+	$(CC) $(CFLAGS) -DTEST $(LDFLAGS) $< $(LDLIBS) -o $@
45
+
46
+test: $(TESTS)
47
+	set -e; $(TESTS:%=./%;)
48
+.Ed
49
+.
50
+.Pp
51
+Note that the test binaries
52
+aren't linked with the rest of the code,
53
+so there is potential for simple stubbing or mocking.
54
+.
55
+.Pp
56
+To get the best output
57
+from C's simple
58
+.Xr assert 3 ,
59
+it's best to assert the result
60
+of a helper function
61
+which takes the expected output
62
+and the test input,
63
+rather than calling
64
+.Xr assert 3
65
+inside the helper function.
66
+This way,
67
+the message printed by the assert failure
68
+contains a useful line number
69
+and the expected output
70
+rather than just variable names.
71
+.
72
+.Pp
73
+For a real example,
74
+check
75
+.Lk https://code.causal.agency/june/catgirl/src/branch/master/term.c term.c
76
+from my IRC client project.
77
+.
78
+.Sh AUTHORS
79
+.An C. McEnroe Aq Mt june@causal.agency

+ 1
- 0
Makefile View File

@@ -4,6 +4,7 @@ TXTS += 001-make.txt
4 4
 TXTS += 002-writing-mdoc.txt
5 5
 TXTS += 003-pleasant-c.txt
6 6
 TXTS += 004-uloc.txt
7
+TXTS += 005-testing-c.txt
7 8
 
8 9
 all: $(TXTS)
9 10
 

Loading…
Cancel
Save