我是 ios Unitesting 的新手,这是我第一次真正这样做。
我的应用程序正在使用一个正在执行一些网络调用的框架,
我正在尝试通过调用其中一个函数来测试框架的业务逻辑 但该函数只是通过了实际调用,并没有进入回调。
这是我正在尝试检查的框架内的实际功能 >
func initSDK () {
let launchParams: [String:String] = [
kAWSDKUrl: WhiteLabeler.localizedStringForKey(key: "baseSDKUrl", comment: "-", defaultValue: "https://isr-lap-tst2.americanwell.com:8443/"),
kAWSDKKey: WhiteLabeler.localizedStringForKey(key: "SDKserviceKeyForIos", comment: "-", defaultValue: "TriageApp"),
kAWSDKBundleID: Bundle.main.bundleIdentifier!
]
AWSDKService.initialize(withLaunchParams: launchParams) {[weak self] (success, error) in
if success {
self?.myPresenter?.onSDKInitlized()
self?.didSdkInitilized = true
} else {
self?.myPresenter?.onError(errorText: error?.localizedDescription ?? "")
}
}
}
这是我的测试用例:
import XCTest
@testable import TriageFramework
class Virtual_First_Tests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample1() {
let homeInteractor: HomeInteractor = HomeInteractor();
var didInitlized = homeInteractor.didSdkInitilized
homeInteractor.initSDK()
sleep(2)
didInitlized = homeInteractor.didSdkInitilized
XCTAssertTrue(didInitlized)
}
但它总是失败,因为它永远不会进入成功或失败的回调。 我在这里做错了什么?
最佳答案
您不应该在单元测试中进行网络调用。单元测试旨在测试孤立的单个类。所以你应该 stub 你的网络电话或inject your dependencies进入您正在测试的类(在您的情况下为 HomeInteractor
)。此外,您的单元测试需要快速运行,在单元测试中进行网络调用会适得其反。
Here有一篇文章可以帮助您创建良好的单元测试。
关于ios - 无法在 xcode 项目中测试网络调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54689869/