Reputation: 1343
I somehow extended the gmock test case from donsoft.io's example, and made it as follows:
coinflipper/
├── BUILD
├── WORKSPACE
├── coinflipper.cc
├── coinflipper.h
├── rng.cc
└── rng.h
Well, instead put the Rng
class as a parameter of the constructor of the CoinFlipper
, I made it initialized inside the CoinFlipper::flipCoin()
method.
I was wondering how to mock the generate()
from Rng
in this case?
#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;
}
#include "rng.h"
class CoinFlipper {
public:
enum Result { HEADS = 0, TAILS = 1 };
explicit CoinFlipper();
Result flipCoin() const;
};
#ifndef RNG_H
#define RNG_H
class Rng {
public:
Rng() {};
~Rng() {};
double generate(double min, double max);
};
#endif
#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"],
)
#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 output:
$ 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
Upvotes: 0
Views: 875
Reputation: 6326
Define dependencies(The random generator here) as local variables are not recommended, it's much harder to do dependencies injection(Or it won't be possible), so I change the functions Rng_t
into template function and pass the Rng as a parameter.
In practice to construct a random generation may be heavy work, it needs to initialize its internal status, to construct it every time we call the function flipCoin
is waste.
The non-virtual function can be mocked, one most commonly used strategy is to use the template, here we make the class CoinFlipper's member function as a template function, then we can test the dependency with our MockRng
.
Be aware that for the template function, we need to define the member function in the header file.
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;
}
};
The test file part, MockRng
doesn't inherit anything now. And the test member function we use here has the type CoinFlipper::flipCoin<MockRng>
. For production code: we use the type 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);
}
See related question here:
Mock non-virtual method C++ (gmock)
The official document:
Upvotes: 1