Problem using ElementsAreArray with C-Style array

2,509 views
Skip to first unread message

Ken

unread,
Apr 16, 2015, 7:00:58 PM4/16/15
to googl...@googlegroups.com
Hi.  I am trying to use googlemock to test a parameter that is a c-style array.  I have looked at the CookBook and several posts on this group.  I've tried to base what I have done on those examples, but I keep getting the same compile error.
 
 
Here is a code snippet:
 
double doubleArray[] = {1.1, 2.2};
 
Matcher<double> expected_array_values[] =
{
   DoubleEq(1.1),
   DoubleEq(2.2)
};
 
EXPECT_CALL(mock_arrayUser, doubleArrayIn(ElementsAreArray(expected_array_values)));
The signature of doubleArrayIn is
void doubleArrayIn(double array[ ]) = 0;
 
The error I am getting says that in gmock-matchers.h, line 2873, error "double*" is not a class, struct or union type.  The error gets kicked off from line 3292 which is trying to instantiate ElementsAreArrayMatcher<T> as operator testing::Matcher<T>() const [with Container = double*, T = testing::Matcher<double>]
 
Any suggestions?
 
I am using GoogleMock 1.7.
 
Thanks!
 
Ken

Samuel Benzaquen

unread,
Apr 17, 2015, 12:22:33 PM4/17/15
to Ken, googl...@googlegroups.com
ElementsAre can't work with unsized arrays. It can't know its size, so it can't iterate it and compare them. It does work on sized arrays (like 'double array[N]').
Note that the 'Array' part of ElementsAreArray refers to the way you construct the matcher, not what it matches. It is still a variant of ElementAre.
I recommend using a custom matcher for that.
Something like:

MATCHER_P(AsVector, m, DescribeMatcher(m, negation)) {
  return ExplainMatchResult(m, std::vector<double>(arg, <some_hardcoded_size_you_know>), result_listener);
}
...
EXPECT_CALL(mock_arrayUser, doubleArrayIn(AsVector(ElementsAreArray(expected_array_values))));

The custom matcher is pretty much only providing that hardcoded size to the array. If there is not such a size, then I don't think you can do this safely.
_Sam

 
I am using GoogleMock 1.7.
 
Thanks!
 
Ken

--

---
You received this message because you are subscribed to the Google Groups "Google C++ Mocking Framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to googlemock+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/googlemock/bc9b46a8-8e0c-4832-883a-4863d8c7c25a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Greg

unread,
Jul 1, 2015, 12:56:35 PM7/1/15
to googl...@googlegroups.com
There is another way to do it, but it also requires to pass the array size:

class Mock
{
  public:
    MOCK_METHOD4(func, void(int, const std::string&, int *array, int arraySize));
}

TEST(MockTest, Array)
{
    Mock mock;
    EXPECT_CALL(mock, func(1, "test", _, _))
        .With(Args<2, 3>(ElementsAre(1, 2, 3)));
Reply all
Reply to author
Forward
0 new messages