Skip to content

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

Open

Description

@FrankLiang826

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?

Activity

  1. 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.[/+] on Dec 19, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions