【问题标题】:how can I set one pointer attribute so that it can call a function for an EXPECT_CALL?如何设置一个指针属性,以便它可以调用 EXPECT_CALL 的函数?
【发布时间】:2020-08-21 02:43:56
【问题描述】:
class Parent
{
public:
int* x;
};
//is I am trying to make an object of type parent, it results: waiting for specifier after new *
class Child:public Parent
{

void Func()
{
   <//DO SOMETHING>
}
};

//Unit test using mock
std::shared_pointer<Child> y =std::make_shared<Mock>();
//set_pointer(y);** //how this can be implemented
EXPECT_CALL(*(std::dynamic_pointer_cast<Mock>(y)).get(),Func()).Times(1);//this test is failed 

【问题讨论】:

  • 我不明白你在做什么。创建Parent 类型的对象有什么问题? set_pointer 应该做什么?为什么你需要dynamic_pointer_cast 而不是让y 成为std::shared_ptr&lt;Mock&gt; 类型?
  • 我正在尝试将 x 设置为 y 的值,并且在期望调用时收到 sgm 错误

标签: c++ unit-testing pointers inheritance googlemock


【解决方案1】:

如果您的目标是设置 x 指针作为调用 Func 的结果,您可以使用 Invoke 和自定义 lambda:

class Parent {
public:
    // most probably this needs a virt. dtor, but if shared_ptrs are to be used, it might be OK
    int* x;
};

class Child : public Parent {
public:
    virtual void Func() {
        //<//DO SOMETHING>
    }
};

class ChildMock : public Child {
public:
    MOCK_METHOD0(Func, void());
};

TEST(ChildMock, some_test_name) {
    // Unit test using mock
    std::shared_ptr<Child> y = std::make_shared<ChildMock>();
    // set_pointer(y);** //this lambda allows to set the vaule of x -----------------
    int some_x = 42;     //                                                         |
    EXPECT_CALL(*(std::dynamic_pointer_cast<ChildMock>(y)), Func()).WillOnce(Invoke([&y,&some_x](){
        y->x = &some_x;
    }));
    y->Func();
    ASSERT_EQ(42, *y->x);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-04
    • 1970-01-01
    • 2017-05-20
    • 2013-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    相关资源
    最近更新 更多