Вопрос

I have a C module and I want to refactor a little bit. There are some global variables and structures which are not hidden (in the module.h file). I use this variables in some test case but nowhere else so I thought it's a good idea to set them to static. In my test cases I extern these variables and fill with test values. But if they will be static variables I can't reach them from the test case. I don't want to write getter and setter methods and put it to the .h file, because I want to hide this variables.

I know if I include the .c file into my test case I can see the static variables. Is there any other way to fill these variables?

I use cygwin and gcc, the test framework is CppUtest.

Thanks in advance.

Это было полезно?

Решение

There are two main possibilities:

  1. The difficulty of testing is showing that the interface provided by the module is incomplete.
  2. Your unit testing is prying into the internals of the module in a way that consumers would never need to do.

If the problem is an incomplete interface, then you can add the extra interfaces that make the module more easily testable, and more generally usable. For example, if the static variables are counters of some sort, you might need to add a 'reset' method to set the counters back to zero, ready for the next part of the unit testing, or (in the more general use case) to allow the statistics to be zeroed so that you can accumulate the statistics afresh.

If the problem is unit testing needing to probe more deeply than consumers need to probe, then I don't see anything wrong with the test code using #include "sourcecode.c". It keeps the module code clean for general use; it allows the unit test to probe more deeply than it would otherwise. It converts the test code from 'black box' testing to a form of 'white box' testing - the test can see more of the tested code than a regular black box test can. But that's sometimes helpful. It is often an intermediate stage during development. Once you have all the black box testing in place, you may not need to be concerned with probing the internals in the same way - until you make changes.

Другие советы

Often its a good idea to create these static variables in a separate file (some like to call it scaffolding) so that you can get away from including the .c. The basic theory behind this is that if you are always including .c files it quickly becomes impossible to unit test since the whole idea of unit testing is drilling down and testing one bit of code without depending on the rest of it. Once you're including all these exterior .c files, you aren't doing this.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top