Популярное

Музыка Кино и Анимация Автомобили Животные Спорт Путешествия Игры Юмор

Интересные видео

2025 Сериалы Трейлеры Новости Как сделать Видеоуроки Diy своими руками

Топ запросов

смотреть а4 schoolboy runaway турецкий сериал смотреть мультфильмы эдисон
dTub
Скачать

XCTest + Swift: setUp/tearDown vs Factory Methods

Автор: Essential Developer

Загружено: 2018-10-10

Просмотров: 19940

Описание:

★ Register Now to Our Free iOS Career Course! https://www.essentialdeveloper.com/co...

Subscribe to our channel: https://www.youtube.com/essentialdeve...

• XCTest repo on GitHub https://github.com/apple/swift-coreli...
• QuizApp repo on GitHub https://github.com/essentialdeveloper...

In this episode, we dive into `XCTestCase`’s lifecycle and show different ways for configuring your system under test.

XCTest, similarly to JUnit, invokes each test method on a separate instance of the test case. To illustrate with an example, imagine that you have ten test methods, the XCTest framework will instantiate ten instances of the test case class and invoke only one of the methods per instance. We believe this is a good design choice, as by running the test methods in separate instances we can avoid sharing state between tests. However, `XCTestCase`’s behavior isn’t that obvious which can make it counterintuitive when compared with how we're used to using objects to share state between methods.

Swift Factory methods

Although the `setUp/tearDown` configuration method is valid, at Essential Developer we noticed that moving configuration code to factory methods would yield better results in most cases.

Here are the main reasons why we prefer factory methods over the `setUp/tearDown` configuration:

1. Many tests have a different setup/configuration, so there are no significant benefits in sharing the object instantiation.

2. We normally use constructor injection. If we create a class as a property in the class scope, we would have to use property injection to be able to configure the instance for each test. Which is fine too, but we prefer constructor injection since most of our classes don’t allow mutability.

3. We want to test the whole lifecycle of the system under test instance, to guarantee there are no issues when it's removed from memory. We could achieve this with the `setUp()` approach, but to test the whole lifecycle we would also need to set it to `nil` in the `tearDown()`. By creating the instance in the test method scope, we guarantee its lifecycle is tested within the method (since the instance will be freed automatically).

4. It would take more lines of code to do the same thing and, in our opinion, it would negatively impact the design of the test and the production code (e.g., `constructor to property` injection).

5. `setUp/tearDown` can make the tests harder to read/understand since, when reading the code, we would have to scroll/jump scope (from test method to `setUp/tearDown` code) to understand the whole context. We prefer to keep our test setup (Given/When/Then or Arrange/Act/Assert) in the shortest scope possible.

When we use XCTestCase setUp/tearDown in Swift

To be clear, we avoid `setUp/tearDown` configuration because we believe there are better ways, but we do use it when it's useful to us.

For example, `setUp/tearDown` can be useful when dealing with global state (e.g., databases) that needs to be restated for each test (as we don't want to pollute the test methods with those details).

Conclusion

We would like you to be proactive and think about the problems you're facing so you find the best solution for you. For example, our approach could be wrong for you, so be critical and let us know your preferred way.


★ Professional iOS Engineering S01

Take your skillset to the next level and boost your career https://www.essentialdeveloper.com/pr...

★ Download our new app

You can download Neat Trivia from the App Store today at https://itunes.apple.com/app/id125311....

Connect with us on:

• Website: https://www.essentialdeveloper.com
• Twitter:   / essentialdevcom  
• Facebook:   / essentialdeveloper  

XCTest + Swift: setUp/tearDown vs Factory Methods

Поделиться в:

Доступные форматы для скачивания:

Скачать видео mp4

  • Информация по загрузке:

Скачать аудио mp3

Похожие видео

Игорь Плотников, «XCUITest. Таков путь»

Игорь Плотников, «XCUITest. Таков путь»

Модульное тестирование в iOS с помощью XCTest

Модульное тестирование в iOS с помощью XCTest

Синьор 1С: 10 привычек, без которых ты не вырастешь

Синьор 1С: 10 привычек, без которых ты не вырастешь

Careful With “Singleton” Lookalikes (WAY TOO COMMON)

Careful With “Singleton” Lookalikes (WAY TOO COMMON)

“How do you think when writing tests?” – It’s simpler than you may think

“How do you think when writing tests?” – It’s simpler than you may think

Я в опасности

Я в опасности

UI Testing Your iOS App (Xcode 13) – 2022

UI Testing Your iOS App (Xcode 13) – 2022

Почему ваш код не соответствует Python (и как это исправить)

Почему ваш код не соответствует Python (и как это исправить)

⚡️ У Путина экстренно просят помощи || Сын Кадырова разбился в ДТП?

⚡️ У Путина экстренно просят помощи || Сын Кадырова разбился в ДТП?

The Windows 11 Disaster That's Killing Microsoft

The Windows 11 Disaster That's Killing Microsoft

What is Unit Testing, Why We Use It, and Sample Test Cases

What is Unit Testing, Why We Use It, and Sample Test Cases

Swift Dependency Injection - What is it? What are the benefits?

Swift Dependency Injection - What is it? What are the benefits?

Сисадмины больше не нужны? Gemini настраивает Linux сервер и устанавливает cтек N8N. ЭТО ЗАКОННО?

Сисадмины больше не нужны? Gemini настраивает Linux сервер и устанавливает cтек N8N. ЭТО ЗАКОННО?

Decomposing Swift code into modules – Intro to modular design

Decomposing Swift code into modules – Intro to modular design

MVVM + Dependency Injection in Swift | Unit Testing | iOS

MVVM + Dependency Injection in Swift | Unit Testing | iOS

S01E02: [TDD 🍅 1] Creating a Swift Framework - The Game Engine

S01E02: [TDD 🍅 1] Creating a Swift Framework - The Game Engine

Intro to Unit Testing in Swift

Intro to Unit Testing in Swift

Кто пишет код лучше всех? Сравнил GPT‑5.2, Opus 4.5, Sonnet 4.5, Gemini 3, Qwen 3 Max, Kimi, GLM

Кто пишет код лучше всех? Сравнил GPT‑5.2, Opus 4.5, Sonnet 4.5, Gemini 3, Qwen 3 Max, Kimi, GLM

UI Testing a SwiftUI application in Xcode | Advanced Learning #18

UI Testing a SwiftUI application in Xcode | Advanced Learning #18

Clean Swift Code with Where Clause

Clean Swift Code with Where Clause

© 2025 dtub. Все права защищены.



  • Контакты
  • О нас
  • Политика конфиденциальности



Контакты для правообладателей: infodtube@gmail.com