Skip to content

Instantly share code, notes, and snippets.

@kitasuke
Last active March 18, 2021 06:35
Show Gist options
  • Save kitasuke/5cb4a29c129f9e571ce6 to your computer and use it in GitHub Desktop.
Save kitasuke/5cb4a29c129f9e571ce6 to your computer and use it in GitHub Desktop.
iOSにおけるUIテスト

iOSにおけるUIテスト

目次


【やりたいこと】

  • 画面遷移が正常に行えるかの確認
  • 表示内容が適切かの確認

【ツール】
XCTest + KIFを使用します
*KIFはSquare社製のUIテスト用フレームワーク

導入方法は下記のドキュメントを参照してください
公式ドキュメント 非公式日本語ドキュメント

【KIFで出来るアクション】

  • Viewのタップ
  • 指定された座標のタップ
  • 長押し
  • 文字入力・削除
  • スクロール
  • スワイプ
  • テーブルビュー内のセル選択
  • コレクションビュー内のアイテム選択
  • カメラロール内の写真選択 *要修正
  • ピッカービュ内での選択
  • トグルのオン・オフ
  • ステータスバーのタップ
  • ポップオーバを閉じる

【使い方】

  1. 操作対象のViewにAccessibilityLabelAccessibilityIdentifierを設定する(Storyboard or コード)
  2. 上記のViewを対象に、アクション実行メソッドを実装する

Storyboard上での設定例 Button.storyboard

Accessibility項目がある場合の例
Accessibility項目が無い場合の例

コード上での設定例 Button.m

UIButton *doneButton = [UIButton new];
doneButton.accessibilityLabel = @"hoge";
doneButton.accessibilityIdentifier = @"hoge";

アクションメソッドの実装 ButtonTests.m

@interface ButtonTests : KIFTestCase

@end

@implementation ButtonTests

- (void)beforeAll{}
- (void)beforeEach{}

- (void)testButton
{
  [tester tapViewWithAccessibilityLabel:@"hoge"];
}

- (void)afterEach{}
- (void)afterAll{}

@end

【実行方法】

  • 全テストケースをテスト → ⌘+U
  • 指定のテストケースをテスト → ⌃+⌥+⌘+U
    *実行前にiPhoneシミュレーターが起動していないことを確認する

【やりたいこと】

  • 工数を減らす
  • 作業内容が他の部分に悪影響を与えてないかの確認

【ツール】
Github + Travis

【設定方法】

  1. .travis.ymlの作成
  2. Travis上でのビルド設定
  3. 画面遷移の際にスクリーンショットを撮るようにKIFで実装
  4. ImageMagickのmontageコマンドで複数毎の画像を1枚にするスクリプト作成
  5. ImageMagickのcompositeコマンドでdiffを調べるスクリプト(オプション)

.travis.ymlの例

language: objective-c
xcode_workspace: hoge.xcworkspace
xcode_scheme: hoge
xcode_sdk: iphonesimulator

before_install:
  - gem install cocoapods

スクリーンショット保存の実装例

- (void)captureScreenshot
{
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    UIGraphicsBeginImageContextWithOptions(keyWindow.bounds.size, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    NSArray *windows = [[UIApplication sharedApplication] windows];
    [windows enumerateObjectsUsingBlock:^(UIWindow *window, NSUInteger idx, BOOL *stop) {
        [window.layer renderInContext:context];
    }];

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *path = [[paths firstObject] stringByAppendingPathComponent:@"hoge.png"];
    [UIImagePNGRepresentation(image) writeToFile:path atomically:YES];
}

保存場所は/Library/Caches/以下を指定しています。 実際は、テストケース名のディレクトリ以下に、タイムスタンプをファイル名にして保存しています。

montageコマンドの例

montage -tile 2x2 -geometry 640x1136 hoge1.png hoge2.png hoge3.png hoge4.png result.png

compositeコマンドの例

composite -compose difference hoge1.png hoge2.png diff.png
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment