1 #include "utils/conversion.hpp" 2 3 #include <gmock/gmock.h> 4 5 using namespace testing; 6 7 class TestConversion : public Test 8 { 9 public: 10 enum class Enum 11 { 12 zero = 0, 13 one, 14 two 15 }; 16 17 Enum toEnum(int x) 18 { 19 return utils::toEnum<Enum, Enum::zero, Enum::two>(x); 20 } 21 22 Enum stringToEnum(const std::string& value) 23 { 24 return utils::stringToEnum(convDataEnum, value); 25 } 26 27 std::string enumToString(Enum value) 28 { 29 return std::string(utils::enumToString(convDataEnum, value)); 30 } 31 32 static constexpr std::array<std::pair<std::string_view, Enum>, 3> 33 convDataEnum = { 34 {std::make_pair<std::string_view, Enum>("zero", Enum::zero), 35 std::make_pair<std::string_view, Enum>("one", Enum::one), 36 std::make_pair<std::string_view, Enum>("two", Enum::two)}}; 37 }; 38 39 TEST_F(TestConversion, passValueInRangeExpectToGetValidOutput) 40 { 41 EXPECT_EQ(toEnum(0), Enum::zero); 42 EXPECT_EQ(toEnum(2), Enum::two); 43 } 44 45 TEST_F(TestConversion, passInvalidValueExpectToThrowOutOfRangeException) 46 { 47 EXPECT_THROW(toEnum(-1), std::out_of_range); 48 EXPECT_THROW(toEnum(3), std::out_of_range); 49 } 50 51 TEST_F(TestConversion, convertsToUnderlyingType) 52 { 53 EXPECT_THAT(utils::toUnderlying(Enum::one), Eq(1)); 54 EXPECT_THAT(utils::toUnderlying(Enum::two), Eq(2)); 55 EXPECT_THAT(utils::toUnderlying(Enum::zero), Eq(0)); 56 } 57 58 TEST_F(TestConversion, convertsEnumToString) 59 { 60 EXPECT_THAT(enumToString(Enum::one), Eq("one")); 61 EXPECT_THAT(enumToString(Enum::two), Eq("two")); 62 EXPECT_THAT(enumToString(Enum::zero), Eq("zero")); 63 } 64 65 TEST_F(TestConversion, convertsStringToEnum) 66 { 67 EXPECT_THAT(stringToEnum("one"), Eq(Enum::one)); 68 EXPECT_THAT(stringToEnum("two"), Eq(Enum::two)); 69 EXPECT_THAT(stringToEnum("zero"), Eq(Enum::zero)); 70 } 71 72 TEST_F(TestConversion, enumToStringThrowsWhenUknownEnumPassed) 73 { 74 EXPECT_THROW(enumToString(static_cast<Enum>(77)), std::out_of_range); 75 } 76 77 TEST_F(TestConversion, stringToEnumThrowsWhenUknownStringPassed) 78 { 79 EXPECT_THROW(stringToEnum("four"), std::out_of_range); 80 } 81