How to unit test a main() function?

Hello,

I have a program with just a main() function that contains some cin.

I want to create unit tests that run the program, send in input for the cin, and then check the output to see if it matches what is expected.

I am using Visual Studio 2010 and Eclipse for C++.

Any help would be greatly appreciated :)
closed account (10oTURfi)
What do you mean?

1
2
3
4
5
6
7
8
9
10
11
#include <string>
#include <iostream>
using namespace std;

int main()
{
string input:
cin >> input;
cout << input << endl;
return 0;
}
Krofna, Nice. I know that there is a way to make automate unit testing by using father process and make the main the child.
But I don't know how to do it !!
How many value are you reading using cin?

You could modify your program so it takes a command line parameter which specifes the values you would have entered. You could then drive your tests using a batch file (at least to start with).

If you have multiple inputs, you could read the input values from file (its path would be the command line parameter)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <string>
#include <iostream>
using namespace std;

int main(int arcg, char*argv[])
{
    string input:

    if(1 < argc)
    {
        input = argv[1];
    }
    else
    {
        cin >> input;
    }

    cout << input << endl;

    ProcessInput(input);

    return 0;
}


1
2
3
4
5
@echo off
echo Running tests...
test.exe  "input one" > results_1.txt
test.exe  "input two" > results_2.txt
test.exe  "input three" > results_3.txt


Andy

P.S. Do you already use a diff tool? (WinMerge/DiffMerge/...)
Last edited on
I found one solution:

I used _popen to open the program I want to test with a program created just for testing.

This program is able to receive the output of cout and convert them to strings.

I used SendInput to input into cin.

I have a text file that contains the test input and the expected output.

The fault I have with this approach is that I have to input by emulating keyboard; it would be better if I could directly send strings into the cin. Also, I found that by emulating the keyboard, if I try to input two same consecutive characters, I can only output one of the characters unless I put a Sleep(15 ms) between the two characters.

If there's any other solutions others can think of or how to fix the problems above plz tell me :)

thanks everyone,
Dennis
Topic archived. No new replies allowed.