GMock: How to return mock class variable as the return value - c++

I am trying to use GMock (google mocking framework for c++) for the first time. I have the following class:
class LocalCache
{
public:
virtual time_t GetCurrentTime() = 0;
virtual int AddEntry(const std::string key, std::string& value);
virtual int GetEntry(const std::string key, std::string& value);
};
The GetEntry method invokes GetCurrentTime call. I'd like to mock the GetCurrentTime method so that I can advance the clock in my test to test the aging out of entries which happens as part of the GetEntry call (please don't ask me why the aging is being done as part of GetEntry call... that's another discussion :( ). Here's my mock class:
class MockLocalCache : public LocalCache
{
public:
using LocalCache::GetCurrentTime;
MOCK_METHOD0(GetCurrentTime, time_t());
MockLocalCache()
: mCurrentTime(0)
{
}
void EnableFakeTime()
{
ON_CALL(*this, GetCurrentTime()).WillByDefault(Return(mCurrentTime));
}
void SetTime(time_t now) { mCurrentTime = now; }
private:
time_t mCurrentTime;
};
TEST(MockTest, TimeTest)
{
MockLocalCache mockCache;
mockCache.EnableFakeTime();
std::string key("mykey");
std::string value("My Value");
EXPECT_TRUE(mockCache.AddEntry(key, value));
mockCache.SetTime(10); // advance 10 seconds
std::string expected;
EXPECT_TRUE(mockCache.GetEntry(key, expected));
}
When I run the test, I expected the mCurrentTime value to be return by my mock GetCurrentTime function. However, I get the following error output:
GMOCK WARNING:
Uninteresting mock function call - taking default action specified at:
..../test_local_cache.cpp:62:
Function call: GetCurrentTime()
Returns: 0
Stack trace:
Would appreciate it if someone can let me know what I am doing wrong and how to fix it. Thanks in advance.

The solution to your problem is to make it in much simpler way. Just use EXPECT_CALLwhere you expect call to your mocked function:
class MockLocalCache : public LocalCache
{
public:
MOCK_METHOD0(GetCurrentTime, time_t());
};
TEST(MockTest, TimeTest)
{
MockLocalCache mockCache;
std::string key("mykey");
std::string value("My Value");
EXPECT_TRUE(mockCache.AddEntry(key, value));
EXPECT_CALL(mockCache, GetCurrentTime()).WillOnce(Return(10)); // advance 10 seconds
std::string expected;
EXPECT_TRUE(mockCache.GetEntry(key, expected));
}
Just to answer why your example did not work - with this call, the current value of your member variable is stored - later change to it has no effect:
ON_CALL(*this, GetCurrentTime()).WillByDefault(Return(mCurrentTime));
Look in google-mock-doc for difference between Return and Return(ByRef...
Probably - I did not check this, calling set member value, before calling setting this default would also work - but as I said - for your case EXPECT_CALL shall be used:
mockCache.SetTime(10); // advance 10 seconds
mockCache.EnableFakeTime();

Just for the record (and future people finding this question, like me), while PiotrNycz's answer is the best option when you can do it (keeping test values directly within tests) -- in some cases it really is necessary to return a "live" return value from a field or variable.
The appropriate documentation is here; in particular:
Return(field) doesn't work (it makes a copy of the field's current value when the action is defined)
Return(ByRef(field)) also doesn't work (it does exactly the same as above, contrary to what you might expect)
ReturnRef(field) doesn't compile (because the return type isn't a reference)
ReturnPointee(&field) does work (it returns the value as of the time the method is actually called)
Of course, you have to ensure that the pointee remains valid whenever the method is called, since it's now being used directly instead of making a copy.

Related

What's the proper way to have a Task that calls an arbitrary function with a known, specific return type?

I have a value which is expensive to calculate and can be asked for ahead of time--something like a lazily initiated value whose initialization is actually done at the moment of definition, but in a different thread. My immediate thought was to use parallelism.-Task seems purpose-built for this exact use-case. So, let's put it in a class:
class Foo
{
import std.parallelism : Task,task;
static int calculate(int a, int b)
{
return a+b;
}
private Task!(calculate,int,int)* ourTask;
private int _val;
int val()
{
return ourTask.workForce();
}
this(int a, int b)
{
ourTask = task!calculate(a,b);
}
}
That seems all well and good... except when I want the task to be based on a non-static method, in which case I want to make the task a delegate, in which case I start having to do stuff like this:
private typeof(task(&classFunc)) working;
And then, as it turns out, typeof(task(&classFunc)), when it's asked for outside of a function body, is actually Task!(run,ReturnType!classFunc function(Parameters!classFunc))*, which you may notice is not the type actually returned by runtime function calls of that. That would be Task!(run,ReturnType!classFunc delegate(Parameters!classFunc))*, which requires me to cast to typeof(working) when I actually call task(&classFunc). This is all extremely hackish feeling.
This was my attempt at a general template solution:
/**
Provides a transparent wrapper that allows for lazy
setting of variables. When lazySet!!func(args) is called
on the value, the function will be called in a new thread;
as soon as the value's access is attempted, it'll return the
result of the task, blocking if it's not done calculating.
Accessing the value is as simple as using it like the
type it's templated for--see the unit test.
*/
shared struct LazySet(T)
{
/// You can set the value directly, as normal--this throws away the current task.
void opAssign(T n)
{
import core.atomic : atomicStore;
working = false;
atomicStore(_val,n);
}
import std.traits : ReturnType;
/**
Called the same way as std.parallelism.task;
after this is called, the next attempt to access
the value will result in the value being set from
the result of the given function before it's returned.
If the task isn't done, it'll wait on the task to be done
once accessed, using workForce.
*/
void lazySet(alias func,Args...)(Args args)
if(is(ReturnType!func == T))
{
import std.parallelism : task,taskPool;
auto t = task!func(args);
taskPool.put(t);
curTask = (() => t.workForce);
working = true;
}
/// ditto
void lazySet(F,Args...)(F fpOrDelegate, ref Args args)
if(is(ReturnType!F == T))
{
import std.parallelism : task,taskPool;
auto t = task(fpOrDelegate,args);
taskPool.put(t);
curTask = (() => t.workForce);
working = true;
}
private:
T _val;
T delegate() curTask;
bool working = false;
T val()
{
import core.atomic : atomicStore,atomicLoad;
if(working)
{
atomicStore(_val,curTask());
working = false;
}
return atomicLoad(_val);
}
// alias this is inherently public
alias val this;
}
This lets me call lazySet using any function, function pointer or delegate that returns T, and then it'll calculate the value in parallel and return it, fully calculated, next time anything tries to access the underlying value, exactly as I wanted. Unit tests I wrote to describe its functionality pass, etc., it works perfectly.
But one thing's bothering me:
curTask = (() => t.workForce);
Moving the Task around by way of creating a lambda on-the-spot that happens to have the Task in its context still seems like I'm trying to "pull one over" on the language, even if it's less "hackish-feeling" than all the casting from earlier.
Am I missing some obvious language feature that would allow me to do this more "elegantly"?
Templates that take an alias function parameter (such as the Task family) are finicky regarding their actual type, as they can receive any type of function as parameter (including in-place delegates that get inferred themselves). As the actual function that gets called is part of the type itself, you would have to pass it to your custom struct to be able to save the Task directly.
As for the legitimacy of your solution, there is nothing wrong with storing lambdas to interact with complicated (or "hidden") types later.
An alternative is to store a pointer to &t.workForce directly.
Also, in your T val() two threads could enter if(working) at the same time, but I guess due to the atomic store it wouldn't really break anything - anyway, that could be fixed by core.atomic.cas.

Globally check value in mock

I have a mock that represents an API wrapper.
class MockApiWrapper : public ApiWrapper {
public:
MockNrfWrapper();
virtual ~MockNrfWrapper();
MOCK_METHOD1(api_do, void(int param));
};
Lets assume that api_do should never be called with param = 0. Since I use this mock "everywhere", I would like to append an assertion/expect to each call made to api_do. Example:
void MyClass::InvalidCallsToApi(void) {
// api->api_do(0); // Fails "global assert"
// api->api_do(1); // Fails by specific test
api->api_do(2); // Valid call
}
TEST(MyTestCase, FirstTest) {
// Mock always checks that api_do is not called
// with argument of 0
EXPECT_CALL(api, api_do(Ne(1));
uut->InvalidCallsToApi();
}
I tried doing this with an ON_CALL and Invoke in the constructor, but either it was overridden by the added EXPECT in the test, or I got compilation error (couldn't do ASSERT or EXPECT in invoked call).
I hope my problem statement is clear. Thanks in advance for any input!
I've came up with one solution, it's not the nicest, but acceptable IMO.
Code:
struct BInterface {
virtual void foo(int) = 0;
};
struct BMock : public BInterface {
MOCK_METHOD1(foo, void(int));
BMock() {
ON_CALL(*this, foo(0))
.WillByDefault(::testing::InvokeWithoutArgs([](){ADD_FAILURE() << "This function can't be called with argument 0";}));
}
};
void testedMethod(int a) {
BInterface* myB = new BMock;
myB->foo(a);
delete myB;
}
TEST(myTest, okCase) {
testedMethod(1);
}
TEST(myTest, notOkCase) {
testedMethod(0);
}
Explanation:
We add a default action to BMock, for every call of foo method with argument 0.
In this action, we call a lambda, which uses GTest macro ADD_FAILURE() to generate a non-fatal fail - equivalent of EXPECT_* macros. You can use FAIL() instead for a fatal failure like in ASSERT_* macros.
We use ON_CALL macro in mock's constructor, which allows to avoid calling it with every other mock object.
Limitations:
The same trick won't work with EXPECT_CALL for example - I don't know GMock implementaion, but I assume EXPECT_CALL requires a fully initialized object.
A call with matcher that accepts 0 will still pass (i.e. EXPECT_CALL(myB, foo(::testing::_));, but that's the case in every other GMock expectations. GMock will always shadow older expectations when newer ones are encountered. You have to create your expectations in such a way that they won't override the previous expectations.
Adding .RetiresOnSaturation() to all your EXPECT_CALL will make sure that calls are forwarded to default action (set by ON_CALL), when they are not interesting.
Custom matchers will be helpful in cases when there are multiple disallowed values.
MATCHER(IsValidApiArg, ""){return arg == 0 || arg == 1;}
ON_CALL(*this, api_foo(!IsValidApiArg)
.WillByDefault(::testing::InvokeWithoutArgs([](){ADD_FAILURE();}));
EXPECT_CALL(myMock, api_foo(IsValidApiArg));
Note: I still can't believe that GMock doesn't provide a default action for simply generating a failure. Perhaps you can find something better suitable deep in documentation.
You can also create a custom action for that, to avoid all that Invoke and lambdas.

LevelDB --- Code in C++

The below given code is taken from LevelDB. I am giving two blocks of code for better understanding. I am unable to understand what is happening.
ThreadState is a structure and I have written here to make it easy for the reader.
struct ThreadState {
int tid; // 0..n-1 when running in n threads
Random rand; // Has different seeds for different threads
Stats stats;
SharedState* shared;
ThreadState(int index)
: tid(index),
rand(1000 + index) {
}
};
Is the marked code below an object instantiation of class Benchmark? What is happening in the marked code below?
void Run() {
PrintHeader();
Open();
const char* benchmarks = FLAGS_benchmarks;
while (benchmarks != NULL) {
{
//code ommitted
}
// Reset parameters that may be overriddden bwlow
***void (Benchmark::*method)(ThreadState*) = NULL;*** // What does this code line mean? // Benchmark is a class.
bool fresh_db = false;
int num_threads = FLAGS_threads;
if (name == Slice("fillseq")) {
fresh_db = true;
method = &Benchmark::WriteSeq;
}
If required, I can give detailed implementation of Benchmark as well.
Thanks a lot for the help!
void (Benchmark::*method)(ThreadState*) = NULL;
// What does this code line mean?
// Benchmark is a class.
The above is a pointer to a member function. Since member functions are not like regular functions (they can only be called on a valid object), you cannot take their address it the same way you would for a free function.
Therefore the above syntax is introduced. It is similar to a regular function pointer except the class specifier Benchmark::. This is essentially the type of the implicit this pointer.
In your case, method is a pointer to a member function that takes ThreadState* as a parameter, and has a void return type. The reason for using it is most probably to simplify the call. First, and based on various parameters, a member function is chosen to be called, and its "address" stored in method. After all the checks are done, there is only a single call to the chosen function via the pointer to member.
Incidentally, &Benchmark::WriteSeq is how the code obtains the "address" of the member function WriteSeq. You must use the address-of operator on the qualified function name.

Google Mock Return a live element using ON_CALL

I read through Google Mock: Return() a list of values and found out how to return a single element from a vector on each EXPECT_CALL, as such I wrote the following code which works:
{
testing::InSequence s1;
for (auto anElem:myVecCollection) {
EXPECT_CALL(myMockInstance, execute())
.WillOnce(testing::Return(anElem));
}
}
so far so good...
Now I read not to use EXPECT_CALL unless you need to. https://groups.google.com/forum/#!topic/googlemock/pRyZwyWmrRE
My use case, myMockInstance is really a stub providing data to the SUT(software under test).
However, a simple EXPECT_CALL to ON_CALL replacement will not work(??), since ON_CALL with WillByDefault only calculates the return type only once(??)
As such I tried setting up an ACTION.
ACTION_P(IncrementAndReturnPointee, p)
{
return (p)++;
}
ON_CALL(myMockInstance, execute())
.WillByDefault(testing::Return
(*(IncrementAndReturnPointee(myVecCollection.cbegin()))));
Clang gives
error: expected expression 'ACTION_P(IncrementAndReturnPointee, p)'
Then I tried setting up a functor and use the Invoke method on it.
struct Funct
{
Funct() : i(0){}
myClass mockFunc(std::vector<myClass> &aVecOfMyclass)
{
return aVecOfMyclass[i++];
}
int i;
};
Funct functor;
ON_CALL(myMockInstance, execute())
.WillByDefault(testing::Return(testing::Invoke(&functor, functor.mockFunc(myVecCollection))));
Clang gives
no matching function for call to 'ImplicitCast_'
: value_(::testing::internal::ImplicitCast_<Result>(value)) {}
Now , I am fairly new to google-mock but have used google-test extensively.
I am a bit lost with the Google-Mock doc. I wanted to know, whether I am on the right path, in terms of what I needed.
If one of you could point to me , which approach is the correct one; or whether I am even close to the right approach, I can take it from there and debug the "close to right approach" further.
Thanks
testing::Return is an action. Your code should look like:
ACTION_P(IncrementAndReturnPointee, p)
{
return *(p++);
}
ON_CALL(myMockInstance, execute())
.WillByDefault(IncrementAndReturnPointee(myVecCollection.cbegin()));
As a side note, it doesn't look like a good idea to use a finite collection myVecCollection. You will probably get a more robust test if you figure out an implementation of the action that creates a new element to return on the fly.

c++ int accessor return 0 even if mutator sets properly

I'm stuck at a problem I feel stupid about as it's basically just two lines of code in midst of a 2000 line working OOP script.
Cut to the chase - I have an Entity class which provides various information (name, address, ID). The problem is - even if the ID mutator (setter) sets a proper value (tested with cout and return value), the accessor always returns 0.
// ID accessor
int Entity::ID() const {
return _ID;
}
// ID mutator
int& Entity::ID( int newID ) {
if ( newID >= 0 ) {
_ID = newID;
}
return _ID;
}
Here are my classes (the ID( int ) method is called in AgencyNetwork::createXXX() and is used in every toStr() method (at the end of each class)):
Entity.cpp, AgencyNetwork.cpp, Agent.cpp
SOLVED: I forgot to add the ID mutator in every operator=. Thanks to everyone who helped :)
Most notably, the assignment operator of Entity is broken:
Entity& Entity::operator= ( const Entity& tocopy ) {
delete this; // <<< don't do that
this -> name ( tocopy.name() );
this -> address ( tocopy.address() );
// <<< missing _ID
return *this;
}
There is no magic. There is plain BUG. So, lets use tracing: trace every 'mutator' call. Make sure that nobody can access the _ID field in other way than through the mutator call. Trace constructor, copy constructor, copy assignment operator and destructor calls also.
Then run your code and follow the trace log.
I'm sure everything will become clear in your case.
NOTE: if your implementation misses some of the member functions mentioned above you should to define them with the bodies consisting of tracer call only.
You shouldn't let the compiler to make any implicit member function generation in order to be sure that you've the full control of you class and particularly the _ID field.