Skip to content

Instantly share code, notes, and snippets.

@leovido
Last active September 23, 2020 12:00
Show Gist options
  • Save leovido/868bf63cdee21b94de2a0e262382cfa8 to your computer and use it in GitHub Desktop.
Save leovido/868bf63cdee21b94de2a0e262382cfa8 to your computer and use it in GitHub Desktop.
Mock example for AVFoundation code. This will allow to pass in default values and to isolate testing for specific interfaces. In this example, it mocks the AVCaptureSession through the SessionCapturable.
import Foundation
import AVFoundation
enum CameraPosition {
case front
case back
}
// interface with functions that our app uses for AVCaptureSession
protocol SessionCapturable {
func canAddInput(_ input: AVCaptureInput) -> Bool
func addInput(_ input: AVCaptureInput)
func canAddOutput(_ output: AVCaptureOutput) -> Bool
func addOutput(_ output: AVCaptureOutput)
func startRunning()
}
// All the functions in SessionCapturable are in AVCaptureSession.
extension AVCaptureSession: SessionCapturable {}
// to be adopted by a component that managed the camera. Can be used to mock as well. Ideally, it's better to test out the real implementation with mocked values, hence why captureSession is a SessionCapturable type, allowing to have the real AVCaptureSession or anything else that conforms to it.
protocol CameraRepresentable {
var captureSession: SessionCapturable? { get }
var currentCameraPosition: CameraPosition? { get }
var frontCamera: AVCaptureDevice? { get }
var frontCameraInput: AVCaptureDeviceInput? { get }
var photoOutput: AVCapturePhotoOutput? { get }
var rearCamera: AVCaptureDevice? { get }
var rearCameraInput: AVCaptureDeviceInput? { get }
}
final class MockAVCaptureSession: SessionCapturable {
let canAddInputMockValue: Bool
let canAddOutputMockValue: Bool
var canAddInputWasCalled: Bool = false
var addInputWasCalled: Bool = false
var canAddOutputWasCalled: Bool = false
var addOutputWasCalled: Bool = false
var startRunningWasCalled: Bool = false
init(input: Bool, output: Bool) {
self.canAddInputMockValue = input
self.canAddOutputMockValue = output
}
func canAddInput(_ input: AVCaptureInput) -> Bool {
canAddInputWasCalled.toggle()
return canAddInputMockValue
}
func addInput(_ input: AVCaptureInput) {
canAddInputWasCalled.toggle()
}
func canAddOutput(_ output: AVCaptureOutput) -> Bool {
canAddOutputWasCalled.toggle()
return canAddOutputMockValue
}
func addOutput(_ output: AVCaptureOutput) {
addOutputWasCalled.toggle()
}
func startRunning() {
startRunningWasCalled.toggle()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment