【问题标题】:c++ Google Tests run twicec++ Google 测试运行两次
【发布时间】:2014-03-27 15:01:33
【问题描述】:

我开始使用 Google Test 对我的代码运行单元测试。我在 Ubuntu 12.04 上使用 Eclipse Kepler。

我在第一次测试中使用以下类:

AllTests.cpp

#include "gtest/gtest.h"
#include "SerialManagerTest.cpp"

int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

SerialManagerTest.cpp

#include "gtest/gtest.h"
#include "SerialManager.h"
#include "SerialInterface.h"
#include "FakeSerialHandler.h"

namespace {

TEST(TestingSerialManager, FirstTest) {
  SerialInterface *fakeSerialHandler=new FakeSerialHandler();
  SerialManager* serialManager=new SerialManager(fakeSerialHandler);
  ASSERT_TRUE(serialManager->OpenPort());

  delete serialManager;
}

TEST(TestingSerialManager, SecondTest) {
SerialInterface *fakeSerialHandler=new FakeSerialHandler();
SerialManager* serialManager=new SerialManager(fakeSerialHandler);
ASSERT_FALSE(!serialManager->OpenPort());

delete serialManager;
}
}

当我运行测试时,我得到了这个输出

[==========] Running 4 tests from 1 test case.
[----------] Global test environment set-up.
[----------] 4 tests from TestingSerialManager
[ RUN      ] TestingSerialManager.FirstTest
[       OK ] TestingSerialManager.FirstTest (0 ms)
[ RUN      ] TestingSerialManager.SecondTest
[       OK ] TestingSerialManager.SecondTest (0 ms)
[ RUN      ] TestingSerialManager.FirstTest
[       OK ] TestingSerialManager.FirstTest (0 ms)
[ RUN      ] TestingSerialManager.SecondTest
[       OK ] TestingSerialManager.SecondTest (0 ms)
[----------] 4 tests from TestingSerialManager (2 ms total)

[----------] Global test environment tear-down
[==========] 4 tests from 1 test case ran. (3 ms total)
[  PASSED  ] 4 tests.

为什么每个测试都被处理两次?

【问题讨论】:

  • 匿名命名空间看起来很可疑,没有它试过吗?
  • 是的。删除命名空间会导致 `TestingSerialManager_FirstTest_Test::test_info_' 的多个定义错误
  • 这正是你的问题,你的测试有多个定义,匿名命名空间只是通过给它们不同的名称来隐藏它。

标签: c++ eclipse unit-testing googletest


【解决方案1】:

为什么要在翻译单元中包含翻译单元?

#include "SerialManagerTest.cpp"

在某些情况下它有它的位置,但通常是一种不好的做法。

很可能发生的情况(没有看到您的命令行)是您的 SerialManagerTest 代码由于包含在最终可执行文件中而被链接两次。也就是说,它在AllTests.oSerialManagerTest.o 中重复,并且两个对象都链接到最终的测试可执行文件中。

【讨论】:

  • 改成#include "SerialManagerTest.hpp" 解决了
猜你喜欢
  • 2019-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-29
  • 2015-01-17
  • 1970-01-01
  • 2015-07-19
相关资源
最近更新 更多