Rework envMock
Instead of mocking all the functions, only mock std::getenv.
Now each test only needs to provide an EnvImpl that delegate calls to
mockEnv in order to inject dependencies on std::getenv. This for several
reasons:
1. Any call to env::getEnv() will be calling the real implementation of
the C++ code, and testing real code is better than testing mocks.
2. It is easier to write a fake class that takes a config string which
can greatly simplify test cases.
3. We can now write unit tests that ensure the number of times
std::getenv gets called (should be once, but multiple times right now).
Tested: unit tests still pass
Signed-off-by: Kun Yi <kunyi731@gmail.com>
Change-Id: I3e5aff7fa5d025de1b8ae798af43b97d31151ab9
diff --git a/test/env_unittest.cpp b/test/env_unittest.cpp
index 665f8a5..8e12e0e 100644
--- a/test/env_unittest.cpp
+++ b/test/env_unittest.cpp
@@ -5,28 +5,46 @@
#include <gmock/gmock.h>
#include <gtest/gtest.h>
+using ::testing::_;
using ::testing::Return;
using ::testing::StrEq;
-using ::testing::StrictMock;
+
+namespace env
+{
+
+// Delegate all calls to getEnv() to the mock
+const char* EnvImpl::get(const char* key) const
+{
+ return mockEnv.get(key);
+}
+
+EnvImpl env_impl;
+
+} // namespace env
+
+TEST(EnvTest, NonExistingEnvReturnsEmptyString)
+{
+ EXPECT_CALL(env::mockEnv, get(_)).WillOnce(Return(nullptr));
+ EXPECT_EQ(std::string(), env::getEnv("NonExistingKey"));
+}
TEST(EnvTest, EmptyEnv)
{
+ EXPECT_CALL(env::mockEnv, get(StrEq("AVERAGE_power1")))
+ .WillOnce(Return(nullptr));
EXPECT_FALSE(
phosphor::utility::isAverageEnvSet(std::make_pair("power", "1")));
}
TEST(EnvTest, ValidAverageEnv)
{
- StrictMock<EnvMock> eMock;
- envIntf = &eMock;
-
std::string power = "power";
std::string one = "1";
std::string two = "2";
- EXPECT_CALL(eMock, getEnv(StrEq("AVERAGE"), power, one))
+ EXPECT_CALL(env::mockEnv, get(StrEq("AVERAGE_power1")))
.WillOnce(Return("true"));
- EXPECT_CALL(eMock, getEnv(StrEq("AVERAGE"), power, two))
+ EXPECT_CALL(env::mockEnv, get(StrEq("AVERAGE_power2")))
.WillOnce(Return("bar"));
EXPECT_TRUE(phosphor::utility::isAverageEnvSet(std::make_pair(power, one)));