如何解决当 EXCEPT_CALL ::Times() 时,gmock 不计算调用
我使用的是 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(测试::_))... 预期:被调用一次 实际:从未致电 - 不满意且活跃
我真的很抱歉您不得不浏览所有代码。提前致谢。
解决方法
我真的很抱歉浪费你们的时间,唯一的问题是有一个 MOCK_METHOD 的变体,它是 MOCK_CONST_METHOD(没有参数),它工作得很好。有没有其他方法可以像如果我们想编写非 const 方法的模拟,我们编写 MOCK_METHOD 而不是 MOCK_METHOD1 只是 args 更改,因此上述方法是否有任何其他此类变体以相同的方式工作
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。