I have a unit test that validates whether certain member values (valueA
, valueB
) equate to 0 or not. And the object being tested i.e Object
is a template and what I am looking to accomplish is to:
wrap the validation part in a function so instead of invoking EXPECT_NE/EXPECT_EQ
for each member value, I just invoke a function that takes care of the validation
This is the original snippet:
template<typename T>
struct Object
{
struct Values
{
int valueA;
int valueB;
};
Values values = {};
T otherStuff;
void setValues(int valueA, int valueB)
{
values.valueA = valueA;
values.valueB = valueB;
}
};
TEST(UnitTest, testA)
{
Object<int> object;
// do stuff that modified object's values via setValues()
EXPECT_NE(object.values.valueA, 0);
EXPECT_EQ(object.values.valueB, 0);
}
Following is what I came up with but I get the following error
gmock-matchers.h:2074:31: error: no matching function for call to 'testing::internal::FieldMatcher<Object<int>::Values, int>::MatchAndExplainImpl(std::integral_constant<bool, false>::type, const Object<int>&, testing::MatchResultListener*&) const'
2074 | return MatchAndExplainImpl(
| ~~~~~~~~~~~~~~~~~~~^
2075 | typename std::is_pointer<typename std::remove_const<T>::type>::type(),
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2076 | value, listener);
If I were to use a member variable outside of a struct i.e testVar
in MatchesStruct
, it would compile fine. Why the complain with struct member?
using ::testing::Eq;
using ::testing::Ne;
using ::testing::Field;
using ::testing::AllOf;
template<typename T>
struct Object
{
int testVar;
struct Values
{
int valueA;
int valueB;
};
Values values = {};
T otherStuff;
void setValues(int valueA, int valueB)
{
values.valueA = valueA;
values.valueB = valueB;
}
};
template <typename T, class M1, class M2>
auto MatchesStruct(M1 m1, M2 m2)
{
return AllOf(Field(&Object<T>::Values::valueA, m1),
Field(&Object<T>::Values::valueB, m2));
}
TEST(UnitTest, testA)
{
Object<int> object;
// do stuff that modified object's values via setValues()
EXPECT_THAT(object, MatchesStruct<int>(Ne(0), Eq(0)));
}
Here's a live sample