0

I am trying to write a test that verifies a SKSpriteNode in my scene has the correct texture. The test looks like this:

let sceneSprite = scene.childNodeWithName("sceneSprite") as SKSpriteNode!

let sprite = SKSpriteNode(imageNamed: expectedSpriteTexture)
sprite.size = sceneSprite.size // 102.4 x 136.533

XCTAssertTrue(sceneSprite.texture!.sameAs(sprite.texture!), "Scene sprite has wrong texture")

The sameAs method for SKTexture is implemented with the following extensions:

extension SKTexture {
    func sameAs(texture: SKTexture) -> Bool {
        return self.image.sameAs(texture.image)
    }

    var image: UIImage {
        let view = SKView(frame:CGRectMake(0, 0, size().width, size().height))
        let scene = SKScene(size: size())
        let sprite  = SKSpriteNode(texture: self)
        sprite.position = CGPoint(x: CGRectGetMidX(view.frame), y: CGRectGetMidY(view.frame))
        scene.addChild(sprite)
        view.presentScene(scene)
        return self.imageWithView(view)
    }

    func imageWithView(view: UIView) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0)
        view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

extension UIImage {
    func sameAs(image: UIImage) -> Bool {
        let firstData = UIImagePNGRepresentation(self);
        let secondData = UIImagePNGRepresentation(image);
        return firstData.isEqual(secondData)
    }
}

The problem is sometimes the tests passes and sometimes the test fails. I have change the code so it save the images on failure, and discovered the test fails because even though the first image is correct, the second image is completely black. What can be done so the test will pass reliably? This failure is happening on the simulator for iPad2.

Tron Thomas
  • 871
  • 7
  • 20

1 Answers1

0

I made the following change, and it seems to make the test pass reliably

func imageWithView(view: UIView) -> UIImage {
    UIGraphicsBeginImageContext(view.bounds.size)
    view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: false)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
}

What ideas do people have for why this allows the test to succeed?

Tron Thomas
  • 871
  • 7
  • 20
  • Seem like I was wrong. The reason that the test is passing with the change above both images are now completely white. – Tron Thomas Feb 08 '15 at 01:29