我是iOS开发的新手。我想创建一个函数,当应用程序首次启动时,它可以基于系统语言切换应用程序语言。如何创建单元测试来测试该功能?
这是我在AppDelegate.swift中的代码,我想测试“setLang”函数: 测试用例应该是:
setLang(“en”,设置)
预期结果:setting.string(forKey:“lang”)==“en”
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
applySetting()
return true
}
func applySetting(){
setLang(SysLangCode: Locale.current.languageCode, UserSetting: UserDefaults.standard)
}
func setLang(SysLangCode sysLang:String?, UserSetting setting:UserDefaults){
//Some logic to check sysLang
setting.set(sysLang, forKey:"lang")
}
...
这是我的单元测试,但它失败了“致命错误:在解开一个Optional值时意外发现了nil”
class xxx: XCTestCase {
var appDelegate: AppDelegate!
func testSetLang(){
self.appDelegate.setLang(SysLangCode: "en", UserSetting:UserDefaults.standard)
XCTAssert(UserDefaults.standard.string(forKey: "lang") == "en")
}
}
答案 0 :(得分:0)
如果您已将单元测试目标添加到项目中,那么简单的单元测试将如下所示:
func testLanguageCodeCanBeSetInUserDefaults() {
UserDefaults.standard.set(Locale.current.languageCode,
forKey: "lang")
XCTAssertEqual(UserDefaults.standard.string(forKey: "lang"),
Locale.current.languageCode)
}
将单元测试目标添加到项目中:
档案>新>目标> iOS> iOS单元测试包
编辑:(基于你的)
func testAppDelegateCanSetLanguageCodeToUserDefaults() {
let appDelegate = AppDelegate()
appDelegate.setLang(SysLangCode: "en",
UserSetting:UserDefaults.standard)
XCTAssertEqual(UserDefaults.standard.string(forKey: "lang"),
"en")
}