Testing API call that happens at app launch results in multiple calls to fulfill

168 Views Asked by At

I am trying to implement Unit Testing for the first time on an existing app. First of all, contrary to what I see in tutorials, the app is launched as I try to run unit tests. I tried setting Host App to "None" on my test target, but ran into several issues having to do with "symbols not found" errors.

I then kept trying to run unit tests even with the app launching, but I run into the following error:

'NSInternalInconsistencyException', reason: 'API violation - multiple calls made to -[XCTestExpectation fulfill] for Did log in user.'

My guess is that my test logs in the user and fulfills an expectation on the delegate, but the app itself when it launches is logging in the user, so 'fulfill' gets called twice.

My test is the following:

func testLogInUser() {
   UserManager.loginDelegate = self
   expectation = expectation(description: "Did log in user")
   UserManager.logInUser(withEmail: "[email protected]", password: "jacobo123")
   waitForExpectations(timeout: 10.0)
}

//Delegate Method
func didLogIn(user: User) {
    XCTAssertEqual(user.email, "[email protected]")
    XCTAssertNotNil(user.uid)
    XCTAssertNotEqual(user.type, .guest)
    expectation?.fulfill() //Crashes here
}

Therefore, I'm looking for a solution that either lets me run the tests and API calls without running the app, or somehow avoids fulfill being called multiple times.

There is an answer in SO that suggests setting 'expectation' to nil after use, but didn't work in my case. Also tried setting the variable to weak.

1

There are 1 best solutions below

0
Jon Reid On

You can prevent your normal app launch sequence from taking place. Provide a different app delegate that's used when the app is launched for testing. See https://qualitycoding.org/ios-app-delegate-testing/