ccmock

How to configure expectations in cmock for a "read" function


Given a function under test that does something like:

void funcUnderTest()
{
    char buf[32];
    int bufSize=32;
    someReadFunction(buf, size);
}

int someReadFunction(char* buf, int size)
{
    int readlen;
    //loads buf with data
    //returns number of bytes copied
    return readlen;
}

How can i write my unit test such that the mock function:

  1. Loads buf with specific data
  2. returns a specified retval

eg:

void test_funcUnderTest()
{
    char* testBuf="Hello World";
    someReadFunc_ReturnArrayThruPtr_buf(testBuf,12) // Copy "testBuf" into "buf"
    //How do we control return value?
    funcUnderTest();
 }

Solution

  • You can configure the Mock object by combining multiple expectations. It should work like this:

    void test_funcUnderTest()
    {
        char* testBuf="Hello World";
        someReadFunc_ExpectAnyArgsAndReturn(retval)     // Return "retval" on next call
        someReadFunc_ReturnArrayThruPtr_buf(testBuf,12) // Copy "testBuf" into "buf" on the same call
        funcUnderTest();
    }
    

    Be aware though, that the order of this calls matters. Usually you need to call the "Expect" function first before defining the behavior of specific arguments.