GMOCK : need to mock async behaviour - c++

bool Test::someFun() {
if (libFunction([](bool b) {
if (b) {
doThisWork();
} else {
doThatWork();
}
})) {
return true;
} else return false;
}
signature of libFunction is:
typedef void (*FUN)(bool);
bool libFunction(FUN f);
Hi Guys,
I need to test someFun function using Gtest/GMOCK. i need to mock libFunction which is written in C.
this libFunction takes a callback(lambda) argument.
Could you please help me with below 2 queries.
how to mock a C function (libFunction) ?
how to test callback which is passed as argument to libFunction as my actual implementation is in lambda which is need to be tested. is there a way to replace libFunction definition with dummy definition so that at run time of test case my dummy implementation will call instead of actual one and i can simulate the libFunction behaviour in dummy function.
Could to please suggest better way to test this.

Related

How to write a test case for module dependent function using EXPECT_CALL in Google test?

I am new to google test environment. I have a sample code written in C and want to perform unit test with Google test framework.
Below is the sample code
// My module function (test.c)
void Update_user_value(void)
{
int user_value;
user_value = get_val_module(); /* return a integer value*/
if(user_value == 0x1)
update_user_flag(true);
else
update_user_flag(false);
}
// This function is in the other module(stub.c) , so we can use Mock function
void update_user_flag(bool val)
{
struct *temp;
if(val == true)
{
temp->userflag = 1;
}
else
{
temp->userflag = 0;
}
}
I wan to write a test case for the Update_user_value function (only for test.c). Through this function, i am sending some flag value to other module (update_user_flag) to set the flag.
I have written a simple google test like this
TEST_F(sampletest, setuser_flag_true_testcase)
{
//Get value from module
ON_CALL(*ptr1, get_val_module()).WillByDefault(Return(0x1)); //Mock function
EXPECT_CALL(*ptr2, get_val_module(_)).Times(1); // Mock function
Update_user_value();
}
TEST_F(sampletest, setuser_flag_false_testcase)
{
//Get value from module
ON_CALL(*ptr1, get_val_module()).WillByDefault(Return(0x0)); //Mock function
EXPECT_CALL(*ptr2, get_val_module(_)).Times(1); // Mock function
Update_user_value();
}
My question: Is this test case is enough to validate the Update_user_value function ?
Also i want to know, EXPECT_CALL() is good to use for setting a value to other module ?
If my understanding is wrong, please suggest me a better test case ?
ON_CALL, EXPECT_CALL are macros designed to be used on mock objects. Usually the use case is as follows:
You create an interface to derive from (it will be mocked in your test).
You pass the mock object (to method or via dependency injection).
You make expectations on this object.
See example:
class Foo {
public:
virtual ~Foo() = default;
virtual int bar() = 0;
};
class FooMock : public Foo {
public:
MOCK_METHOD0(bar, int());
};
bool check_bar_over_42(Foo& foo) {
if (foo.bar() > 42) {
return true;
}
return false;
}
TEST(check_bar_over_42_test, bar_below_42) {
FooMock fooMock{};
EXPECT_CALL(fooMock, bar()).WillOnce(testing::Return(41));
ASSERT_FALSE(check_bar_over_42(fooMock));
}
TEST(check_bar_over_42_test, bar_above_42) {
FooMock fooMock{};
EXPECT_CALL(fooMock, bar()).WillOnce(testing::Return(43));
ASSERT_TRUE(check_bar_over_42(fooMock));
}
AFAIK there is no way of using EXPECT_CALLs on C-like functions. One approach for your problem would be link-time mocking: given a method get_val_module is defined in a separate library, you can create test-only library with get_val_module that will allow you to return the expected values. In tests you would link against test lib, in production - against the real lib.

Mocking functions with cmocka

I'm trying to mock some functions using cmocka:
void test_led_driver_NeedToImplement(void **state)
{
state_t current = CLEAR;
will_return(led_status_toggel,SET);
TEST_ASSERT_EQUAL(SET, led_status_toggel(current));
}
But, I get an error: led_status_toggel() has remaining non-returned values.
Do I have to create a mock file for my functions or what's the source of this error?
Ps: I'm using unity.h as an assertions library.
According to your test, it seams that function you are testing is led_status_toggel. If that is the case, you should not mock it. You should just remove will_return(led_status_toggel,SET);, since your led_status_toggel is probably something like this (You dind't share it so I don't know exactly):
state_t led_status_toggel(state_t state)
{
if (state == CLEAR)
{
return SET;
}
return CLEAR;
}
If your function under test is not led_status_toggel, but some other (that you didn't mentioned) which calls this led_status_toggel, then you can mock this function like this
state_t __wrap_led_status_toggel(state_t state)
{
return (state_t)mock();
}
and use -Wl,--wrap=led_status_toggel in your build command. With --wrap linker flag, when you execute your test, the mock function __wrap_led_status_toggel will be called instead of the original led_status_toggel.

Unit test that ensures method A called after method B

I have a code which interacts with some object and then should call finish() method on it.
void completeTransaction(PaymentTransaction transaction) {
recordTransaction(transaction.getId());
transaction.finish();
}
PaymentTransaction is some third-party class which behaviour after finish() is undefined — it may throw an exception or just fail silently.
I need to write a unit test which passes then and only then:
recordTransaction(transaction.getId()) called
transaction.finish() called
transaction.finish() called after recordTransaction(transaction.getId())
Test satisfying the above conditions should prohibit code like this:
void completeTransaction(PaymentTransaction transaction) {
transaction.finish();
recordTransaction(transaction.getId()); //oops
}
Test case for the first condition:
void testCompleteTransaction_TransactionRecorded() {
completeTransaction(transactionMock);
// assert that recordTransaction(transaction.getId())
// called with correct argument
completeTransaction(PaymentTransaction transaction)
}
For the second one:
void testCompleteTransaction_TransactionCompleted() {
completeTransaction(transactionMock);
// assert that transaction.finish() called
}
I wonder how can I enforce the 3rd condition via test case.
You could pass in a fake PaymentTransaction that overrides finish() and getId() such that finish() throws an exception if some internal flag isn't set when getId() is called.
public class FakePaymentTransaction {
private bool _getIdWasCalled = false;
public override void finish () {
if (!_getIdWasCalled) {
throw new Exception ("getId wasn't called first!");
}
}
public override /* your return type */ getId() {
_getIdWasCalled = true;
// Some other logic to return your specified return type
}
}
Now when you pass it into your SUT, you will see if the calls were made in the right order.
What you want is a mock that can verify the order of calls was as expected. You can roll your own for the specific case as suggested in James D'Angelo's answer or you could create a more generic one that works similarly.
Or you can use facilities supplied by a good mocking framework.
Mockito has, for example, an InOrder verifier that can verify the order of calls of mocked methods from a single mock or multiple mocks.
Your test case makes no sense:
Methods are called in the order you have them in the code:
In an Unit test you should not only call some methods, you should test for a correct result.
but if you want to have some fun:
public testNonsenseTest() {
int i = 0;
PaymentTransaction transaction = new PaymentTransaction();
int transactionId = transaction.getId());
recordTransaction(transactionId);
i++;
assertEquals(1, i);
transaction.finish();
i++;
assertEquals(2, i);
}

Stub a method from tested class to test another method

I discovered that stub and mock are very helpful in testing.
But I wondering about one thing. I think an example will show it clearly.
Class A {
public function isOk() {
// some work
}
public function iAmDepend() {
if ($this->isOk()) {
// do work
}
}
}
class TestA {
public function testIsOk() {
// Test itOk here
}
public function testIAmDepend() {
mock(A)->method(isOk)->return(true);
// tests for iAmDepend
}
}
It wise to do something like this? Stub method of tested class. Or maybe it breaks some rules?
PS. I can't refactore code
Your examples are correct, i.e. testIsOk tests only IsOk, and testIAmDepend only IAmDepend.
But there is important difference between mock and stub that you have to understand: difference between mock and stub.
In your example, if testIAmDepend is verifying that isOk has been called with some arguments and this is part of your assertion for unittest, this is mock. Otherwise this is stub, and you aren't going to verify that it has been called or not.

Should I add features in a class just to make it testable?

I am still trying to get the hang of unit testing, I have a simple question. Today I wanted to write a test for a very simple function. This function was doing just this:
void OnSomething()
{
increment++;
if (increment == 20)
SaveIt();
}
I said, this function could be testable. I could write a test that calls it 20 times and then verifies that SaveIt has been called.
Then my doubt arose. How can I test that SaveIt has been called? My first answer was to add a boolean, but then I thought: is it correct to add class features just to make it testable?
Please advise. Thank you.
I would suggest having SaveIt return a success or failure result, this just makes it easier to test overall. You could do something as simple as having it return a bool, or you could create a generic result class that contains the ability to set messages as well, if you ever need to report whether it passed or failed.
A simple example example
public class Result
{
public bool IsSuccess;
public List<string> Messages;
}
In the unit test you're trying to test only the OnSomething behavior though -- what happens inside "SaveIt" should not be tested. So ideally you'd want SaveIt() to occur in another class so you can mock its response.
I use Moq for this purpose. Moq is free, you can get it here: http://code.google.com/p/moq/
my method would then become
Result OnSomething()
{
Result result=null;
increment++;
if(increment == 20)
{
result = saver.SaveIt();
}
return result;
}
Your class constructor would take an object that implements ISaver interface (defining SaveIt() method) (ideally injected by a DI framework but you could generate it manually if you had to).
Now in your unit test you would create a mock version of ISaver and tell it what to return when it gets called:
Mock<ISaver> mock = new Mock<ISaver>();
mock.Setup(x=> x.SaveIt()).Returns(new Result{IsSuccess=true});
You'd instantiate your class passing mock.Object in the constructor ISaver parameter.
ex.
MyClass myClass = new MyClass(mock.Object);
//(assuming it didn't have other parameters)
Then, you could Assert whether result is null or not -- if it never got called, it would be null because the setup you did above would never trigger.
(in nunit)
Result result = myClass.OnSomething();
Assert.IsNotNull(result);
If you really didn't want OnSomething() to return a result, or it couldn't because it's an event, then I would have OnSomething() call a method to do the work for you:
void OnSomething()
{
Result result = DoTheWork();
}
Result DoTheWork()
{
Result result=null;
increment++;
if(increment == 20)
{
result = saver.SaveIt();
}
return result;
}
And then run your unit test on DoTheWork() instead of OnSomething().
Definitely not! Production code should not depend on tests at all, but the tests should verify the correct behaviour of the actual code. This can be achieved by several methods, such as IOC, and using mocks. You can take a look at some existing frameworks which simplify your life a lot:
http://code.google.com/p/mockito/
http://code.google.com/p/jmockit/
http://www.easymock.org/