Escribir pruebas unitarias en Swift para probar tareas asincr贸nicas

Hoy quiero decirte r谩pidamente c贸mo probar el c贸digo asincr贸nico.

Imagine la situaci贸n en la que necesita descargar datos de Internet y verificar si todo funciona bien o alguna otra tarea que se ejecute de forma asincr贸nica. 驴Y c贸mo probarlo? 驴Qu茅 pasa si intenta lo mismo que el c贸digo s铆ncrono normal?

func testAscynFunction() { someAsyncFunction() } func someAsyncFunction() { let bg = DispatchQueue.global(qos: .background) bg.asyncAfter(deadline: .now() + 5) { XCTAssert(false, "Something went wrong") } } 

Tal prueba nos devolver谩 un resultado positivo, ya que el m茅todo no esperar谩 todas nuestras tareas asincr贸nicas.

Para resolver tal problema en las pruebas, hay una gran cosa: XCTestExpectation
XCTestExpectation establece cu谩ntas veces se debe ejecutar el m茅todo asincr贸nico y solo despu茅s de todas estas ejecuciones la prueba finalizar谩 y dir谩 si hubo alg煤n error. Aqu铆 hay un ejemplo:

 class TestAsyncTests: XCTestCase { // 1)  expectation var expectation: XCTestExpectation! func testWithExpectationExample() { //2)   expectation = expectation(description: "Testing Async") //3)    ,     expectation.fulfill() expectation.expectedFulfillmentCount = 5 for index in 0...5 { someAsyncFunctionWithExpectation(at: index) } //5)      expectation.fulfill() //       60     ,     waitForExpectations(timeout: 60) { (error) in if let error = error { XCTFail("WaitForExpectationsWithTimeout errored: \(error)") } } } func someAsyncFunctionWithExpectation(at index: Int) { let bg = DispatchQueue.global(qos: .background) bg.asyncAfter(deadline: .now() + 5) { [weak self ] in XCTAssert(false, "Something went wrong at index \(index)") //4)      expectation.expectedFulfillmentCount self?.expectation.fulfill() } } } 

Espero que esta publicaci贸n sea 煤til para alguien.

Source: https://habr.com/ru/post/439772/


All Articles