Skip to content

Instantly share code, notes, and snippets.

@katryo
Last active January 18, 2018 03:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save katryo/44f990d7bc5850fb1dec2f7af4181850 to your computer and use it in GitHub Desktop.
Save katryo/44f990d7bc5850fb1dec2f7af4181850 to your computer and use it in GitHub Desktop.
How I started testing my code in C with Googletest

https://github.com/google/googletest/tree/master/googletest

Build

$ git clone git@github.com:google/googletest.git

$ mkdir mybuild       # Create a directory to hold the build output.
$ cd mybuild
$ cmake ../googletest/googletest/  # Generate native build scripts.
$ make
  • libgtest.a
  • libgtest_main.a

are created.

Implement tests

func.c

#include <stdio.h>

int some_func(int a) {
  return a + 10;
}

func.h

#ifndef GTEST_TRIAL_FUNC_H
#define GTEST_TRIAL_FUNC_H

int some_func(int a);

#endif //GTEST_TRIAL_FUNC_H

Compile func.c

$ gcc -c func.c

Test case

test.cpp

#include "gtest/gtest.h"
extern "C" {
  #include "func.h"
}

class fixtureName : public ::testing::Test {
protected:
  virtual void SetUp(){
  }
  virtual void TearDown(){
  }
};

TEST_F(fixtureName, testOk)
{
    EXPECT_EQ(10, some_func(0));
    EXPECT_EQ(11, some_func(1));
}
$ g++ -pthread -isystem ../googletest/googletest/include test.cpp func.o libgtest_main.a  libgtest.a

Execute the test

$ ./a.out
Running main() from gtest_main.cc
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from fixtureName
[ RUN      ] fixtureName.testOk
[       OK ] fixtureName.testOk (0 ms)
[----------] 1 test from fixtureName (0 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (0 ms total)
[  PASSED  ] 1 test.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment