'How to implement google mock to mock the C fopen function

I am writing a unit test for embedded C codes using google test/mock. The C function code looks like this.

int readGPIOSysfs(int ioport){
  ...
  FILE *f = fopen("/sys/class/gpio/export", "w");
  ..
  fclose(f);
}

How can I implement a google mock on fopen function call?

Thank you in advance.



Solution 1:[1]

I do it using CppuTest instead of Gtest :

//io.c -> imlementation
#include "drivers/io.h"
#include <string.h>
#include <stdio.h>

bool read_io()
{
    FILE *fp_driver = fopen("/dev/io/my_device", "rw");
    char msg[255] = {0};

    if (fp_driver == NULL)
        return false;

    fread(msg, sizeof(char), 255, fp_driver);

    if (strcmp(msg, "This is a test"))
        return false;

    return true;
}

//io.cpp -> Tests functions
#include "CppUTest/CommandLineTestRunner.h"
#include "CppUTest/TestHarness.h"
#include "CppUTestExt/MockSupport.h"
#include <stdio.h>
#include <string.h>

extern "C"
{
#include "drivers/io.h"
}

TEST_GROUP(IO)
{
    void setup() {
    }


    void teardown() {
        mock().clear();
    }

};

// Mocking function
FILE *fopen (const char *__restrict __filename, const char *__restrict __modes)
{
    void * r = mock().actualCall(__func__).returnPointerValue();
    return (FILE *)r;
}

TEST(IO, simpleTest)
{
    /* Create a temp file with a test string inside to match with
       implementation function expectation */
    FILE * tmp_log_file = tmpfile();
    char str[] = "This is a test";
    fwrite(str, sizeof(char), strlen(str), tmp_log_file);
    rewind(tmp_log_file);

    /* Return or temp file pointer for the next call of fopen */
    mock().expectOneCall("fopen").andReturnValue(tmp_log_file);


    bool r = read_io();
    CHECK_TRUE(r);
    mock().checkExpectations();
}

int main(int ac, char** av)
{
    return CommandLineTestRunner::RunAllTests(ac, av);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Furlings