I just found a nicer solution which I wanted to share, but Andre Holzner already proposed it in this answer.
That solution has all the pros of mine but none of the cons. And it is also more flexible as it supports matchers, so you can do stuff like this:
EXPECT_THAT(someString, AnyOf(StartsWith("foo"), StartsWith("bar")));
This will give an output similar to this (created with GTest 1.10)
error: Value of: someString
Expected: (starts with "foo") or (starts with "bar")
Actual: "baz"
You can use EXPECT_THAT()
in combination with a container and the Contains()
matcher to achieve this:
EXPECT_THAT((std::array{ Value1, Value2 }), Contains(TestValue));
Note that the braces after array
are needed for list initialization and the parentheses around array
are needed, because macros (such as EXPECT_THAT()
) do not understand braces and would otherwise interpret the two arguments as three arguments.
This will give an output similar to this (created with GTest 1.10)
error: Value of: (std::array{ Value1, Value2 })
Expected: contains at least one element that is equal to 42
Actual: { 12, 21 }
Pro:
- Prints all values
- one-liner
- works out of the box
Con:
- Finding the value of
TestValue
in the output is not easy
- Syntax is not straight forward
- Modern compiler features are needed
- C++11 is needed due to
std::array
and list initialization (still not available everywhere)
- C++17 is needed due to CTAD, use
std::initializer_list<T>{ ... }
on C++11/14. Alternatively a free function can be used to deduce size and type of the array.
gmock/gmock.h
instead of or in addition togtest/gtest.h
– Sought