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?
24 9 I'd like to write C++ Google tests which can use value-parameterized testswith multiple parameters of different data types, ideally matching the complexity of the following mbUnit tests written in C++/CLI. For an explanation of mbUnit, see the Hanselman 2006 article. As of this 2019 edit, the other links he includes are dead.
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.
When a test assertion such as EXPECT_EQ fails, googletest prints the argument values to help you debug. It does this using a user-extensible value printer. This printer knows how to print built-in C++ types, native arrays, STL containers, and any type that supports the << operator.
When a test assertion such as EXPECT_EQfails, Google Test prints the argument values to help you debug. It does this using a user-extensible value printer.
Google mock has richer composable matchers:
EXPECT_THAT(x, AllOf(Ge(1),Le(3)));
Maybe that would work for you.
Using just Google Test (not mock), then the simple, obvious answer is:
EXPECT_TRUE((a >= 1) && (a <= 3)); // a is between 1 and 3 inclusive
I find this more readable than some of the Mock based answers.
--- begin edit --
The simple answer above not providing any useful diagnostics
You can use AssertionResult
to define a custom assert that does produce useful a useful error message like this.
#include <gtest/gtest.h> ::testing::AssertionResult IsBetweenInclusive(int val, int a, int b) { if((val >= a) && (val <= b)) return ::testing::AssertionSuccess(); else return ::testing::AssertionFailure() << val << " is outside the range " << a << " to " << b; } TEST(testing, TestPass) { auto a = 2; EXPECT_TRUE(IsBetweenInclusive(a, 1, 3)); } TEST(testing, TestFail) { auto a = 5; EXPECT_TRUE(IsBetweenInclusive(a, 1, 3)); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With