如何使用 gmock 在具体 类 中模拟非虚拟方法?
How to mock Non-virtual Methods in concrete classes using gmock?
我以某种方式扩展了 donsoft.io's example 的 gmock 测试用例,并使其如下:
coinflipper/
├── BUILD
├── WORKSPACE
├── coinflipper.cc
├── coinflipper.h
├── rng.cc
└── rng.h
好吧,我把 Rng
class 作为 CoinFlipper
构造函数的参数,我在 CoinFlipper::flipCoin()
方法中初始化了它。
我想知道在这种情况下如何从 Rng
模拟 generate()
?
coinflipper.cc
#include "coinflipper.h"
#include <iostream>
CoinFlipper::CoinFlipper() {}
CoinFlipper::Result CoinFlipper::flipCoin() const {
Rng d_rng;
const double val = d_rng.generate(0.0, 1.0);
return (val < 0.5) ? HEADS : TAILS;
}
int main(int argc, char** argv) {
CoinFlipper cf;
CoinFlipper::Result res = cf.flipCoin();
if (res == 0) {
std::cout << "head" << std::endl;
} else {
std::cout << "tail" << std::endl;
}
return 0;
}
coinflipper.h
#include "rng.h"
class CoinFlipper {
public:
enum Result { HEADS = 0, TAILS = 1 };
explicit CoinFlipper();
Result flipCoin() const;
};
rng.h
#ifndef RNG_H
#define RNG_H
class Rng {
public:
Rng() {};
~Rng() {};
double generate(double min, double max);
};
#endif
rng.cc
#include "rng.h"
double Rng::generate(double min, double max) {
return 0.75; //Just for test
}
建造
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library")
cc_library(
name = "rng",
srcs = ["rng.cc"],
hdrs = ["rng.h"],
)
cc_binary(
name = "coinflipper",
srcs = ["coinflipper.cc", "coinflipper.h"],
deps = [
":rng",
],
)
cc_test(
name = "coinflipper_test",
size = "small",
srcs = ["coinflipper_test.cc", "rng.h","coinflipper.h","coinflipper.cc"],
deps = ["@com_google_googletest//:gtest_main"],
)
coinflipper_test.cc
#include "coinflipper.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
class MockRng {
public:
MOCK_METHOD2(generate, double(double, double));
};
TEST(CoinFlipper, ShouldReturnHeadsIfRandValueIsLessThanProbability) {
MockRng rng;
EXPECT_CALL(rng, generate(::testing::DoubleEq(0.0), ::testing::DoubleEq(1.0)))
.Times(::testing::Exactly(1))
.WillOnce(::testing::Return(0.25));
CoinFlipper coinFlipper;
auto result = coinFlipper.flipCoin<MockRng>(rng);
EXPECT_EQ(CoinFlipper::HEADS, result);
}
Bazel 输出:
$ bazel test --test_output=all //:coinflipper_test
DEBUG: Rule 'rules_cc' indicated that a canonical reproducible form can be obtained by modifying arguments sha256 = "56ac9633c13d74cb71e0546f103ce1c58810e4a76aa8325da593ca4277908d72"
DEBUG: Repository rules_cc instantiated at:
/Users/pvd/Downloads/toys/cpp/bazelgtest/coinflipper/WORKSPACE:9:13: in <toplevel>
Repository rule http_archive defined at:
/private/var/tmp/_bazel_pvd/3077b447e558b1418694504407cbcb45/external/bazel_tools/tools/build_defs/repo/http.bzl:336:31: in <toplevel>
DEBUG: Rule 'com_google_googletest' indicated that a canonical reproducible form can be obtained by modifying arguments sha256 = "5cf189eb6847b4f8fc603a3ffff3b0771c08eec7dd4bd961bfd45477dd13eb73"
DEBUG: Repository com_google_googletest instantiated at:
/Users/pvd/Downloads/toys/cpp/bazelgtest/coinflipper/WORKSPACE:3:13: in <toplevel>
Repository rule http_archive defined at:
/private/var/tmp/_bazel_pvd/3077b447e558b1418694504407cbcb45/external/bazel_tools/tools/build_defs/repo/http.bzl:336:31: in <toplevel>
INFO: Analyzed target //:coinflipper_test (0 packages loaded, 0 targets configured).
INFO: Found 1 test target...
FAIL: //:coinflipper_test (see /private/var/tmp/_bazel_pvd/3077b447e558b1418694504407cbcb45/execroot/__main__/bazel-out/darwin-fastbuild/testlogs/coinflipper_test/test.log)
INFO: From Testing //:coinflipper_test:
==================== Test output for //:coinflipper_test:
dyld: lazy symbol binding failed: Symbol not found: __ZN3Rng8generateEdd
Referenced from: /private/var/tmp/_bazel_pvd/3077b447e558b1418694504407cbcb45/sandbox/darwin-sandbox/72/execroot/__main__/bazel-out/darwin-fastbuild/bin/coinflipper_test.runfiles/__main__/coinflipper_test
Expected in: flat namespace
dyld: Symbol not found: __ZN3Rng8generateEdd
Referenced from: /private/var/tmp/_bazel_pvd/3077b447e558b1418694504407cbcb45/sandbox/darwin-sandbox/72/execroot/__main__/bazel-out/darwin-fastbuild/bin/coinflipper_test.runfiles/__main__/coinflipper_test
Expected in: flat namespace
================================================================================
Target //:coinflipper_test up-to-date:
bazel-bin/coinflipper_test
INFO: Elapsed time: 0.429s, Critical Path: 0.14s
INFO: 2 processes: 2 darwin-sandbox.
INFO: Build completed, 1 test FAILED, 2 total actions
//:coinflipper_test FAILED in 0.1s
/private/var/tmp/_bazel_pvd/3077b447e558b1418694504407cbcb45/execroot/__main__/bazel-out/darwin-fastbuild/testlogs/coinflipper_test/test.log
INFO: Build completed, 1 test FAILED, 2 total actions
定义依赖(这里的随机生成器)因为不推荐使用局部变量,做依赖注入比较困难(或者不可能),所以我把函数Rng_t
改成了模板函数并将 Rng 作为参数传递。
在实践中构造一个随机生成可能是一个繁重的工作,需要初始化它的内部状态,每次调用函数都构造它flipCoin
是浪费。
非虚函数是可以mock的,最常用的一种策略就是使用模板,这里我们把classCoinFlipper的成员函数做成模板函数,然后我们就可以测试依赖了MockRng
.
注意,对于模板函数,我们需要在头文件中定义成员函数。
coinflipper.h:
#pragma once
#include "rng.h"
class CoinFlipper {
public:
enum Result { HEADS = 0, TAILS = 1 };
template <typename Rng_t>
Result flipCoin(Rng_t& rng) {
const double val = rng.generate(0.0, 1.0);
return (val < 0.5) ? HEADS : TAILS;
}
};
测试文件部分,MockRng
现在不继承任何东西。我们在这里使用的测试成员函数的类型为 CoinFlipper::flipCoin<MockRng>
。对于生产代码:我们使用类型 CoinFlipper::flipCoin<Rng>
//#include "mockrng.h"
#include "coinflipper.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
class MockRng {
public:
MOCK_METHOD2(generate, double(double, double));
};
TEST(CoinFlipper, ShouldReturnHeadsIfRandValueIsLessThanProbability) {
MockRng rng;
EXPECT_CALL(rng, generate(::testing::DoubleEq(0.0), ::testing::DoubleEq(1.0)))
.Times(::testing::Exactly(1))
.WillOnce(::testing::Return(0.25));
CoinFlipper coinFlipper;
auto result = coinFlipper.flipCoin<MockRng>(rng);
EXPECT_EQ(CoinFlipper::HEADS, result);
}
在此处查看相关问题:
Mock non-virtual method C++ (gmock)
官方文档:
我以某种方式扩展了 donsoft.io's example 的 gmock 测试用例,并使其如下:
coinflipper/
├── BUILD
├── WORKSPACE
├── coinflipper.cc
├── coinflipper.h
├── rng.cc
└── rng.h
好吧,我把 Rng
class 作为 CoinFlipper
构造函数的参数,我在 CoinFlipper::flipCoin()
方法中初始化了它。
我想知道在这种情况下如何从 Rng
模拟 generate()
?
coinflipper.cc
#include "coinflipper.h"
#include <iostream>
CoinFlipper::CoinFlipper() {}
CoinFlipper::Result CoinFlipper::flipCoin() const {
Rng d_rng;
const double val = d_rng.generate(0.0, 1.0);
return (val < 0.5) ? HEADS : TAILS;
}
int main(int argc, char** argv) {
CoinFlipper cf;
CoinFlipper::Result res = cf.flipCoin();
if (res == 0) {
std::cout << "head" << std::endl;
} else {
std::cout << "tail" << std::endl;
}
return 0;
}
coinflipper.h
#include "rng.h"
class CoinFlipper {
public:
enum Result { HEADS = 0, TAILS = 1 };
explicit CoinFlipper();
Result flipCoin() const;
};
rng.h
#ifndef RNG_H
#define RNG_H
class Rng {
public:
Rng() {};
~Rng() {};
double generate(double min, double max);
};
#endif
rng.cc
#include "rng.h"
double Rng::generate(double min, double max) {
return 0.75; //Just for test
}
建造
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library")
cc_library(
name = "rng",
srcs = ["rng.cc"],
hdrs = ["rng.h"],
)
cc_binary(
name = "coinflipper",
srcs = ["coinflipper.cc", "coinflipper.h"],
deps = [
":rng",
],
)
cc_test(
name = "coinflipper_test",
size = "small",
srcs = ["coinflipper_test.cc", "rng.h","coinflipper.h","coinflipper.cc"],
deps = ["@com_google_googletest//:gtest_main"],
)
coinflipper_test.cc
#include "coinflipper.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
class MockRng {
public:
MOCK_METHOD2(generate, double(double, double));
};
TEST(CoinFlipper, ShouldReturnHeadsIfRandValueIsLessThanProbability) {
MockRng rng;
EXPECT_CALL(rng, generate(::testing::DoubleEq(0.0), ::testing::DoubleEq(1.0)))
.Times(::testing::Exactly(1))
.WillOnce(::testing::Return(0.25));
CoinFlipper coinFlipper;
auto result = coinFlipper.flipCoin<MockRng>(rng);
EXPECT_EQ(CoinFlipper::HEADS, result);
}
Bazel 输出:
$ bazel test --test_output=all //:coinflipper_test
DEBUG: Rule 'rules_cc' indicated that a canonical reproducible form can be obtained by modifying arguments sha256 = "56ac9633c13d74cb71e0546f103ce1c58810e4a76aa8325da593ca4277908d72"
DEBUG: Repository rules_cc instantiated at:
/Users/pvd/Downloads/toys/cpp/bazelgtest/coinflipper/WORKSPACE:9:13: in <toplevel>
Repository rule http_archive defined at:
/private/var/tmp/_bazel_pvd/3077b447e558b1418694504407cbcb45/external/bazel_tools/tools/build_defs/repo/http.bzl:336:31: in <toplevel>
DEBUG: Rule 'com_google_googletest' indicated that a canonical reproducible form can be obtained by modifying arguments sha256 = "5cf189eb6847b4f8fc603a3ffff3b0771c08eec7dd4bd961bfd45477dd13eb73"
DEBUG: Repository com_google_googletest instantiated at:
/Users/pvd/Downloads/toys/cpp/bazelgtest/coinflipper/WORKSPACE:3:13: in <toplevel>
Repository rule http_archive defined at:
/private/var/tmp/_bazel_pvd/3077b447e558b1418694504407cbcb45/external/bazel_tools/tools/build_defs/repo/http.bzl:336:31: in <toplevel>
INFO: Analyzed target //:coinflipper_test (0 packages loaded, 0 targets configured).
INFO: Found 1 test target...
FAIL: //:coinflipper_test (see /private/var/tmp/_bazel_pvd/3077b447e558b1418694504407cbcb45/execroot/__main__/bazel-out/darwin-fastbuild/testlogs/coinflipper_test/test.log)
INFO: From Testing //:coinflipper_test:
==================== Test output for //:coinflipper_test:
dyld: lazy symbol binding failed: Symbol not found: __ZN3Rng8generateEdd
Referenced from: /private/var/tmp/_bazel_pvd/3077b447e558b1418694504407cbcb45/sandbox/darwin-sandbox/72/execroot/__main__/bazel-out/darwin-fastbuild/bin/coinflipper_test.runfiles/__main__/coinflipper_test
Expected in: flat namespace
dyld: Symbol not found: __ZN3Rng8generateEdd
Referenced from: /private/var/tmp/_bazel_pvd/3077b447e558b1418694504407cbcb45/sandbox/darwin-sandbox/72/execroot/__main__/bazel-out/darwin-fastbuild/bin/coinflipper_test.runfiles/__main__/coinflipper_test
Expected in: flat namespace
================================================================================
Target //:coinflipper_test up-to-date:
bazel-bin/coinflipper_test
INFO: Elapsed time: 0.429s, Critical Path: 0.14s
INFO: 2 processes: 2 darwin-sandbox.
INFO: Build completed, 1 test FAILED, 2 total actions
//:coinflipper_test FAILED in 0.1s
/private/var/tmp/_bazel_pvd/3077b447e558b1418694504407cbcb45/execroot/__main__/bazel-out/darwin-fastbuild/testlogs/coinflipper_test/test.log
INFO: Build completed, 1 test FAILED, 2 total actions
定义依赖(这里的随机生成器)因为不推荐使用局部变量,做依赖注入比较困难(或者不可能),所以我把函数Rng_t
改成了模板函数并将 Rng 作为参数传递。
在实践中构造一个随机生成可能是一个繁重的工作,需要初始化它的内部状态,每次调用函数都构造它flipCoin
是浪费。
非虚函数是可以mock的,最常用的一种策略就是使用模板,这里我们把classCoinFlipper的成员函数做成模板函数,然后我们就可以测试依赖了MockRng
.
注意,对于模板函数,我们需要在头文件中定义成员函数。
coinflipper.h:
#pragma once
#include "rng.h"
class CoinFlipper {
public:
enum Result { HEADS = 0, TAILS = 1 };
template <typename Rng_t>
Result flipCoin(Rng_t& rng) {
const double val = rng.generate(0.0, 1.0);
return (val < 0.5) ? HEADS : TAILS;
}
};
测试文件部分,MockRng
现在不继承任何东西。我们在这里使用的测试成员函数的类型为 CoinFlipper::flipCoin<MockRng>
。对于生产代码:我们使用类型 CoinFlipper::flipCoin<Rng>
//#include "mockrng.h"
#include "coinflipper.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
class MockRng {
public:
MOCK_METHOD2(generate, double(double, double));
};
TEST(CoinFlipper, ShouldReturnHeadsIfRandValueIsLessThanProbability) {
MockRng rng;
EXPECT_CALL(rng, generate(::testing::DoubleEq(0.0), ::testing::DoubleEq(1.0)))
.Times(::testing::Exactly(1))
.WillOnce(::testing::Return(0.25));
CoinFlipper coinFlipper;
auto result = coinFlipper.flipCoin<MockRng>(rng);
EXPECT_EQ(CoinFlipper::HEADS, result);
}
在此处查看相关问题:
Mock non-virtual method C++ (gmock)
官方文档: