断言从UIGraphics生成的UIImage全部为红色

时间:2019-07-16 18:26:46

标签: swift xctest

前一段时间,我发现了一些代码,用于根据状态更改UIButton的背景颜色。代码如下所示:

extension UIButton {
    func setBackgroundColor(_ color: UIColor, for state: UIControl.State) {
        UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
        UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
        UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
        let colorImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        setBackgroundImage(colorImage, for: state)     
    }
}

现在,我想知道如何正确测试此功能。有什么想法吗?

谢谢

1 个答案:

答案 0 :(得分:1)

  • 调用您的扩展方法
  • 致电.backgroundImage(for:)以获得UIImage
  • 将UIImage渲染为像素
  • 比较像素颜色值