简体   繁体   English

Xcode - 来自资产目录的单元测试 UIColor

[英]Xcode - Unit Testing UIColor from asset catalog

I wrote an extension for my Theme class that returns my mainColor based on my current theme.我为我的 Theme 类编写了一个扩展,它根据我当前的主题返回我的 mainColor。 My unit tests cover theme changes but I still have problem with UIColor optional value.我的单元测试涵盖了主题更改,但 UIColor 可选值仍然存在问题。 I can't cover the situation that UIColor could not able returns my specific color from my color catalog.我无法涵盖 UIColor 无法从我的颜色目录中返回我的特定颜色的情况。

extension Theme {
var mainColor: UIColor {
    switch self {
        case .system:
          if let color = UIColor(named: "MainColor") {
             return color
          } else {
             return .clear
          }
        case .custom:
             return .yellow
      }
   }
}

I also used this line instead of unwrapping the optional but it didn't work too.我也使用了这一行而不是解开可选项,但它也不起作用。

return UIColor(named: "MainColor") ?? .clear

How I unit test that the correct color is retrieved from the asset catalog?我如何对从资产目录中检索到正确的颜色进行单元测试?

The problem is that the name MainColor is hard coded, and either this color is in your asset catalog or it isn't, and you cannot control for that in a test.问题在于名称 MainColor 是硬编码的,这个颜色要么在您的资产目录中,要么不在,您无法在测试中控制它。 You need to abstract this into a method to which you can pass the color name from the test.您需要将其抽象为一个方法,您可以将测试中的颜色名称传递给该方法。

I would personally just force unwrap UIColor(named: "MainColor")!我个人会强制打开UIColor(named: "MainColor")! the color in my tests to assert the correct behaviour is occurring (that we are indeed able to access the desired color in the asset catalog).我的测试中用于断言正确行为的颜色正在发生(我们确实能够访问资产目录中所需的颜色)。 If we cannot access this color we will get a crash which, in a unit testing context, is actually desirable to isolate any problems.如果我们无法访问此颜色,我们将导致崩溃,在单元测试上下文中,这实际上是隔离任何问题所需要的。

I would also abstract the name of the color into an enum to ensure that the name is only defined in 1 place, then the possibility of naming inconsistencies between your app target and test target are removed.我还将颜色的名称抽象为一个enum以确保名称仅在 1 个位置定义,然后消除应用目标和测试目标之间命名不一致的可能性。

enum Colors: String { 
    case main = "MainColor" 
}

Then use UIColor(named: Colors.main.rawValue) to access the color.然后使用UIColor(named: Colors.main.rawValue)访问颜色。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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