-1

Unlike the question in Gmock - matching structures, I'm wondring how I could create a matcher for a struct with >2 members. Let's say I've got a structure of 8 members, and that MyFun() takes a pointer to a SomeStruct_t as an argument.

typedef struct
{
  int data_1;
  int data_2;
  int data_3;
  int data_4;
  int data_5;
  int data_6;
  int data_7;
  int data_8;
} SomeStruct_t;

SomeStruct_t my_struct;

EXPECT_CALL(*myMock, MyFun(MyMatcher(my_struct)));

Do you have any suggestions/examples on how MyMatcher should be implemented? Or, could I solve this without using a matcher? I'd like to check each element of my_struct.

273K
  • 29,503
  • 10
  • 41
  • 64
jack_h
  • 1
  • 1

2 Answers2

1

You own answer is ok, but there is better way to do it. It is good practice to provide stream operator or PrintTo function for better readability of gtest logs.

And it is possible to force GTest print better messages for a matcher in case of failure.

using testing::AllOf;
using testing::ExplainMatchResult;
using testing::Field;
using testing::Not;

std::ostream& operator<<(std::ostream&  out, const SomeStruct_t& data)
{
    return out << '{' 
        << data.data_1 << ','
        << data.data_2 << ','
        << data.data_3 << ','
        << data.data_4 << ','
        << data.data_5 << ','
        << data.data_6 << ','
        << data.data_7 << ','
        << data.data_8 << '}';
}

MATCHER_P(MyMatcher, myStruct, "")
{
    return ExplainMatchResult(
        AllOf(Field("data_1", &SomeStruct_t::data_1, myStruct.data_1),
              Field("data_2", &SomeStruct_t::data_2, myStruct.data_2),
              Field("data_3", &SomeStruct_t::data_3, myStruct.data_3),
              Field("data_4", &SomeStruct_t::data_4, myStruct.data_4),
              Field("data_5", &SomeStruct_t::data_5, myStruct.data_5),
              Field("data_6", &SomeStruct_t::data_6, myStruct.data_6),
              Field("data_7", &SomeStruct_t::data_7, myStruct.data_7),
              Field("data_8", &SomeStruct_t::data_8, myStruct.data_8)),
              arg, result_listener);
}

This kind of litle afford pays of a lot later when test detects some problem.

Live demo

Marek R
  • 32,568
  • 6
  • 55
  • 140
0
MATCHER_P(MyMatcher, MyStruct, "arg struct does not match expected struct")
{
  return (arg.data_1 == MyStruct.data_1) && (arg.data_2 == MyStruct.data_2)  &&
    (arg.data_3 == MyStruct.data_3)  && (arg.data_4 == MyStruct.data_4)  &&
    (arg.data_5 == MyStruct.data_5)  && (arg.data_6 == MyStruct.data_6)  &&
    (arg.data_7 == MyStruct.data_7) && (arg.data_8 == MyStruct.data_8);
}

This solved my problem. Though it would be nice with more examples in the gmock documentaion.

jack_h
  • 1
  • 1