Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hello my friends, I wonder how to mock a c library function by using cpputest. Thanks very much. #1769

Open
FrankLiang826 opened this issue Dec 19, 2023 · 0 comments

Comments

@FrankLiang826
Copy link

FrankLiang826 commented Dec 19, 2023

I want to mock a c library function, i.e. int abs(int a). I writen my testcase like this, but when I execute it, the testcase call the real one, not the mocked one. I want to know how to mock a c library function, especially the variadic function, i.e. open and ioctl.
source file:src.cpp
#include <stdlib.h> int abs_test() { return abs(-1); }
include file:src.h
int abs_test();
test file:test.cpp

#include "CppUTest/TestHarness.h"
#include "CppUTestExt/MockSupport_c.h"
#include "src.h"
TEST_GROUP(MockDocumentation_C)
{
    void teardown()
    {
        mock_c()->clear();
    }
};

int abs(int b)
{
    mock_c()->actualCall("abs")->withIntParameters("a", b);
    return mock_c()->returnValue().value.intValue;
}

TEST(MockDocumentation_C, abs_test) {
    mock_c()->expectOneCall("abs")->withIntParameters("a", -1)->andReturnIntValue(2);
    CHECK_EQUAL(abs_test(), 2);
    mock_c()->checkExpectations();
}

TEST(MockDocumentation_C, abs) {
    mock_c()->expectOneCall("abs")->withIntParameters("a", -1)->andReturnIntValue(2);
    CHECK_EQUAL(abs(-1), 2);
    mock_c()->checkExpectations();
}

image

The second one can pass, but the first one fail.
And I also want to know whether a parameter can be set to an arbitrary value rather than a fixed value when I mock a function?

@FrankLiang826 FrankLiang826 changed the title Hello my friends, I wonder how to mock a c library function by using cpputest. Thanks very much. Hello my friends, I wonder how to mock a c library function by using cpputest. Thanks very much. Dec 19, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant