我试图在单元测试中扩展一个类,为测试提供仅适用于测试的API。此测试API不适合正常使用,我也不想在原始类中公开其他私有属性和方法。
例如,以下是在同一文件中包含扩展名的类。正如所料,此处的扩展程序可以查看所有属性,包括私有属性,因为扩展名是原始文件的一部分。
class DoSomething {
private var aPrivate:String? = nil
fileprivate var aFilePrivate:String? = nil
internal var anInternal:String? = nil
public var aPublic:String? = nil
}
extension DoSomething {
func anExtensionInSameFile() {
aPrivate = "aaa" // works (private includes extensions defined in the same file)
aFilePrivate = "bbb" // works
anInternal = "ccc" // works
aPublic = "ddd" // works
}
}
请注意,在另一个文件中定义的外部类只能按预期访问internal
和public
属性。
class DoAnotherThing {
let doSomething = DoSomething()
func whatEver() {
// Only internal and public variables are visible - as expected
doSomething.anInternal = "111"
doSomething.aPublic = "222"
}
}
我的单元测试类有一个扩展,打算添加一个应该只对测试可见的额外API。我需要访问私有属性和方法,但不希望将这些属性公开给其他类。
不幸的是,我的测试定义的扩展程序无法看到private
或fileprivate
属性。
import XCTest
@testable import navigation
extension DoSomething {
func anExtensionForTestingOnly() {
aPrivate = "www" // does not compile
aFilePrivate = "xxx" // does not compile
anInternal = "yyy" // works
aPublic = "zzz" // works
}
}
class DoSomethingTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testAnything() {
let doSomething = DoSomething()
doSomething.anExtensionForTestingOnly() // only available from the tests
// only has visibility to internal and public properties
doSomething.anInternal = "333"
doSomething.aPublic = "444"
}
}
我不认为Swift有一个允许访问扩展程序的访问控制,我相信我需要这样做。