我可以模拟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) {

        ...
    }

    ...
}

最佳答案

虽然,乔恩·里德(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 ...

}

关于swift - 有没有一种方法可以编写一个对SKPhysicsContactDelegate函数的测试?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44084187/

10-09 12:58