C Command Line Interface Testing

For #ProjectEuler100, I am working in C.

I have a basic command line interface for user input. I am trying to follow best practices (documentation, unit testing, etc).

Does anyone know of any good ways to do unit testing for C interfaces that use functions such as fgets?

(I haven’t had a chance to do an in depth Google for possible approaches, but I will put what I find here.)

GitHub: https://github.com/jeremylt/ProjectEuler

There are a multitude of ways to get this done. Some may suit your scenario better than others. Here are a couple…

One option is to use dependency injection. That is, instead of coding your function to use fgets directly code it to us a pointer to a function with the signature of fgets (char *fgets(char *str, int n, FILE *stream)). The function pointer can be either passed in to your function of be global.

Then, when your code runs when under test, set the function pointer to point to a function that returns what you would like fgets to return for that test case. When you run your code in production, set the function pointer to fgets.

Another option: Instead of hard coding stdin into your fgets calls, pass the FILE *stream parameter into your function. Then, when your code runs when under test, pass in a FILE *stream that contains the input you want to test against. When your code is run under production, pass in stdin or whatever is appropriate.

1 Like

Thank you for those fantastic approaches! I think the second approach works particularly well in my test harness.

I’ll let you know how it goes.

I went with specifying the streams to my functions that use fgets, and it worked great.