Fixture in Glib(夹具)

下述夹具示例演示的是将一个素数转换成无符号长整形。从例子中我们可以看出,夹具由左夹具右夹具两个函数组成,

  • 左边的我们一般叫做 fixture_setup 函数,左夹具负责对测试例的初始化准备工作。
  • 右边的叫做 fixture_teardown 函数,右夹具负责测试例运行后的清理工作。

gtest 中貌似有一个 Fixture 的概念,表示的测试时候传进来的数据,以及对于这个数据的 setup、test 和 destroy。

3_01_GLib库入门与实践_测试框架_glib test-CSDN博客

#include <glib.h>

typedef struct {
  guint  seed;
  guint  prime;
  gchar *msg;
} Fixturetest;

static void fixturetest_setup (Fixturetest  *fix, gconstpointer test_data) {
  g_assert (test_data == (void*) 0xc0cac01a);
  fix->seed = 18;
  fix->prime = 19;
  fix->msg = g_strdup_printf ("%d", fix->prime);
}

static void fixturetest_test (Fixturetest  *fix, gconstpointer test_data) {
  guint prime = g_spaced_primes_closest (fix->seed);
  g_assert_cmpint (prime, ==, fix->prime);
  prime = g_ascii_strtoull (fix->msg, NULL, 0);
  g_assert_cmpint (prime, ==, fix->prime);
  g_assert (test_data == (void*) 0xc0cac01a);
}

static void fixturetest_teardown (Fixturetest  *fix, gconstpointer test_data) {
  g_assert (test_data == (void*) 0xc0cac01a);
  g_free (fix->msg);
}

int main(int argc, char **argv) {
    g_test_init(&argc, &argv, NULL);
    g_test_add("/misc/primetoul", Fixturetest, (void*) 0xc0cac01a, fixturetest_setup, fixturetest_test, fixturetest_teardown);
    return g_test_run();
}

g_test_add_func()

g_test_add_func("/misc/assertions", test_assertions);

Creates a test suite called “misc” with a single test case named “assertions”, which consists of running the test_assertions function.

这个测试 case 不涉及到外部传进来的任何数据,如果涉及到的话,需要 g_test_add_data_func_full()g_test_add_data_func()

g_test_add_data_func()

void g_test_add_data_func (
  const char* testpath,
  gconstpointer test_data,
  GTestDataFunc test_func
)

Create a new test case, However the test is assumed to use no fixture, and test suites are automatically created on the fly and added to the root fixture, based on the slash-separated portions of testpath. The test_data argument will be passed as first argument to test_func.

If testpath includes the component “subprocess” anywhere in it, the test will be skipped by default, and only run if explicitly required via the -p command-line option or g_test_trap_subprocess().

No component of testpath may start with a dot (.) if the G_TEST_OPTION_ISOLATE_DIRS option is being used; and it is recommended to do so even if it isn’t.

g_test_add_data_func_full()

void g_test_add_data_func_full (
  const char* testpath,
  gpointer test_data,
  GTestDataFunc test_func,
  GDestroyNotify data_free_func
)

Create a new test case, as with g_test_add_data_func(), but freeing test_data after the test run is complete.