【问题标题】:Is using FRIEND_TEST the right thing to do?使用 FRIEND_TEST 是否正确?
【发布时间】:2012-10-27 07:39:38
【问题描述】:

当我在 https://github.com/google/googletest/blob/master/googletest/include/gtest/gtest_prod.h 查看 FRIEND_TEST 的实现时,我看到以下内容:

#ifndef GTEST_INCLUDE_GTEST_GTEST_PROD_H_
#define GTEST_INCLUDE_GTEST_GTEST_PROD_H_
// When you need to test the private or protected members of a class,
// use the FRIEND_TEST macro to declare your tests as friends of the
// class.  For example:
//
// class MyClass {
//  private:
//   void MyMethod();
//   FRIEND_TEST(MyClassTest, MyMethod);
// };
//
// class MyClassTest : public testing::Test {
//   // ...
// };
//
// TEST_F(MyClassTest, MyMethod) {
//   // Can call MyClass::MyMethod() here.
// }
#define FRIEND_TEST(test_case_name, test_name)\
friend class test_case_name##_##test_name##_Test
#endif 

如果我的理解是正确的,测试类是无条件地成为生产类的孩子。这将使生产类依赖于测试类。实际上,生产代码也将包含我的测试库。

我不确定这是否是正确的做法。

我在这里遗漏了什么还是应该仅按条件编译?

谢谢。

【问题讨论】:

    标签: c++ googletest


    【解决方案1】:

    我不是那样读的。如果你愿意,你可以让一个不存在的类成为你的生产类的朋友。它是无害的,而且它肯定不会引入依赖项或将测试代码添加到您的生产代码中。

    class Production
    {
       friend class WibbleWibble;
       ...
    };
    

    即使 WibbleWibble 不存在,此代码也是完全正确的。所以没有依赖关系。

    【讨论】:

    • 其实依赖是反过来的。通过使测试类成为生产类的朋友,您使测试类依赖于生产类的实现。这并不理想,但我想有时在现实世界中需要它。
    猜你喜欢
    • 2014-02-08
    • 2021-10-30
    • 2016-01-24
    • 2014-05-15
    • 2010-12-31
    • 2019-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多