【发布时间】:2018-11-30 22:31:08
【问题描述】:
我遇到了一个问题,我在多个不同的测试中对 GMOCK 对象调用相同的函数调用。期望调用总是相同的。但是,只有第一个测试会将期望调用与实际调用匹配。进行相同期望调用的后续测试将失败并显示以下消息:
意外的模拟函数调用 - 返回默认值。 函数调用:getNewTempAccountSlot(@0xaddrs 4-byte object ) mock函数没有设置默认动作,其返回类型也没有设置默认默认值。
所以,这里有一个代码示例,说明我如何设置我的设备。
struct fixture
{
Payment *MOCK_payment;
NiceMock<GMOCK_AccountDatabase_I*> *MOCK_accountDatabase = new NiceMock<GMOCK_AccountDatabase_I()>;
std::shared_ptr<GMOCK_AccountDatabase_I> MOCK_accountDatabaseSharedPtr = std::shared_ptr<NiceMock<GMOCK_AccountDatabase_I>>(MOCK_accountDatabase);
std::shared_ptr<GMOCK_ClientAccount_I> MOCK_clientAccount;
TransactionProcessor testTransactionProcessor;
Fixture()
: testTransactionProcessor(MOCK_accountDatabaseSharedPtr),
MOCK_clientAccount(std::make_shared<GMOCK_ClientAccount_I>())
{
MOCK_payment = new Payment();
}
~Fixture()
{
delete MOCK_payment;
MOCK_payment = 0;
Mock::VerifyAndClearExpectations(MOCK_clientAccount.get());
}
setPaymentData(ClientAccountType acc_type)
{
MOCK_payment->paymentData.account_type = acc_type;
}
}
这是我评估测试的方式
TEST(TransactionProcessorTest, New_Automatic_Payment)
{
Fixture f;
f.setPaymentData(AccountTypes::ACC_DEFAULT);
InSequence s1;
EXPECT_CALL(*f.MOCK_accountDatabase, getNewTempAccountSlot(AccountTypes::ACC_DEFAULT)).WillOnce(Return(f.MOCK_clientAccount);
f.testTransactionProcessor.processPayment(*f.payment);
}
TEST(TransactionProcessorTest, New_Manual_Payment)
{
Fixture f;
f.setPaymentData(AccountTypes::ACC_DEFAULT);
InSequence s1;
EXPECT_CALL(*f.MOCK_accountDatabase, getNewTempAccountSlot(AccountTypes::ACC_DEFAULT)).WillOnce(Return(f.MOCK_clientAccount);
f.testTransactionProcessor.processPayment(*f.payment);
}
最后是源码:
void AccountDatabase::processPayment(AccountTypes type)
{
std::shared_ptr<ClientAccount_I> temp_client_account = nullptr;
temp_client_account = AccountDatabasePtr->getNewTempAccountSlot(type);
if(temp_client_account != nullptr){
...
}
}
我真的很困惑,因为它第一次识别传入的是什么对象。我实际上可以重新排序测试,它总是会通过第一个测试并在其余的测试中失败。任何人都可以就我如何规避这个问题提供任何见解吗?预先感谢您的耐心等待。
【问题讨论】:
标签: c++ unit-testing mocking gmock