اختبارات وحدة الكتابة في سويفت لاختبار المهام غير المتزامنة

اليوم أريد أن أخبرك بسرعة عن كيفية اختبار التعليمات البرمجية غير المتزامنة.

تخيل الموقف الذي تحتاجه لتنزيل البيانات من الإنترنت وتحقق ما إذا كان كل شيء يعمل بشكل جيد ، أو بعض المهام الأخرى التي تعمل بشكل غير متزامن. وكيفية اختباره؟ ماذا لو حاولت نفس الكود المتزامن العادي؟!

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

سيعود هذا الاختبار بنا بنتيجة إيجابية ، لأن الطريقة لن تنتظر جميع مهامنا غير المتزامنة.

لحل هذه المشكلة في الاختبارات ، هناك شيء واحد رائع: XCTestExpectation
يحدد XCTestExpectation عدد مرات تنفيذ الطريقة غير المتزامنة وفقط بعد كل عمليات الإعدام هذه ، سينتهي الاختبار ويعرف ما إذا كانت هناك أية أخطاء. هنا مثال:

 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() } } } 

آمل أن يكون هذا المنشور مفيدًا لشخص ما.

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


All Articles