【问题标题】:gmock is not counting the call when EXCEPT_CALL ::Times()当 EXCEPT_CALL ::Times() 时 gmock 不计算呼叫
【发布时间】:2021-04-14 23:23:52
【问题描述】:

我正在使用 cmake v3.19.2、gtest v1.10.0。我在构建一个类(让它成为 someClass)并尝试模拟另一个类(otherClass),其指针对象在同一个类(someClass)中并尝试查看它调用该方法的次数时遇到了这个问题。如我所见,该方法调用不计在内。我设法隔离了这个问题:

someClass.h:

#ifndef SOMECLASS_H
#define SOMECLASS_H
#include "otherClass.h"

//has an object from the other class
class someClass{
    public:
        someClass( otherClass* oc )
            : toCheck{oc}
        {}
        float method_to_forward( int id ) const;
    private:
        otherClass* toCheck;
};

#endif

someClass.cpp

#include "someClass.h"

float someClass::method_to_forward( int id ) const{
    return toCheck->method_to_check(id);
}

otherClass.h

#ifndef OTHERCLASS_H
#define OTHERCLASS_H

class otherClass{
    public:
        otherClass( float val )
            :val{val}
        {}
        virtual float method_to_check( int id ) const;

    private:
        float val;
        int id;
};

#endif

otherClass.cpp

#include "otherClass.h"

float otherClass::method_to_check( int id ) const{
    return this->val;
}

Main.cpp

#include <iostream>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "otherClass.h"
#include "someClass.h"

class mockOtherClass: public otherClass{
    public:
        mockOtherClass( float val )
            :otherClass(val)
        {}
        MOCK_METHOD( float, method_to_check, (int) );
};

TEST( test_1, testOther ){
    float val{20.00};
    mockOtherClass mo{val};
    someClass sc(&mo);
    EXPECT_CALL(mo, method_to_check(testing::_)).Times(1);//.WillOnce(testing::Return(val));
    float retVal = sc.method_to_forward( 2 );
    ASSERT_EQ(retVal, val);
}

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

CMakeLists.txt

cmake_minimum_required(VERSION 3.19.2)
project( justTest VERSION 1.0 )

find_package(GTest REQUIRED)
include_directories( ${GTEST_INCLUDE_DIRS})

find_package(GMock REQUIRED)
include_directories( ${GMOCK_INCLUDE_DIRS})

add_executable(testRunner 
Main.cpp
otherClass.cpp
someClass.cpp
)

target_link_libraries(testRunner
${GTEST_LIBRARIES}
${GMOCK_BOTH_LIBRARIES}
pthread)

我得到的失败

实际函数调用计数与 EXPECT_CALL(mo, method_to_check(testing::_))... 预期:被调用一次 实际:从未调用 - 不满意且活跃

真的很抱歉您必须检查所有代码。提前致谢。

【问题讨论】:

    标签: c++ cmake googletest googlemock


    【解决方案1】:

    真的很抱歉浪费了你们的时间,唯一的问题是 MOCK_METHOD 的变体是 MOCK_CONST_METHOD(no of args),它工作得很好。如果我们想编写一个非 const 方法的模拟,是否还有其他方法可以编写 MOCK_METHOD 而不是 MOCK_METHOD1 只是 args 发生变化,那么上述方法是否还有其他类似的变体以相同的方式工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多