I noticed that the table-driven test recommended by Go can be written in C as well.
Table-driven test is recommended for Go testing. The pair of data input and expected value given to the test target is treated as one test case, and the list of expected value and measured value is shown in the table.
For example, to write a test for the gcd ()
method in a table-driven manner:
gcd_test.go
func TestGcd(t *testing.T) {
cases := []struct {
a, b int
z int
}{
{12, 8, 4},
{3, 7, 1},
}
for _, c := range cases {
if gcd(c.a, c.b) != c.z {
t.Errorf("expected gcd(%v,%v) == %v\n", c.a, c.b, c.z)
}
}
}
Go can write struct definitions and variable initializations at the same time. Test case initialization is easy and type-safe with the struct literal syntax{}
. The code is very easy to read as you can focus on the test data only.
I also wrote a test of gcd ()
in C in table-driven. Even in C, structure declaration and variable initialization can be performed at the same time. And initialization can be type-safe with struct literal syntax{}
.
gcd_test.c
#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
int test_gcd() {
struct {
int a, b;
int z;
} cases[] = {
{12, 8, 4},
{3, 7, 1},
};
for (int i = 0; i < ARRAY_SIZE(cases); ++i) {
if (gcd(cases[i].a, cases[i].b) != cases[i].z) {
printf("expected gcd(%d,%d) == %d\n", cases[i].a, cases[i].b, cases[i].z);
}
}
}
Compared to Go, there was no big difference in the amount of description and readability, and I was able to write a table-driven test in C language.
Go is often referred to as a simple C, but it's also a good idea to import Go culture into C.
Recommended Posts