Swift Swizzling功能测试后的清理
我想在调用方法swizzling和不调用方法swizzling时测试我的应用程序的行为Swift Swizzling功能测试后的清理,swift,Swift,我想在调用方法swizzling和不调用方法swizzling时测试我的应用程序的行为 class ViewControllerTests: XCTestCase { var sut: ViewController? override func setUp() { sut = ViewController() } override func tearDown() { sut = nil } func testIn
class ViewControllerTests: XCTestCase {
var sut: ViewController?
override func setUp() {
sut = ViewController()
}
override func tearDown() {
sut = nil
}
func testInitialLabelValue() {
// without method swizzling engaged we pull from the existing strings
sut?.viewDidLoad()
XCTAssertEqual( sut?.targetLabel.text, "Welcome en lproj")
}
func testDownloaded() {
// Strings from bundle
sut?.viewDidLoad()
Localizer.swizzleMainBundle()
XCTAssertEqual( sut?.targetLabel.text, "Welcome en lproj")
}
现在我没有正确使用tearDown()。怎么做
那么我怎样才能将这个函数更改为可测试的呢
let bundleName = "Bundle.bundle"
var downloadedBundlePath: String? = Bundle.main.path(forResource: bundleName, ofType: nil)
class Localizer: NSObject {
class func swizzleMainBundle() {
MethodSwizzleGivenClassName(cls: Bundle.self, originalSelector: #selector(Bundle.localizedString(forKey:value:table:)), overrideSelector: #selector(Bundle.specialLocalizedStringForKey(_:value:table:)))
}
}
extension Bundle {
@objc func specialLocalizedStringForKey(_ key: String, value: String?, table tableName: String?) -> String {
if self == Bundle.main {
if let path = downloadedBundlePath, let bundle = Bundle(path: path) {
return (bundle.specialLocalizedStringForKey(key, value: value, table: tableName))
}
return (self.specialLocalizedStringForKey(key, value: value, table: tableName))
} else {
return (self.specialLocalizedStringForKey(key, value: value, table: tableName))
}
}
}
func MethodSwizzleGivenClassName(cls: AnyClass, originalSelector: Selector, overrideSelector: Selector) {
if let origMethod: Method = class_getInstanceMethod(cls, originalSelector), let overrideMethod: Method = class_getInstanceMethod(cls, overrideSelector) {
if (class_addMethod(cls, originalSelector, method_getImplementation(overrideMethod), method_getTypeEncoding(overrideMethod))) {
class_replaceMethod(cls, overrideSelector, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
} else {
method_exchangeImplementations(origMethod, overrideMethod);
}
}
}
这需要是可测试的,但由于它是一个需要Swizzle的函数,我的定位器Swizzle NSLocalizedString并使我的测试失败。但这并不重要,我以后不会清理,所以我需要知道如何清理。@WishIHadThreeGuns您想在测试后将定位器重置为默认值吗?我使用了Swizzle NSLocalizedString的Localizer.swizzleMainBundle()来Swizzle。我不知道如何重置它,我希望能够通过使用tearDown()中的某些内容来实现这一点。这已经解释过了,但我不知道如何释放所有对象以“重新启动”。似乎您必须将
定位器
更改为可测试的,因为目前它不是。