Ignoring user input when testing with unity

75 Views Asked by At

I have a chatbot program that uses a function called userInput() to get the input from the user.

I have to test the program for my project but I don't know how to input text into the function in the test program. Everything I have tried has stopped the automatic testing waiting for the user to type something.

Any help adding test phrases the user would say without stopping the testing program.

char *userInput()
{
    char *str = NULL;
    int ch;
    size_t size = 0, len = 0;

    while ((ch=getchar()) != EOF && ch != '\n') {
        if (len + 1 >= size)
        {
            size = size * 2 + 1;
            str = realloc(str, sizeof(char)*size);
        }
        str[len++] = ch;
    }

    if (str != NULL) {
        str[len] = '\0';
    }

    return str;
}
1

There are 1 best solutions below

0
On

I ran with anonmess's idea that you can input text from the user using an input file. I used an input file with the following lines:

testing input
testing input 2

The input file name is given through the command line. You can hard code the filename if you'd like.

#include <stdio.h>
#include <string.h>

int processInputFile(char *filename)
{
    FILE *ifp;
    char buffer[1024];
    char *p;

    if ((ifp = fopen(filename, "r")) == NULL)
    {
        fprintf(stderr, "Failed to open \"%s \" in processInputFile.\n", filename);
        return -1;
    }

    while ((fgets(buffer, sizeof(buffer), ifp)) != NULL)
    {
        // remove newline character
        p = strchr(buffer, '\n');

        if (p != NULL)
            *p = '\0';

        // We can also remove the newline character by getting
        // its length and chomping the last character

        // int length = strlen(buffer);
        // buffer[length - 1] = '\0';

        printf("%s\n", buffer);
    }

    fclose(ifp);

}

int main(int argc, char **argv)
{
    if (argc < 2)
    {
        printf("Proper syntax: ./a.out <n>\n");
        return -1;
    }

    processInputFile(argv[1]);

    return 0;
}

The file is read and the lines are printed. You can pass the string to another function within the while loop.