XCTestExpectation - calling async method twice breaks API
I am writing units of tests in swifts and testing a unique workflow.
-
In the A () method, I am loading the object incorrectly (say with the wrong credentials) using the async method. Also start waiting
func methodA(withCred credential: NSURLCredential) { var objA = ObjectA() // Set objA.a, objA.b, objA.c, objA.credential = credential //Incorrect credential First time, Correct Credential second time objA.delegate = self expectation = expectationWithDescription("Aync") objA.callAsyncMethod() //This fires successDelegate() or failureDelegate()}
-
When FailureDelegate () is fired, I reload the object, correctly this time. To do this, I need to call MethodA () again (so I can reuse all the other stuff in there).
func failureDelegate(error: NSError!) { XCTAssertTrue(error.localizedDescription == "Invalid Credentials") //Now that I’ve verified correct error is returned, I need to reload objA methodA(withCred:correctCredential) } func successDelegate(obj : ObjectA) { XCTAssert("Object is loaded") expectation.fulfill() }
3. This again raises the same expectation in method A and results in the following error:
API violation - creating pending wait.
I understand that this is not allowed by swift. Is there a workaround or better way to test these async looping methods with Swift using XCTest?
Thank!
source to share
Don't use instances expectation
for testing. You must declare expectation
(i.e. C let
) in the body of each test, not as a property on XCTestCase
. If you really need to use the delegation pattern (closure would be much, much simpler and more conditional), you can pass this as an additional parameter to your delegate method.
source to share
I think your example code is incomplete, could you provide the complete code?
As @mattt suggests, each test should be unique and should not reuse another test variable.
As for your problem, you must declare all your expectations before launching waitForExpectationsWithTimeout:handler:
. You cannot create a new expectation after you start waiting for another.
source to share