Nik Reiman Nik Reiman - 1 month ago 6
C++ Question

How to redirect data to stdin within a single executable?

I am using cxxtest as the test framework for my C++ classes, and would like to figure out a way to simulate sending data to classes which would normally expect to receive it from standard input. I have several different files which I would like to send to the classes during different tests, so redirection from the command line to the test suite executable is not an option.

Basically, what I would really like to do is find a way to redefine or redirect the 'stdin' handle to some other value that I create inside of my program, and then use fwrite() from these tests so that the corresponding fread() inside of the class pulls the data from within the program, not from the actual standard I/O handles associated with the executable.

Is this even possible? Bonus points for a platform-independent solution, but at a very minimum, I need this to work with Visual Studio 9 under Windows.

Answer

The appropriate method is to rewrite your classes so that they are testable. They should accept as a parameter the handle, stream or file from which they are supposed to read data - in your test framework, you can then mock in the stream or supply the path to the file containing the test data.

Comments