Question

Is there a proper way to to TDD (test driven development) against private variables and functions efficiently?

I am testing a new circular buffer module. The buffer parameters are held in a struct. These struct members should be private since the client doesn’t need to touch them. BUT by hiding the members, testing becomes much more difficult. If the struct format is public in the header, I can directly look to make sure I’m pointing at the storage array, that my read index is correct, that my write index is correct, etc. If private, I can only test the interface, which I obviously need to do, but validating the underlying hidden functionality feels slow and inefficient.

buf.h

typedef struct circBuf circBuf_t;

buf.c

struct circBuf {
    privateMember_1;
    ...
    privateMember_n;  
};

Should I put a spy in my test function? i.e.:

test_buf.c

#include "buf.h"      

struct spy_circBuf {
    privateMember_1;
    ...
    privateMember_n;
};

void test_circBufInit(void) 
{
    circBuf_t * p_testCircBuf;
    struct spy_circBuf * p_spy;

    p_testCircBuf = CircBuf_Init (initVar_1, ...);

    p_spy = ((struct spy_circBuf *)p_testCircBuf);

    TEST_ASSERT_EQUAL(p_spy->privateMember_1, initVar_1);
}

Is there a better way to do TDD on private variables and functions?

Was it helpful?

Solution

TDD is about testing the external behavior of your class, not the internal implementation. If your tests look at the internal implementation, they will fragile and may break if details of the implementation change. This will discourage you from refactoring and improving the code.

TDD also emphasizes that you write each test before you write the necessary production code. This helps avoid testing implementation because you are writing a test for an implementation that doesn't exist yet. This encourages you to think about the desired behavior of your class and write a test to exercise that behavior.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top