Swift:基类数组不调用子类函数实现

时间:2016-02-10 16:50:45

标签: ios swift unit-testing mocking

我正在尝试将一个假实例注入一个类的单元测试,这取决于SimpleSing,一个NSObject子类。我的类有一个属性var simplePings: [SimplePing],在我的单元测试中,我将其设置为FakeSimplePing数组。但是,当类进入数组并调用simplePing.start()时,它会调用SimplePing.start实现而不是FakeSimplePing,即使在调试时我看到实例类型是FakeSimplePing。

当属性只是一个SimplePing时,单元测试使用FakeSimplePing.start并且测试通过。这与Swift和超类数组有关吗?

class Pinger : NSObject {
   private var simplePings: [SimplePing] = []

   func pingLocation(location: Location) -> Signal<Double, NoError> {
       let simplePings = location.serverIPs.map { (serverIP: String) -> SimplePing in
           let simplePing = SimplePing(hostName: serverIP)
           simplePing?.delegate = self
           return simplePing
    }
       configureDependencies(simplePings)
       simplePings.forEach { $0.start() }

       return signal
   }

   func configureDependencies(simplePings: [SimplePing]) {
       if self.simplePings.isEmpty {
           self.simplePings = simplePings
       }
   }
}



class FakeSimplePing: SimplePing {
    var receivedStart = false
    var receivedSendPingWithData = false
    var fakeHostName: String!
    override var hostName: String {
        return fakeHostName
    }

    convenience init(hostName: String) {
        self.init()
        fakeHostName = hostName
    }

    override func start() {
        // This does not get called
        receivedStart = true
        delegate?.simplePing?(self, didStartWithAddress: nil)
        delegate?.simplePing?(self, didReceivePingResponsePacket: nil)
    }

    override func sendPingWithData(data: NSData!) {
        receivedSendPingWithData = true
    }
}

失败的测试:

            beforeEach {
                fakeSimplePing = FakeSimplePing(hostName: serverIP)
                fakeSimplePing.delegate = pinger
                pinger.configureDependencies([fakeSimplePing])
            }

            it("pings server with data") {
                pinger.pingLocation(location)

                expect(fakeSimplePing.receivedSendPingWithData).toEventually(beTrue())
            }

1 个答案:

答案 0 :(得分:1)

问题(我相信......)在pingLocation

的命名中

let simplePings = location.serverIPs.map { .... 

您使用与您的财产相同的名称

private var simplePings: [SimplePing] = []

因此您可能认为您使用let定义了一个新变量,但实际上,您可能只是使用您的属性并在途中进行更改,因此它已更改为SimplePing数组,因为它从地图返回

尝试将您的方法更改为:

func pingLocation(location: Location) -> Signal<Double, NoError> {
       let tempSimplePings = location.serverIPs.map { (serverIP: String) -> SimplePing in
           let simplePing = SimplePing(hostName: serverIP)
           simplePing?.delegate = self
           return simplePing
    }
       configureDependencies(tempSimplePings)
       simplePings.forEach { $0.start() }

       return signal
   }