[英]How to write a unit test for a function inside a protocol extension?
Currently I have a protocol: 目前,我有一个协议:
protocol CameraOpen: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func openCamera()
}
The function is defined in the protocol extension: 该功能在协议扩展中定义:
extension CameraOpen where Self: UIViewController {
func openCamera() {
if UIImagePickerController.isSourceTypeAvailable(.camera) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .camera
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
}
}
}
This issue is I have no clue on how to actually test the function defined in the protocol extension. 这个问题是我不知道如何实际测试协议扩展中定义的功能。 Typically I make an instance of the class I want to test and use dot notation to test each function in the class but since it's a protocol I can't make an instance of it.
通常,我会创建要测试的类的实例,并使用点表示法来测试该类中的每个函数,但是由于它是协议,因此无法创建它的实例。 For example if I do something like this:
例如,如果我做这样的事情:
class CamerOpenTests: XCTestCase {
var cameraOpen: CameraOpen?
override func setUp() {
super.setUp()
cameraOpen = CameraOpen()// error here
}
override func tearDown() {
cameraOpen = nil
super.tearDown()
}
}
I get an error: 我收到一个错误:
'CameraOpen' cannot be constructed because it has no accessible initializers
无法构造“ CameraOpen”,因为它没有可访问的初始化程序
Any ideas on how to unit test this function? 关于如何对该功能进行单元测试的任何想法?
Even though you can add code to a protocol as an extension, you cannot instantiate it, that requires a view controller sub class tagged with the protocol. 即使您可以将代码作为扩展添加到协议中,也无法实例化它,这需要使用协议标记的视图控制器子类。
class CamerOpenTests: XCTestCase {
class TestCameraOpen : UIViewController, CameraOpen { }
var cameraOpen: CameraOpen?
override func setUp() {
super.setUp()
cameraOpen = TestCameraOpen()
}
override func tearDown() {
cameraOpen = nil
super.tearDown()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.