c++ Google测试运行两次

标签 c++ eclipse unit-testing googletest

我开始使用 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.

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

最佳答案

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

#include "SerialManagerTest.cpp"

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

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

关于c++ Google测试运行两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22013350/

相关文章:

unit-testing - 如何测试 setTimeout 是否被正确调用?

c++ - C++ 中的 SQLite char* 转换

c++ - 将数组中的对象向上移动

c++ - 如何在 QStyledItemDelegate 中绘制整行的背景?

Android eclipse 插件 - 无法在硬件设备上安装和运行构建

java - intellij idea默认如何排序导入?

javascript - setTimeout 测试未按预期运行

c++ - C++ 中 protobuf 消息的长度前缀

java - 从 Eclipse 中的编辑器中获取选定的 Java 元素

unit-testing - 在 Azure DevOps 中发布测试结果时如何包含 NUnit 测试输出?