简体   繁体   中英

c++ Google Tests run twice

I'm starting to use Google Test to run unit tests on my code. I use Eclipse Kepler over Ubuntu 12.04.

I'm using the following classes on this first test:

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;
}
}

When I run the tests I get this output

[==========] 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.

Why each test is being processed twice?

Why do you include a translation unit in a translation unit?

#include "SerialManagerTest.cpp"

It has its place in some cases, but usually is a bad practice.

What very likely happens (without seeing your command line), is that your SerialManagerTest code is linked twice because of the include in the final executable. That is, it is duplicated in AllTests.o and SerialManagerTest.o , and both objects are linked into the final test executable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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