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.