0

我可以模拟SKPhysicsContact对象以输入-(void)didEndContact:(SKPhysicsContact *)contact方法吗?或者还有其他可以在这里利用的技术吗?

class PhysicsTestCase: XCTestCase {

    var physics: GamePhysics!

    ...

    func testCaseOfCollisionsHandling() {

        let contact = SKPhysicsContact()
        contact.bodyA = SKPhysicsBody(circleOfRadius: 10) // Error, 'bodyA' is get-only property

        physics.didEnd(contact) // Physics conforms to `SKPhysicsContactDelegate`
    }

    ...

}

...

// The class that is being tested

class GamePhysics: NSObject, SKPhysicsContactDelegate {

    // MARK: - SKPhysicsContactDelegate

    func didBegin(_ contact: SKPhysicsContact)  {

        guard let nodeA = contact.bodyA.node, let nodeB = contact.bodyB.node else {
            fatalError("No nodes in colliding bodies")
        }

        switch (nodeB, nodeA) {

        case let (ball as LogicalBall, tile as LogicalTile):
           // Performing some logic

        ...

        }
    }

    func didEnd(_ contact: SKPhysicsContact) {

        ...
    }

    ...
}
4

2 回答 2

2

尽管 Jon Reid 在https://stackoverflow.com/a/44101485/482853中提出的子类化非常简洁,但由于SKPhysicsContact类本身难以捉摸,我没有设法使其在这种特殊情况下工作。

解决这个问题的方法是使用良好的旧 Objective C 运行时:

func testBallsCollisionIsPassedToHandler() {

    let ballAMock = LogicalBallMock()
    let bodyA = SKPhysicsBody(circleOfRadius: 10)
    bodyA.perform(Selector(("setRepresentedObject:")), with: ballAMock) // So the bodyA.node will return ballAMock

    let ballBMock = LogicalBallMock()
    let bodyB = SKPhysicsBody(circleOfRadius: 10)
    bodyB.perform(Selector(("setRepresentedObject:")), with: ballBMock) // So the bodyB.node will return ballBMock

    let contact = SKPhysicsContact()
    contact.perform(Selector(("setBodyA:")), with: bodyA)
    contact.perform(Selector(("setBodyB:")), with: bodyB)

    physics.didEnd(contact)

    // Assertions ...       

}
于 2017-05-26T05:02:33.227 回答
1

当我们因为不拥有 API 而无法更改类型时,解决方案是使用遗留代码技术 Subclass 和 Override Method:

class TestablePhysicsContact: SKPhysicsContact {
    var stubbedBodyA: SKPhysicsBody?

    override var bodyA: SKPhysicsBody {
        return stubbedBodyA!
    }
}

要在您的示例测试中使用它:

    func testCaseOfCollisionsHandling() {
        let contact = TestablePhysicsContact()
        contact.stubbedBodyA = SKPhysicsBody(circleOfRadius: 10)

        physics.didEnd(contact)

        // assert something
    }

有关此技术的更多信息,请参阅https://qualitycoding.org/swift-partial-mock/

于 2017-05-21T20:29:04.177 回答