简体   繁体   English

如何使用std :: function在Google测试中测试方法?

[英]How to test method in google test, using std::function?

I would like to test method "methodToTest" in class A: 我想在A类中测试方法“ methodToTest”:

typedef std::function F_global; typedef std :: function F_global;

struct A
{
    F_global m_F_global;

    A(F_global m_F_global) : p_F_global(m_F_global) {}

    void methodToTest()
    {
        m_F_global(5);
    }
};

I have got a mock class: 我有一个模拟课:

class RunMock { public: MOCK_METHOD1(run, void (int)); 类RunMock {public:MOCK_METHOD1(run,void(int)); }; };

Below I have got a test case: 下面我有一个测试用例:

class TestClass : public testing::Test
{
protected:
    void SetUp();

    std::unique_ptr<A> m_aa;
    std::unique_ptr<RunMock> m_runMock;
};

void UecSimplePortTestSuite::SetUp()
{
    m_aa = make_unique<A>(m_runMock->run);//IT DOESN'T WORK I DON'T KNOW HOW TO FORWARD A METHOD run from RunMock to constructor
}

TEST_F(UecSimplePortTestSuite, testForwardMessage)
{
    EXPECT_CALL(*m_runMock, run(_));
    m_aa->methodToTest();
}

Generally I don't know how transfer a method "run" from Mock class "RunMock" in "UecSimplePortTestSuite::SetUp()". 通常,我不知道如何从“ UecSimplePortTestSuite :: SetUp()”中的Mock类“ RunMock”转移方法“ run”。 I would like to do this, because I would like to "EXPECT_CALL(*m_runMock, run(_));" 我想这样做,因为我想“ EXPECT_CALL(* m_runMock,run(_));” in UecSimplePortTestSuite.testForwardMessage to test "methodToTest()". 在UecSimplePortTestSuite.testForwardMessage中测试“ methodToTest()”。 I think that good idea could be to use lmbda, std::boost::bind or something like this. 我认为,好主意可能是使用lmbda,std :: boost :: bind或类似的东西。

You can pass a lambda to the constructor of A in the SetUp() : 您可以在SetUp()中将lambda传递给A的构造函数:

m_runMock.reset( new RunMock );
m_aa.reset( new A( [&](int value){ m_runMock->run(value); } );

This : 这个 :

m_runMock->run

is not going to do what you thing, and it is a compilation error. 不会做什么,这是编译错误。 You can read this parashift QA and here how to use pointer to member function. 您可以阅读此parashift质量检查以及此处如何使用指向成员函数的指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM