I just started writing tests using XCTest, I have to write test cases to test if the right analytics event is passed, the analytics system has enum based events something like this.
enum AnalyticsEvent {
case loginScreenViewed
case loginAttempted
case loginFailed(reason: LoginFailureReason)
}
Analytics Engine
protocol AnalyticsEngine: class {
func sendAnalyticsEvent(named name: String, metadata: [String : String])
}
Implementation
class AnalyticsManager {
private let engine: AnalyticsEngine
init(engine: AnalyticsEngine) {
self.engine = engine
}
func log(_ event: AnalyticsEvent) {
engine.sendAnalyticsEvent(named: event.name, metadata: event.metadata)
}
}
class someViewModel{
private let analytics: AnalyticsManager!
func viewLoaded() {
analytics.screenView(name: .loginScreenViewed)
}
}
class someViewController {
private var viewModel : someViewModel?
func viewDidLoad(){
//fires an event
viewModel.viewDidLoad()
}
I checked a few articles which mentioned I have a mock class and store the event fired in an event queue array and assert the event against the array.
A basic assertion would be as follows (here eventQueue is an array where we are storing our mock events)
let event = try XCTUnwrap(analytics.eventQueue.first)
XCTAssertEqual(event.key,AnalyticsEvent.loginScreenViewed)
I would like to understand is there a way to standardize this kind of assertion, how do I dynamically check which analytics event the mock event has to be asserted against and if the respective properties are set for the event and also how to go about UI testing for the same.