Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expect a value within a given range using Google Test

Tags:

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?

like image 338
Drew Noakes Avatar asked Feb 23 '14 18:02

Drew Noakes


People also ask

Is it possible to write value-parameterized Google tests in C++?

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.

Is there a way to test a range in Google Test?

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.

How does googletest debug expect_EQ?

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.

What is expect_eqfails in Google Test?

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.


2 Answers

Google mock has richer composable matchers:

EXPECT_THAT(x, AllOf(Ge(1),Le(3))); 

Maybe that would work for you.

like image 134
Billy Donahue Avatar answered Sep 19 '22 17:09

Billy Donahue


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)); } 
like image 28
Daniel Avatar answered Sep 18 '22 17:09

Daniel