测试旧OS版本的代码路径 [英] Testing codepaths for older OS versions
问题描述
如果我有一些方法类似的库:
If I have some library with methods like:
public struct Foo {
@available(macOS 10.15, *)
func greatNewFeature() -> String {
return "new feature"
}
func legacyFeature() -> String {
return "legacy feature"
}
}
然后使用它的一些代码:
Then some code that uses it:
func methodToTest() -> String {
let foo = Foo()
guard #available(macOS 10.15, *) else {
return foo.legacyFeature()
}
return foo.greatNewFeature()
}
有没有一种方法可以编写单元测试,使我完全了解 methodToTest
?
Is there a way I can write unit tests which give me complete coverage of methodToTest
?
到目前为止,我所有的想法都没有帮助:
All ideas I have had so far, have not been helpful:
- 您不能将可用性检查视为已注入的功能-编译器特别需要
@available
关键字才能使用greatNewFeature
方法. - 您不能添加一些可以在测试中设置的hacky布尔值,例如
#available(macOS 10.15,*)||isMacOS10_15
的原因与上一点类似.
- you can't treat the availability check as injected functionality - the compiler specifically needs the
@available
keyword in order to use thegreatNewFeature
method. - you can't add some hacky boolean which you could set in the tests like
#available(macOS 10.15, *) || isMacOS10_15
for a similar reason to the previous point.
我认为唯一可行的方法是多次运行测试套件-对每个受支持的OS版本运行一次,然后创建一个脚本以合并代码覆盖率统计信息.谁能想到更好的方法?
The only thing I think would work is to run the test suite multiple times - once for each supported OS version, then create a script to combine the code coverage stats. Can anyone think of a better approach?
推荐答案
您可以在测试中创建一个标志,以决定是否跳过OS版本检查,并使用 #available
检查.
You can create a flag in your tests whether to skip the OS version check or not and &&
that with your #available
check.
这样,您只需要在打开和关闭该标志的情况下调用 testFooFeature
,就可以在 macOS 10.15
上测试这两个代码路径.
This way you simply need to call testFooFeature
with the flag both turned on and off and you'll be able to test both code paths on macOS 10.15
.
var forceOldOSVersion = true
func testFooFeature() -> String {
let foo = Foo()
if !forceOldOSVersion, #available(macOS 10.15, *) {
return foo.greatNewFeature()
} else {
return foo.legacyFeature()
}
}
testFooFeature() // "legacy feature"
这篇关于测试旧OS版本的代码路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!