pBouillon
pBouillon

Reputation: 373

How to mock socket in C

I have a function using a socket and I would mock it but I couldn't find how to do it.

Is there a way to mock sockets in C?

Thanks

Upvotes: 7

Views: 5105

Answers (2)

dbush
dbush

Reputation: 223907

Most system / library function are weak symbols. That means you can create your own implementation of them that will override the existing versions. You can then use these functions when unit testing.

Suppose you want to test the following function:

src.c:

int get_socket()
{
    int s;

    s = socket(AF_INET, SOCK_DGRAM, 0);
    if (s == -1) {
        perror("socket failed");
    } else {
        printf("socket success\n");
        close(s);
    }
    return s;
}

You would then create the mock function (and any controlling variables) in a separate source file:

mock_socket.c:

int sock_rval;

int socket(int domain, int type, int protocol)
{
    printf("calling mock socket\n");
    return sock_rval;
}

Then in another file you have your test:

test_socket.c:

extern int sock_rval;
int get_socket();

int main()
{
    sock_rval = -1;
    int rval = get_socket();
    assert(rval == -1);
    sock_rval = 3;
    int rval = get_socket();
    assert(rval == 3);
    return 0;
}

You would then compile and link these three modules together. Then get_socket will call the socket function in mock_socket.c instead of the library function.

This technique works not just with socket functions, but with system / library functions in general.

Upvotes: 13

John Bollinger
John Bollinger

Reputation: 180201

Sockets are managed by the kernel, so there is no userspace-only mechanism for mocking them, but you can set up a genuine socket connected to an endpoint that's part of your test fixture.

In particular, you may be able to use a unix-domain or raw socket for that purpose where the code under test normally has, say, a TCP socket to work with, or you can connect a socket back to the local test fixture via the loopback interface. Or, though I am unaware of any example, in principle you could also find or write a driver that provides sockets for an artificial, for-purpose address family.

Upvotes: 0

Related Questions