简体   繁体   中英

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

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()
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM