CodeBlanks Logo Icon CodeBlanks

Test doubles

Learn test doubles and stubs.

Test doubles

Test doubles are stand-ins for real dependencies: stub, mock and fake. The most common is a stub; it returns a fixed value.

Example: time() returns a different value on every call, which makes it hard to test. By writing long stub_time(void) { return 1000; } you get a deterministic value. The test then produces the same result on every machine. Stubs separate the outside world (clock, random number, network) from the test.

Types of doubles

A stub returns a fixed value; a mock also records which calls were made; a fake provides a simplified but working implementation (e.g. an in-memory database).

In this lesson we only use a stub: long stub_time(void). In main you write long t = stub_time(); and printf("zaman: %ld\n", t);. The output is always "zaman: 1000"; this is the definition of a deterministic test. Testing with the real time would give different results every hour.

Practice Write stub_time

Write long stub_time(void) that returns 1000. In main compute long t = stub_time(); and print printf("zaman: %ld\n", t);.

Starter code

main.c
#include <stdio.h>

// Write long stub_time(void) that returns 1000
// main: call stub_time and print the time

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>

long stub_time(void) {
    return 1000;
}

int main(void) {
    long t = stub_time();
    printf("zaman: %ld\n", t);
    return 0;
}

Expected output

zaman: 1000

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 stub_time body

Question
long stub_time(void) { return ____; }
Answer
long stub_time(void) { return 1000; }

Explanation: The stub returns a fixed 1000; the test is deterministic.

2 Match double types

Term Meaning
stub Fixed value
mock Call record
fake Simple impl
real Real dependency

3 When is stub_time useful?

  • For deterministic tests Correct answer
  • To allocate memory
  • To close files
  • To send signals

Explanation: A stub gives a fixed value for deterministic tests.

All lessons in Advanced