Expect a value within a given range using Google Test

c++, googletest, unit-testing

Solution

Google mock has richer composable matchers than google test alone:

#include "gmock/gmock.h"

using namespace ::testing;

// expect that x is >= 1 and <= 3
EXPECT_THAT(x, AllOf(Ge(1),Le(3)));

Maybe that would work for you.

See the googletest `matchers.md` document under the "Composite Matchers" section, here

Gabriel, I generally try to avoid introducing macros because they don't compose well and you end up with a proliferation of them. We should only really need ASSERT_THAT and EXPECT_THAT once we're using Matchers.

But that's not to say I don't value a built-in range check. I just wouldn't do it with macros. I would do it with a higher-level matcher. So:

--- UPDATE ---

For notational convenience, a function returning such a composite matcher can be easily written:

template <typename T>
auto IsInRange(T lo, T hi) {
    return AllOf(Ge((lo)), Le((hi))));
}

EXPECT_THAT(value, IsInRange(min, max));
ASSERT_THAT(value, IsInRange(min, max));

Problem

I want to specify an expectation that a value is between an upper and lower bound, inclusively. Google Test provides LT,LE,GT,GE, but no way of testing a range that I can see. You could use `EXPECT_NEAR` and juggle the operands, but in many cases this isn't as clear as explicitly setting upper and lower bounds. Usage should resemble: ``` EXPECT_WITHIN_INCLUSIVE(1, 3, 2); // 2 is in range [1,3] ``` How would one add this expectation?

Original source