使用gtest单元测试,使用stub为sqlite3接口进行Mock

使用stub可以对sqlite3的C接口进行mock

代码

#include 
#include "sqlite3.h"
using namespace std;

#include 
#include 
#include 

int GetValue(std::string key) 
{
    int ret;

    std::string sql = "SELECT value FROM Table WHERE Key=`" + key + "`;";

    sqlite3 *m_sql;
    if (SQLITE_OK != sqlite3_open_v2("test.db", &m_sql, SQLITE_OPEN_READWRITE | SQLITE_OPEN_NOMUTEX, NULL))
    {
        return -1;
    }
    
    sqlite3_stmt *pStmt;
    int sql_ret = sqlite3_prepare_v2(m_sql, sql.c_str(), -1, &pStmt, NULL);
    if (SQLITE_OK != sql_ret)
    {
        return -1;
    }
    else
    {
        sql_ret = sqlite3_step(pStmt);
        if (sql_ret == SQLITE_ROW)
        {
            ret = sqlite3_column_int(pStmt, 0);
        }
        else if (sql_ret == SQLITE_DONE)
        {
          ret = -1;
        }
    }

    sqlite3_finalize(pStmt);
    return ret;
}

int check_sqlite3_prepare_v2(
  sqlite3 *db,            /* Database handle */
  const char *zSql,       /* SQL statement, UTF-8 encoded */
  int nByte,              /* Maximum length of zSql in bytes. */
  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
)
{
    return SQLITE_OK;
}
 
int check_sqlite3_open_v2(
  const char *filename,   /* Database filename (UTF-8) */
  sqlite3 **ppDb,         /* OUT: SQLite db handle */
  int flags,              /* Flags */
  const char *zVfs        /* Name of VFS module to use */
)
{
    return SQLITE_OK;
}

int check_sqlite3_step(sqlite3_stmt*){
    return SQLITE_ROW;
}
 
int check_sqlite3_column_int(sqlite3_stmt*, int iCol){
    return 1;
}

int check_sqlite3_finalize(sqlite3_stmt*){
    return SQLITE_OK;
}

TEST(GetValue, GetValue_1){
    Stub stub;
    stub.set(sqlite3_prepare_v2, check_sqlite3_prepare_v2);
    stub.set(sqlite3_open_v2, check_sqlite3_open_v2);
    stub.set(sqlite3_step, check_sqlite3_step);
    stub.set(sqlite3_column_int, check_sqlite3_column_int);
    stub.set(sqlite3_finalize, check_sqlite3_finalize);

    int ret = GetValue("test");
    EXPECT_EQ(ret, 1);
}

int main(int argc, char **argv)
{
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

编译

$ g++ test.cpp -lgtest -lgmock -lpthread -lsqlite3

输出

[==========] Running 1 test from 1 test suite.
[----------] Global test environment set-up.
[----------] 1 test from GetValue
[ RUN      ] GetValue.GetValue_1
[       OK ] GetValue.GetValue_1 (0 ms)
[----------] 1 test from GetValue (0 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test suite ran. (0 ms total)
[  PASSED  ] 1 test.

你可能感兴趣的:(单元测试,c++,linux)