简体   繁体   中英

Swift Unit test- How do I assert that a CGColor is what it's supposed to be?

Using Xcode V7.2. Trying to unit test, need to verify that the correct color has been set, and get this message:

Cannot invoke 'XCTAssertEqual' with an argument list of type '(CGColor, CGColor)'

How do I assert that a CGColor is what it's supposed to be?

使用XCTAssert并测试CGColorEqualToColor是否为true。

As of Swift 3.0 / Xcode 8.0 CGColorEqualToColor also no longer works, it results in the error "CGColorEqualToColor is unavailable: use == instead".

== or isEqual has the limitation that it:

will return NO[/False] when comparing colors that are in different models/spaces (for instance #FFF with [UIColor whiteColor])

(From this SO answer ) which may not be the desired behaviour.

It is cumbersome, but I break the colour down into its R/G/B/Alpha components and compare those, eg:

    var red1:CGFloat=0, green1:CGFloat=0, blue1:CGFloat=0, alpha1:CGFloat=0
    colour1.getRed(&red1, green:&green1, blue:&blue1, alpha:&alpha1)

    var red2:CGFloat=0, green2:CGFloat=0, blue2:CGFloat=0, alpha2:CGFloat=0
    colour2.getRed(&red2, green:&green2, blue:&blue2, alpha:&alpha2)

    XCTAssertEqual(red1, red2)
    XCTAssertEqual(green1, green2)
    XCTAssertEqual(blue1, blue2)
    XCTAssertEqual(alpha1, alpha2)

EDIT: (adding this to your answer instead of creating a new answer :)

Here's a UIColor extension for easier use:

import UIKit

extension UIColor {
    func isEqualTo(_ color: UIColor) -> Bool {
        var red1: CGFloat = 0, green1: CGFloat = 0, blue1: CGFloat = 0, alpha1: CGFloat = 0
        getRed(&red1, green:&green1, blue:&blue1, alpha:&alpha1)

        var red2: CGFloat = 0, green2: CGFloat = 0, blue2: CGFloat = 0, alpha2: CGFloat = 0
        color.getRed(&red2, green:&green2, blue:&blue2, alpha:&alpha2)

        return red1 == red2 && green1 == green2 && blue1 == blue2 && alpha1 == alpha2
    }
}

and use it like this:

XCTAssertTrue(cell.backgroundColor!.isEqualTo(.clear))

OR - you can use an Equatable function

func ==(lhs: UIColor, rhs: UIColor) -> Bool {
    var lr: CGFloat = 0, lg: CGFloat = 0, lb: CGFloat = 0, la: CGFloat = 0
    lhs.getRed(&lr, green:&lg, blue:&lb, alpha:&la)
    var rr: CGFloat = 0, rg: CGFloat = 0, rb: CGFloat = 0, ra: CGFloat = 0
    rhs.getRed(&rr, green: &rg, blue: &rb, alpha: &ra)
    return lr == rr && lg == rg && lb == rb && la == ra
}

and use it like this:

XCTAssertTrue(cell.backgroundColor == UIColor.clear)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM