Is there a way to write a test of a `SKPhysicsContactDelegate` functions?

157 views Asked by At

Can I mock SKPhysicsContact object to feed into -(void)didEndContact:(SKPhysicsContact *)contact method? Or is there any other technique, that can be leveraged here?

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) {

        ...
    }

    ...
}
2

There are 2 answers

0
Zapko On BEST ANSWER

Although, subclassing proposed by Jon Reid in https://stackoverflow.com/a/44101485/482853 is very neat, I didn't managed to make it work in this particular case because of elusive nature of SKPhysicsContact class itself.

The way this problem can be solved is to use good old Objective C runtime:

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 ...       

}
4
Jon Reid On

When we can't change a type because we don't own the API, the solution is to use the legacy code technique Subclass and Override Method:

class TestablePhysicsContact: SKPhysicsContact {
    var stubbedBodyA: SKPhysicsBody?

    override var bodyA: SKPhysicsBody {
        return stubbedBodyA!
    }
}

To use this in your example test:

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

        physics.didEnd(contact)

        // assert something
    }

For more on this technique, see https://qualitycoding.org/swift-partial-mock/