iOS Swift:为XCTest分离AppDelegate [英] iOS Swift: Separate AppDelegate for XCTest

查看:316
本文介绍了iOS Swift:为XCTest分离AppDelegate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于一些问题,我希望项目中的XCTest目标能够运行单独的应用程序委托。使用ObjC,这是一个相对简单的过程:操作 main.m (参见: https://stackoverflow.com/a/15725328/1299041 )。

Due to a couple issues, I want the XCTest target in a project to run a separate app delegate. Using ObjC, this was a relatively straightforward process: manipulate main.m (see: https://stackoverflow.com/a/15725328/1299041).

因为似乎用初始化Swift应用程序在AppDelegate中@UIApplicationMain ,是否可以使用单独的AppDelegate为测试目标进行初始化?

Since it seems that a Swift application is initialized with @UIApplicationMain in the AppDelegate, is it possible to initialize with a separate AppDelegate for the test target?

推荐答案

强烈建议在正常的代码检查中添加条件,如果它正在测试。相反,你应该在测试中模拟你的 AppDelegate 来做你想做的事。

It's strongly unrecommended to add conditions to normal code checking if its being tested. Instead you should mock your AppDelegate in tests to do whatever you want.

然后你可以替换UIApplication的委托是 setUp 在每个 XCTestCase 'es的超级类中。

Then you could replace delegate of UIApplication is setUp in super class of your each XCTestCase'es.

class MockAppDelegate:NSObject, UIApplicationDelegate {

}


class BaseTest: XCTestCase {

    override func setUp() {
        super.setUp()
        UIApplication.shared.delegate = MockAppDelegate()
       }
}
class Test1: BaseTest {

    override func setUp() {
        super.setUp()
        // normal testing
       }
}






如果您仍想停止测试的代码执行,这是我的方法运作良好:


If you still want to stop code execution for tests this is my method that works well:

您可以向app添加启动参数,表示这是测试运行

You can add startup parameter to app which indicates that this is test run

这些参数可从 NSUserDefaults

#define IS_TESTS [[NSUserDefaults standardUserDefaults] boolForKey:@"TESTING"]

这篇关于iOS Swift:为XCTest分离AppDelegate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆