gpt4 book ai didi

c++ - Googletest expect_call 不记录调用

转载 作者:行者123 更新时间:2023-11-28 01:35:39 26 4
gpt4 key购买 nike

测试用例应断言调用了资源的方法tagcache(),以确保更新资源的标签缓存。我知道调用了该方法,但测试失败,因为:

Expected: to be called at least once
Actual: never called - unsatisfied and active

但为什么呢?

void TagModel::tagResource(Tag *tag, Resource *r)
{
if ( tag ){ tag->addToResource(r); }
}

void Tag::addToResource(Resource *r)
{
if ( !r ){ return; }
addToResource(r->id());
r->tagcache()->add(this->id(),this->name());
}

class ResourceMock : public Resource
{
public:
MOCK_CONST_METHOD0(tagcache,TagCache *(void));
};

TEST(tagmodel,tag_resource){
TagModel m;
Tag *t = m.createTag("tag");
ResourceMock mockres;
EXPECT_CALL(mockres,tagcache()).Times(AtLeast(1));
m.tagResource(t,&mockres);
}

更新:资源定义

class Resource
{
mutable TagCache *tagcache_ = nullptr;
public:
virtual ~Resource(){
if ( tagcache_){ delete tagcache_; }
}
TagCache *tagcache() const{
if ( !tagcache_){
tagcache_ = new TagCache;
}
return tagcache_;
}
};

最佳答案

Resource::tagcache() 不是虚拟的,所以

ResourceMock mockres;
Resource *r = &mockres;
// [..]
r->tagcache()->add(this->id(),this->name());

将从基类中调用 tagcache,而不是从 mock 中调用。

关于c++ - Googletest expect_call 不记录调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49369495/

26 4 0
文章推荐: c++ - PlaySound 不工作
文章推荐: html - 当用户点击