【发布时间】:2018-07-18 11:53:44
【问题描述】:
我在模拟一个方法,但我的 GoogleTest 似乎一直在调用原始实现。可能遗漏了什么,但找不到这是什么?
我的班级是 Postgres 数据库访问器:
namespace project
{
class PostgresDb
{
public :
// typedef the CursorPtr, this is just a smart pointer.
// sth like
typedef shared_ptr<DbDataType> CursorPtr ;
PostgresDb( const std::string & connString ) ;
CursorPtr getRecords( const int id_1 ,
const int id_2 ) ;
protected :
// this will be used by the MockPostgresDb in our unit tests.
// it leaves the object uninitialized
PostgresDb (){} ;
}
}// end of namespace
这是我的模拟课:
namespace project_test
{
class MockPostgresDb : public project::PostgresDb
{
public :
MockPostgresDb(){} ;
MOCK_METHOD2( getRecords, CursorPtr*( const int , const int ) ) ;
} ;
class MockCursor : public CursorPtr
{
// ....
}
}
这是我正在测试的方法和测试:
void original_get_method( const int id_1, const int id_2 , PostgresDb db)
{
// ....
db.getRecords( id_1, id_2 ) ;
// ....
}
// helper function
setupGetRecords( MockPostgresDb* db ,
MockCursor* cursor )
{
EXPECT_CALL( *db, getRecords(_,_) )
.Times( 1 )
.WillRepeatedly(::testing::Return( cursor ) ) ;
}
TEST_F(....)
{
MockPostgresDb db ;
MockCursor cursor ;
// ....
setupGetRecords( &db, &cursor ) ;
// ....
// and then calling a functi
original_method( id_1, id_2, db ) ;
}
所以在我看来,我打电话给original_method 并传递一个mock_db。 mock_db 调用它的方法getRecords,它返回一个MockCursor。这是它应该让我模拟的地方,但我确实输入了db::getRecords。
我试图找出不匹配的位置,但无法弄清楚。
编辑:
因此,正如所指出的 - getRecords 应该返回 CursorPtr 而不是 CursorPtr*。所以这就是我所做的:
我也尝试过改变
MOCK_METHOD2( getRecords, CursorPtr*( const int , const int ) ) ;`
到
MOCK_METHOD2( getRecords, CursorPtr( const int , const int ) ) ; // ( no * )
并将助手更改为
// helper function
setupGetRecords( MockPostgresDb* db ,
MockCursor cursor )
{
EXPECT_CALL( *db, getRecords(_,_) )
.Times( 1 )
.WillRepeatedly(::testing::Return( cursor ) ) ;
}
并得到一些不匹配类型的编译错误。什么地方出了错?谢谢。
【问题讨论】:
-
getRecords返回CursorPtr类型的对象,而你的模拟方法试图返回CursorPtr*这是两种不同的方法。( no * )是什么意思?这似乎是导致编译器错误的原因。 -
@Yksisarvinen 好的,让我重试,但返回 CursorPtr 给了我很多编译错误。
-
你得到什么样的编译器错误?请编辑问题并添加它们(复制并粘贴它们,不要解释)。
-
你保护了
PostgresDb构造函数,你不是在任何地方创建那个类的对象吗? -
@Yksisarvinen public 参数是一个字符串,protected 仅适用于使用它的 Mock 类。参数是 db 连接到的环境,但 Mock 不需要它。编辑我的答案。
标签: c++ unit-testing googlemock