简体   繁体   English

在单元测试中模拟iOS App版本号

[英]Mock iOS App Version Number in Unit Test

I have added functionality to my project that downloads JSON and compares the version numbers in there with the currently installed app version to determine whether a feature should be enabled or not. 我向我的项目添加了功能,该功能可以下载JSON ,并将其中的版本号与当前安装的应用程序版本进行比较,以确定是否应启用某个功能。 However, I am now trying to unit test this and I am not sure how to mock the current app version. 但是,我现在正在尝试对此进行单元测试,并且不确定如何模拟当前应用程序版本。

  • Can I inject a value into the info.plist in a test? 我可以在测试中将值注入info.plist吗?
  • Can I completely mock the info.plist in a test? 我可以在测试中完全模拟info.plist吗?

Or should I: 还是我应该:

  • Add a function in my class to retrieve the version number from the info.plist file and then mock that function? 在我的课程中添加一个函数以从info.plist文件中检索版本号,然后模拟该函数?

  • On app startup, store the version number in NSUserDefaults and the mock this? 在应用启动时,将版本号存储在NSUserDefaults并模拟吗?

I would definitely go with the function which retrieves version number. 我肯定会使用检索版本号的功能。 This way you can get it from info.plist in production code and mock whatever you want in tests. 这样,您可以从生产代码中的info.plist中获取它,并在测试中模拟所需的内容。 Additionally you will be able to test the retrieval of app version as well :) 此外,您还可以测试应用程序版本的检索:)

Or even better, create another class which gets the application number and inject instance to the class which downloads JSONs. 甚至更好的做法是,创建另一个获取应用程序编号的类,并将实例注入到下载JSON的类中。 You'll be then able to mock this however you want. 然后,您可以根据需要模拟该内容。

protocol AppVersionProvider {
    func getAppVersion() -> String
}

class JSONDownloader {

    private let appVersionProvider: AppVersionProvider

    public init(appVersionProvider: AppVersionProvider) {
        self.appVersionProvider = appVersionProvider
    }

    public func downloadJSON() {

        if appVersionProvider.getAppVersion() != networkingCallResult.appVersion {
            ...
        }
    }
}

There, you can mock AppVersionProvider protocol in test with some stub and use info.plist provider for production. 在这里,您可以使用一些存根在测试中模拟AppVersionProvider协议,并使用info.plist提供程序进行生产。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM