Cocos2d-x + Xcode でユニットテストをする
はじめに
- http://wonderpla.net/blog/engineer/Cocos2d-x_TDD/ このサイトで Cocos2d-x で TDD を試す手順をわかりやすく解説していてためになった。
- 例示しているコードも実際的で参考になったが、自分には高度すぎたので、簡単なコードで試してみた。
プロジェクトの作成
cd ~/cocos2d-x-2.1.4/tools/project-creator ./create_project.py -project counter -package com.example.counter -language cpp
C++でモデルクラスの作成
Counter.h
#ifndef __counter__Counter__ #define __counter__Counter__ class Counter { private: int count; public: Counter(); void countUp(int n); void countDown(int n); int getCount(); }; #endif /* defined(__counter__Counter__) */
Counter.cpp
#include "Counter.h" Counter::Counter() :count(0) { } void Counter::countUp(int n) { count += n; } void Counter::countDown(int n) { count -= n; } int Counter::getCount() { return count; }
テスト用ターゲットの追加
- 参考サイトの通り、テスト用ターゲットを追加する
- Xcodeの左カラムのファイル一覧から、最上段の counter を選択
- 中央カラムの "Add Target" を選択
- [Other] > [Cocoa Touch Unit Testing Bundle] > "Product Name" に "counterTest" と入力して "Finish"
- 左カラムで counter を選択したまま、中央の TARGETS の counterTest を選択
- 中央カラム上の Build Settings を選択
- "Linking" の "Bundle Loader" に "$(BUILT_PRODUCTS_DIR)/counter.app/counter" と入力
- "Unit Testing" の "Test Host" に "$(BUNDLE_LOADER)" と入力
2013-10-25 追記
- Xcode を 5.0 にしたら、Add Target するだけで Build Setting が適切に設定されるようになっていた。うれしい。
テスト作成
- Xcodeの左カラムから counterTest を右クリック > [New File] > [Cocoa Touch] > [Objective-C test case class] > "CounterTestCase" と入力 > ファイルエクスプローラーで create
- counterTest の CounterTestCase.m を CounterTestCase.mm にリネーム
- テストコードは Objective-C++ で記述する
CounterTestCase.mm
#import "CounterTestCase.h" #import "Counter.h" @implementation CounterTestCase - (void)testCountUp { Counter counter; STAssertEquals(0, counter.getCount(), @"initial count is 0"); counter.countUp(1); STAssertEquals(1, counter.getCount(), @"1 up"); counter.countUp(100); STAssertEquals(101, counter.getCount(), @"1 up and 100 up"); } - (void)testCountDown { Counter counter; STAssertEquals(0, counter.getCount(), @"initial count is 0"); counter.countUp(100); STAssertEquals(100, counter.getCount(), @"100 up"); counter.countDown(1); STAssertEquals(99, counter.getCount(), @"100 up and 1 down"); counter.countDown(10); STAssertEquals(89, counter.getCount(), @"100 up and 1 down and 10 down"); } @end
テストスキーマの設定
テストの実行
- Xcode左上の Run を長押しして、Test を選択して実行
- または、command + u でテスト実行