LoginSignup
44
42

More than 5 years have passed since last update.

XCTestでViewControllerのテストを良い感じにやる方法

Last updated at Posted at 2014-03-05

ViewControllerのテストって難しいですよね。

ContainerViewを活用している場合、addChildViewControllerしていても子ViewControllerのviewWillAppearが呼ばれなくて苦戦しました。
結局、非常に安易な手段で非常に効果的に対処出来たのでメモ。

YourTestCase.m

@implementation UIViewController (TestHelper)

- (void)prefix_viewDidAppearWithObject:(NSNumber*)number
{
    [self viewDidAppear:number.boolValue];
}

@end


@interface YourTestCase : XCTestCase

@property YourViewController *viewController;

@end

@implementation YourTestCase

- (void)setUp
{
    [super setUp];

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:Main_iPhoneStoryboardName bundle:[NSBundle mainBundle]];
    self.viewController = [storyboard instantiateViewControllerWithIdentifier:Main_iPhoneStoryboardFeedViewControllerIdentifier];
}

- (void)testHoge
{
    // こんな感じで、実アプリでは遷移元でのprepareForSegue辺りで渡されるオブジェクトを渡す
    self.viewController.image = someImage; 

    // メインウィンドウのrootViewControllerに表示(をテスト)したいViewControllerをセット
    [UIApplication.sharedApplication.delegate.window setRootViewController:self.viewController];

     // この行がないとメインスレッドをブロックせずに下に処理が走ってしまうので、正しくテスト出来ない模様。
    [self.viewController performSelectorOnMainThread:@selector(prefix_viewDidAppearWithObject:) withObject:@(YES) waitUntilDone:YES];

    // あとは好きにテストコードを書いてください! 例えば以下のような。
    XCTAssertNotNil(self.viewController.imageView.image, @"画像があることを確認、とか。そんな感じ。");
}

@end

44
42
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
44
42