测试用例必须断言已调用资源的方法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()不是virtual,所以

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


会从基类调用tagcache,而不是从模拟调用。

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

10-10 02:30