deanhiller said:
In C++ or Java, or whatever OO, I am used to using the Dependency
Injection Pattern(or I believe formerly called Inversion of Control
Pattern) to accomplish test first in a large system. ie. I would have
5 architecture components, and I would simply create a mock object of
one of those systems like
Station s = MockObjectFactory.createMock(Station.class);
I would then pass the station into the system I was going to test and I
could poke and prod the system from both ends(bottom and top where
bottom is the Station api and top is the "system under test"s api).
How can I do this in C?
As I understand it, the concept of 'test first' is language
neutral, not dependent upon a particular syntax. It means:
"Envision that certain needed or desired functions already exist.
Write code to use those functions. Of course you'll get errors
from the translator. Incrementally add code until no errors
remain. Then check that the results are the intended ones.
If not, modify the code until they are."
First we write:
#include <stdio.h>
int main()
{
int x = 25;
int y = 17;
int r = sum(x, y); /* compute sum of two values */
printf("%d + %d == %d\n", x, y, r); /* display values and their sum */
return 0;
}
We compile ... get error: no 'sum()' function.
So we write:
#include <stdio.h>
int sum(int a, int b)
{
return a * b;
}
int main()
{
int x = 25;
int y = 17;
int r = sum(x, y); /* compute sum of two values */
printf("%d + %d == %d\n", x, y, r); /* display values and their sum */
return 0;
}
No compiler errors. Great. Now we run it, and get output:
25 + 17 == 425
Oops.
So we continue to edit:
#include <stdio.h>
int sum(int a, int b)
{
return a + b;
}
int main()
{
int x = 25;
int y = 17;
int r = sum(x, y); /* compute sum of two values */
printf("%d + %d == %d\n", x, y, r); /* display values and their sum */
return 0;
}
Compile, run, get output:
25 + 17 == 42
Voila! The Answer.
This is of course very simplified, real life testing would
be much more thorough. But this is the essential idea.
As well as helping to manage bugs, this is also a good way
to determine what functions are needed. IOW when writing
the 'top level' (test) code, when needed, simply imagine
and make up (meaningful) names for functions that implement it.
'Stylized' example:
int main()
{
initialize();
compute();
cleanup();
return 0;
}
I have not (yet) developed a habit of always using 'test first',
but when I have used it, it has indeed helped with both bug
control and organizing my code.
-Mike