开发者

how to fake user input in C

Simple question I hope. I have a function that ke开发者_JAVA技巧eps prompting for user input (characters) and returns a character once it finds that the input is valid under certain conditions. I'm writing tests for this and other similar functions, but don't know how to fake user input. By the way, I'm using scanf() to get user input.


You can change the behaviour of standard input to read from a file with freopen. Place the test input in a file and call this before your test.

freopen("filename", "r", stdin);


You can do something like

echo -e "Test string\nAnother string" | ./a.out

The string of echo command should be in the sequence which the program requires

cat test_str_file | ./a.out

The file test_str_file should contain the test strings in the sequence the program requires

On the other hand you can simply replace the code's input section with some dummy sections. If you have a separate module for input, then replace it with dummy.


If you're on unix or cygwin, you can invoke your executable and ask it to use a text file as stdin. For example:

bash$ ./a.out < input_file


Why not just call the function with a default value?


This is a very naive solution, but it may do what you want:

char getFakeUserInput()
{
    static char* fakeInput = "This is some user input\n";
    static int pos = 0;

    if(pos >= strlen(fakeInput))
        return '\0';

    return fakeInput[pos++]
}


Move the validation to another function. And test it independently. Or fake the user input refactor the remainder to take in a function pointer that is called back to collect some letters. That should enable a simple fake.

I've not written C for a long time but something like could also work

/* test this independentaly */
int isvalid(char* chars){ 
  /* do stuff and return result */
}

/*real function */
char* getinput() {
  scanf(....)
  return stuff_from_scanf;
}



/*fake/mock function */
char* getinputFake(char * testString) {
   return testString;
}


test() {
 int result = isvalue(getinputFake("test data"));
 /* rest of test */
}

You don't need to test the scanf function, but you could replace it with a fscanf and pass in the stream with the chars like this

stdin

char* getinput(FILE * stream) {
   fscanf(stream....)
   return stuff_from_fscanf;
}


test() {
 FILE * stream = .....; /*create a dummy stream say from */
 int result = isvalue(getinput(stream);
 /* rest of test */
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜