如何在Swift中模拟UIApplication? [英] How to mock UIApplication in Swift?

查看:101
本文介绍了如何在Swift中模拟UIApplication?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用Quick + Nimble在Swift中进行单元测试.我正在构建一个Inviter类,该类通过不同的方法发送应用邀请.

I'm currently using Quick + Nimble for my unit testing in Swift. I'm building an Inviter class that sends app invites via different methods.

我需要模拟UIApplication来验证我的代码是否调用openURL.

I need to mock out UIApplication to verify that my code calls openURL.

到目前为止,我的代码:

My code so far:

import Quick
import Nimble
import OCMock

extension Inviter {
    convenience init(usingMockApplication mockApplication: UIApplication) {
        self.init()
        application = mockApplication
    }
}

class MockUIApplication : UIApplication {
    var application = UIApplication.sharedApplication()

    var openedURL: String?

    override func openURL(url: NSURL) -> Bool {
        openedURL = url.absoluteString
        return true
    }
}

class InviterSpec: QuickSpec {
    override func spec() {

        describe("Inviter") {
            var mockApplication = MockUIApplication()
            var inviter = Inviter(usingMockApplication: mockApplication)

            beforeEach() {
                inviter = Inviter(usingMockApplication: mockApplication)
            }

            context("for WhatsApp invites") {
                beforeEach() {
                    inviter.inviteViaWhatsAppWithMessage("Invite Message.")
                }

                it("should tell the application to open WhatsApp") {
                    expect(mockApplication.openedURL).toNot(beNil())
                }

                it("should send WhatsApp the right message") {
                    let message = mockApplication.openedURL?.lastPathComponent
                    expect(message).to(equal("Invite%Message."))
                }
            }
        }
    }
}

以这种方法,我的应用程序在运行时出现错误,指出那里只有一个UIApplication是可以理解的.以前,可以使MockUIApplicationNSObject继承,并将其传递.不幸的是,Swift的严格类型检查似乎也可以防止这种情况.

In this approach, my app errors at runtime stating there can understandably be only one UIApplication. Previously, one could make MockUIApplication inherit from NSObject, and pass that in. Unfortunately Swift's strict type checking seems to prevent that too.

会喜欢任何想法.

推荐答案

您很亲密.为所需功能使用协议.

You are close. Use a protocol for the functions you need.

protocol UIApplicationProtocol {
    func openURL(url: NSURL) -> Bool
}

extension UIApplication: UIApplicationProtocol {}

然后,您只需要使用协议而不是类

Then you just need to use the protocol instead of the class

extension Inviter {
    convenience init(usingMockApplication mockApplication: UIApplicationProtocol) {
        self.init()
        application = mockApplication
    }
}

您将需要修改Inviter类以同时使用UIApplicationProtocol.

You will need to modify the Inviter class to use UIApplicationProtocol as well.

这篇关于如何在Swift中模拟UIApplication?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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