Posts

Global State Dependency Injection

Software engineers often times face problems unit testing existing legacy code that has global state dependencies. There are times when large portions of code need to be refactored so that legacy code can be properly unit tested. In this post, I will introduce a technique that allows the unit testing of legacy C code even when there are global state dependencies. Here is a piece of code that illustrates a global state dependency: #include "libdb.h" #include "libuser.h" int valid_user( const char *name) { if (NULL == name) { return EINVAL; } if (0 != db_connect()) { return DB_ERROR; } if (-1 == db_user_id(name)) { return INVALID_USER; } return SUCCESS; } In this example, we can see the function valid_user has a global state dependency on a database module. If we had designed this code from the beginning, we could have used dependency injection in order to unit test this function. For example, we co
Recent posts