【问题标题】:GMOCK Uninteresting Function call for any test that isn't the first test on a shared pointer mock objectGMOCK Uninteresting Function call for any test that is not the first test on a shared pointer mock object
【发布时间】: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


    【解决方案1】:

    好的,我正在回答我自己的问题,因为我刚刚想通了,如果其他人可以从中学习,那么我希望他们能利用我的愚蠢。

    基本上,我假设我的 f.setPaymentData(AccountType type) 正在为帐户类型枚举设置数据。我这样做是因为第一个测试通过! (那是因为真实数据有更多的字段,我看过了)。但事实证明,我不是!我不确定为什么第一个 google mock expect 调用通过了,但是在我设置了数据之后,其余的也开始通过了。我希望这有帮助。

    (我也不确定为什么它被否决了,如果我做错了什么,我将永远感激我如何做得更好的见解,干杯)

    【讨论】:

      猜你喜欢
      • 2022-12-02
      • 2022-12-02
      • 2013-11-30
      • 2018-01-20
      • 1970-01-01
      • 2022-10-13
      • 1970-01-01
      • 2019-11-10
      • 1970-01-01
      相关资源
      最近更新 更多