OCUnitとはObjective-C用のUnitTest用Frameworkです。
今回はこのOCUnitを試してみたいと思います。-setUp, -tearDownなどJUnitなどのxUnitを使用した経験がある方なら非常に親しみやすいと言えます。
以下は全てX-Code上で行います。
UnitTest対象
UnitTestの対象として例えば以下のようなクラスを作成します。
Person.h
#import
@interface Person : NSObject {
NSString *displayName;
}
@property (copy) NSString *displayName;
- (id)initWithName:(NSString *)displayName;
@end
Person.m
#import "Person.h"
@implementation Person
@synthesize displayName;
- (id)initWithName:(NSString *)aName {
if ((self = [super init])!= nil) {
self.displayName = aName;
}
return self;
}
- (void) dealloc {
[displayName release];
[super dealloc];
}
@end
新規ターゲットの作成
- ターゲットを選択し、新規ターゲットの作成を選択
- Cocoa >> Unit Test Bundleを選択し、次へ
- 名前を例えばUnitTestsにして完了
ターゲットUnitTestsの情報の変更
- ビルド >> リンク >>他のリンクフラグのCocoaをFoundationに変更する
- ビルド >> ユーザー定義 で以下の項目以外を削除する。
- GCC_C_LANGUAGE_STANDARD
- GCC_WARN_ABOUT_RETURN_TYPE
- GCC_WARN_UNUSED_VARIABLE
Person.mのターゲット修正
- Person.mのターゲットの中にUnitTestsを追加する
新規TestCaseの作成
- ファイル >> 新規ファイルを選択
- Cocoa Touch Classes >> NSObject subclassを選択し、次へ
- 名前を例えばPersonTest、ターゲットをUnitTestsにして完了
TestCaseの実装
PersonTest.h
#import
@class Person;
@interface PersonTest : SenTestCase {
Person *person;
}
@end
PersonTest.m
#import "PersonTest.h"
#import "Person.h"
@implementation PersonTest
- (void)setUp {
person = [[Person alloc] init];
}
- (void)testCreatePerson {
STAssertNotNil(person, @"Couldn't create Person");
}
- (void)testSetDisplayName {
NSString *displayName = @"Seiji";
person.displayName = displayName;
STAssertEqualObjects(displayName, person.displayName, @"Couldn't set person.displayName");
}
- (void)tearDown {
[person release];
}
@end
TestCaseの実行
UnitTestsを選択し、Buildを行うことでTestCaseが実行される。想定結果が違うものであればBuildの時点でErrorが表示されることになります。
References
// Begin Comments & Trackbacks ?>
// Begin Trackbacks ?>
// End Trackbacks ?>
// Begin Comments ?>
// Begin Comments ?>
Comments
Leave a comment
This is the comment form.

It’s a good example but unfortunately I’m struggling to bring my old classes, which are all import dependent to each other, under test. Should I drag in the Compiled Sources of the UnitTests project also the classes from the main project I want to test, in this case Person ?
Comment by christian — February 27, 2009 @ 8:59 am