title: Google Test and Google Mock do not work with extern global variables
body: <p>I am trying to use <code>google test</code> and <code>google mock</code> to test my simple C++ class. My mock class looks like this:</p>
  <pre><code>#pragma once
  
  #include &quot;base_classes/_HardwareSerial.h&quot;
  #include &quot;gmock/gmock.h&quot;
  
  class HardwareSerial : public _HardwareSerial
  {
  public:
      HardwareSerial() = default;
      MOCK_METHOD(void, begin, (unsigned long baud_rate), (override));
      MOCK_METHOD(void, end, (), (override));
      MOCK_METHOD(void, print, (const __FlashStringHelper *in_flash_str), (override));
      MOCK_METHOD(void, print, (const char *str), (override));
  };
  
  extern HardwareSerial Serial;
  </code></pre>
  <p>Now I make use of this mock class in my test cpp file:</p>
  <pre><code>#include &lt;gtest/gtest.h&gt;
  #include &lt;gmock/gmock.h&gt;
  #include &quot;HardwareSerial.h&quot;
  
  using ::testing::_;
  
  HardwareSerial Serial; // &lt;&lt;&lt; Putting this here does NOT work. The test passes whatever if the function has never been called called 10000 times. The test just passes.. This is the problem I have.
  
  HardwareSerial AnotherNewSerial; // &lt;&lt;&lt; Does NOT work.
  
  class Test_Class: public ::testing::Test
  {
  protected:
      HardwareSerial Serial; // &lt;&lt;&lt; Putting this here makes the test working, but of course if anything relies on the global extern variable will cause compilation error.
      HardwareSerial AnotherNewSerial; // &lt;&lt;&lt; Works.
  
      void SetUp() override
      {
      }
  
      void TearDown() override
      {
      }
  };
  
  TEST_F(Test_Class, MYTEST)
  {
      EXPECT_CALL(Serial, begin(_))
          .Times(10);
  }
  </code></pre>
  <p>Defining the external <code>HardwareSerial Serial</code> variable in the global area in my test causes that the test passes whatever I do with this variable. So my <code>EXPECT_CALL</code> just does not cause the test to fail without caring if the method <code>begin</code> was called or not. It just always passes!</p>
  <p>However, moving the declaration into the class makes the test work as expected. However, I cannot rely on this because I have other components rely on this global extern variable. And it is very interesting to know what is going on here and how I can fix this?</p>
  <h3>UPDATE:</h3>
  <p>It seems to have nothing to do with <code>extern</code>, declaring a new variable of type <code>HardwareSerial</code> in the global area causes exactly the same problem, and moving it into the classes removes the problem.</p>