CUnit を試す。

はじめに

 本記事は、CUnitの入門してみた結果をまとめてみたものである。
使用したソース等は、https://github.com/tomohikoseven/cunit_sample

テスト環境概要

 CUnitのテスト環境は、下記のような階層的な構造になっている。

テスト・レジストリ
   |- テスト・スイート1
   |      | - テストケース1
   |       :
   |      ` - テストケース N
   |- テスト・スイート2
   :
   `- テスト・スイート M

テスト環境とテストソースの対応

 上記テスト環境とテストソースの対応を下記に示す(★の部分)。

/*
 * test
 */
#include
#include

// test target
#include                                           ※ 今回のテスト対象。ただのフィボナッチ数出力関数

/*
 * prototype
 */
void test_fib_001(void);
void test_fib_002(void);

/*
 * main
 */
int
main()
{
    CU_pSuite fib_suite;

    // テストレジストリ作成
    CU_initialize_registry();                             ★ テスト・レジストリ

    // テストスイート
    fib_suite = CU_add_suite( "Fib", NULL, NULL );        ★ テスト・スイート
    // テストケース
    CU_add_test( fib_suite, "test_001", test_fib_001 );   ★ テストケース
    CU_add_test( fib_suite, "test_002", test_fib_002 );

    // テスト実行
    CU_console_run_tests();

    // テストレジストリ削除
    CU_cleanup_registry();

    return 0;
}
void
test_fib_001(void)
{
    int n   = 0;
    int ans = 1;

    CU_ASSERT_EQUAL( fib( n ), ans );
}
void
test_fib_002(void)
{
    int n   = 1;
    int ans = 1;

    CU_ASSERT_EQUAL( fib( n ), ans );
}

Makefile

 テストプログラムのMakefileを示す。libcunit.so が/usr/local/lib に、CUnit/CUnit.h と CUnit/Console.h が /usr/local/includeにないといけない。

SRCS=test_main.c fib.c
OBJS=$(SRCS:.c=.o)
INCLUDES=-I.                                       ※ fib.hのインクルードパス。CUnit.h や Console.hのインクルードパスではない。

all:test_main
test_main:$(OBJS)
	$(CC) -o $@ $^ -L/usr/local/lib -lcunit    ★ libcunit.so のリンク
.c.o:
	$(CC) -c $< $(INCLUDES)
clean:
	\rm -f $(OBJS) test_main core.*

テスト実行結果

andre@andre-VirtualBox:~/work/cunit/test$ ./test_main


     CUnit - A Unit testing framework for C - Version 2.1-2
             http://cunit.sourceforge.net/


 ***************** CUNIT CONSOLE - MAIN MENU ******************************
(R)un  (S)elect  (L)ist  (A)ctivate  (F)ailures  (O)ptions  (H)elp  (Q)uit
Enter command: r

Running Suite : Fib
     Running Test : test_001
     Running Test : test_002

Run Summary:    Type  Total    Ran Passed Failed Inactive
              suites      1      1    n/a      0        0
               tests      2      2      2      0        0
             asserts      2      2      2      0      n/a

Elapsed time =    0.000 seconds


 ***************** CUNIT CONSOLE - MAIN MENU ******************************
(R)un  (S)elect  (L)ist  (A)ctivate  (F)ailures  (O)ptions  (H)elp  (Q)uit
Enter command: