Run-time mocking in C?

后端 未结 4 1972
旧巷少年郎
旧巷少年郎 2021-02-08 14:20

This has been pending for a long time in my list now. In brief - I need to run mocked_dummy() in the place of dummy() ON RUN-TIME, wit

4条回答
  •  逝去的感伤
    2021-02-08 14:51

    An approach that I have used in the past that has worked well is the following.

    For each C module, publish an 'interface' that other modules can use. These interfaces are structs that contain function pointers.

    struct Module1 
    {
        int (*getTemperature)(void);
        int (*setKp)(int Kp);
    }
    

    During initialization, each module initializes these function pointers with its implementation functions.

    When you write the module tests, you can dynamically changes these function pointers to its mock implementations and after testing, restore the original implementation.

    Example:

    void mocked_dummy(void)
    {
        printf("__%s__()\n",__func__);
    }
    /*---- do not modify ----*/
    void dummyFn(void)
    {
        printf("__%s__()\n",__func__);
    }
    static void (*dummy)(void) = dummyFn;
    int factorial(int num)
    {
        int                      fact = 1;
            printf("__%s__()\n",__func__);
        while (num > 1)
        {
            fact *= num;
            num--;
        }
        dummy();
        return fact;
    }
    
    /*---- do not modify ----*/
    int main(int argc, char * argv[])
    {
        void (*oldDummy) = dummy;
    
    /* with the original dummy function */
        printf("factorial of 5 is = %d\n",factorial(5));
    
    /* with the mocked dummy */
        oldDummy = dummy;   /* save the old dummy */
        dummy = mocked_dummy; /* put in the mocked dummy */
        printf("factorial of 5 is = %d\n",factorial(5));
        dummy = oldDummy; /* restore the old dummy */
        return 1;
    }
    

提交回复
热议问题