使用Google Test预期给定范围内的值

时间:2014-02-23 18:10:55

标签: c++ unit-testing googletest

我想指定一个值在上限和下限之间的期望值,包括在内。

Google Test提供LT,LE,GT,GE,但无法测试我能看到的范围。您可以使用EXPECT_NEAR并兼顾操作数,但在许多情况下,这并不像显式设置上限和下限那样清晰。

用法应该类似于:

EXPECT_WITHIN_INCLUSIVE(1, 3, 2); // 2 is in range [1,3]

如何添加这种期望?

6 个答案:

答案 0 :(得分:12)

Google mock拥有更丰富的可组合匹配器:

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

也许这对你有用。

答案 1 :(得分:5)

只使用Google Test(不是模拟),那么简单明了的答案就是:

EXPECT_TRUE((a >= 1) && (a <= 3)); // a is between 1 and 3 inclusive

我发现这比基于Mock的一些答案更具可读性。

---开始编辑 -

上面的简单答案没有提供任何有用的诊断

您可以使用AssertionResult定义一个自定义断言,它确实会产生一个有用的错误消息,如下所示。

#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));
}

答案 2 :(得分:3)

google mock cheat sheet中有一个很好的例子:

using namespace testing;
MATCHER_P2(IsBetween, a, b,
           std::string(negation ? "isn't" : "is") + " between " + PrintToString(a)
           + " and " + PrintToString(b))
{
    return a <= arg && arg <= b;
}

然后使用它:

TEST(MyTest, Name) {
    EXPECT_THAT(42, IsBetween(40, 46));
}

答案 3 :(得分:3)

我将定义这些宏:

#define EXPECT_IN_RANGE(VAL, MIN, MAX) \
    EXPECT_GE((VAL), (MIN));           \
    EXPECT_LE((VAL), (MAX))

#define ASSERT_IN_RANGE(VAL, MIN, MAX) \
    ASSERT_GE((VAL), (MIN));           \
    ASSERT_LE((VAL), (MAX))

答案 4 :(得分:1)

最后,我创建了一个宏来执行此操作,类似于Google Test lib中的其他宏。

#define EXPECT_WITHIN_INCLUSIVE(lower, upper, val) \
  do { \
    EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val, lower); \
    EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val, upper); \
  } while (0)

答案 5 :(得分:1)

Using an Existing Boolean Function在Google Test中不需要谷歌模拟。链接非常具体。

以下是示例。

// Returns true iff m and n have no common divisors except 1.
bool MutuallyPrime(int m, int n) { ... }
const int a = 3;
const int b = 4;
const int c = 10;
     

断言EXPECT_PRED2(MutuallyPrime,a,b);会成功,而   断言EXPECT_PRED2(MutuallyPrime,b,c);会失败的   消息

!MutuallyPrime(b, c) is false, where

b is 4

c is 10