简体   繁体   English

如何使用谷歌测试测试 class?

[英]How to test a class with google test?

I'm just learning google test, I have a class and I want to test its member function, below is the demo code:我只是在学习谷歌测试,我有一个class ,我想测试它的成员 function,下面是演示代码:

class B {
    //......
};
class A {
public:
    //.....
    void add (string s, B* ptrb) { m.insert(s, ptrb); }
    void remove(string s) { 
        auto it = m.find(s);
        if (it != m.end())
            m.erase(it); 
    }
    B* operator[](string s)
    {
        auto it = m.find(s);
        if (it != m.end())
            return (*it).second;
    }
    //.....
protected:
    map<B*> m;
    //.....
}

if I want to test add like this:如果我想像这样测试add

class mygtest : public ::testing::Test
{
protected:
    //....setup
    //....teardown
    A a;
};

TEST_F(mygtest, testadd)
{
    B b1;
    B b2;
    a.add("1", &b1);
    a.add("2", &b2);
    //...how should i do next?
    EXPECT_EQ(.....) //compare with who?
}

this is the first question.这是第一个问题。

the second question is:第二个问题是:

In some conditions, I have to call another member function to get a value first, and use EXPECT_EQ to test the current member function, how to test a function without using other member funtion?在某些情况下,我必须先调用另一个成员 function 来获取值,然后使用EXPECT_EQ测试当前成员 function,如何在没有其他成员功能的情况下测试 ZC1C425268E68385D14AB5074C17Z9? if it's necessary ?如果有必要?

You have to just verify that state of A has changed as desired.您只需验证A state 是否已根据需要更改。 So just check if it contains added objects.所以只需检查它是否包含添加的对象。

TEST_F(mygtest, testadd)
{
    B b1;
    B b2;
    a.add("1", &b1);
    a.add("2", &b2);

    EXPECT_EQ(a["1"], &b1);
    EXPECT_EQ(a["2"], &b2);
    EXPECT_EQ(a["3"], nullptr);
}

https://godbolt.org/z/ezrjdY6hh https://godbolt.org/z/ezrjdY6hh

Since there is not enough context it is impossible o improve this test (it doesn't look nice).由于没有足够的上下文,所以不可能改进这个测试(它看起来不太好)。

You can't avoid use of different functions.您无法避免使用不同的功能。 You are testing behavior of a class.您正在测试 class 的行为。 So you are verify that other function do something else after state has been changed.因此,您要验证其他 function 在 state 更改后是否执行其他操作。

Do not event think to friend a test with production class.不要想用生产 class 给朋友做个测试。 This is bad practice, since this will entangle test with implementation details.这是不好的做法,因为这会使测试与实现细节纠缠在一起。 You will no be able refactor production code when test check implementation detail.在测试检查实现细节时,您将无法重构生产代码。

Here is small refactoring of test I usually do to improve how easy test is maintained: https://godbolt.org/z/Tc1n9Evzs这是我通常对测试进行的小型重构,以提高测试的维护难度:https://godbolt.org/z/Tc1n9Evzs

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

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