Test-Driven iOS Development with Swift - Dr. Dominik Hauser - E-Book

Test-Driven iOS Development with Swift E-Book

Dr. Dominik Hauser

0,0
25,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Test-driven development (TDD) is a proven way to find software bugs earlier on in software development. Writing tests before you code improves the structure and maintainability of your apps, and so using TDD in combination with Swift 5.5's improved syntax leaves you with no excuse for writing bad code.
Developers working with iOS will be able to put their knowledge to work with this practical guide to TDD in iOS. This book will help you grasp the fundamentals and show you how to run TDD with Xcode. You'll learn how to test network code, navigate between different parts of the app, run asynchronous tests, and much more. Using practical, real-world examples, you'll begin with an overview of the TDD workflow and get to grips with unit testing concepts and code cycles. You'll then develop an entire iOS app using TDD while exploring different strategies for writing tests for models, view controllers, and networking code. Additionally, you'll explore how to test the user interface and business logic of iOS apps and even write tests for the network layer of the sample app.
By the end of this TDD book, you'll be able to implement TDD methodologies comfortably in your day-to-day development for building scalable and robust applications.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 250

Veröffentlichungsjahr: 2022

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Test-Driven iOS Development with Swift

Fourth Edition

Write maintainable, flexible, and extensible code using the power of TDD with Swift 5.5

Dr. Dominik Hauser

BIRMINGHAM—MUMBAI

Test-Driven iOS Development with Swift

Fourth Edition

Copyright © 2022 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Rohit Rajkumar

Publishing Product Manager: Ashitosh Gupta

Senior Editor: Keagan Carneiro

Content Development Editor: Adrija Mitra

Technical Editor: Joseph Aloocaran

Copy Editor: Safis Editing

Project Coordinator: Rashika Ba

Proofreader: Safis Editing

Indexer: Pratik Shirodkar

Production Designer: Roshan Kawale

Marketing Coordinator: Elizabeth Varghese

First published: February 2016

Second edition: October 2016

Third edition: October 2017

Fourth edition: March 2022

Production reference: 3060522

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

978-1-80323-248-5

www.packt.com

*

To Isa and our two children

– Dr. Dominik Hauser

Contributors

About the author

Dr. Dominik Hauser is an iOS developer working for a small company in western Germany. In over 11 years as an iOS developer, he has worked on many different apps, both large and small. In his spare time, Dominik builds small (often silly) apps and explores how he can become a better iOS developer. He talks at conferences, writes books, and is active in the iOS community in general. His most successful open source component (in terms of stars) is a pull-to-refresh control for a table view that consists of an actual SpriteKit game.

Before Dominik became an iOS developer, he was a physicist, researching the most powerful photon sources within our galaxy.

Thank you, Isa, for your continued support, patience, and encouragement.

About the reviewers

Nour Araar is a software engineer with extensive experience in mobile and web development who has built many medium- to large-scale apps, and who also has interests in AI/ML, data science, cloud solutions, and competitive programming. He has participated in many competitions not only as a contestant but also as a coach, and has also worked as a teaching assistant in university after graduating as an AI engineer. He loves to share his experience, and his motto is, everyone should learn to code and become a programmer, which is why he makes videos and writes blogs helping others to learn how to code, on YouTube and Medium, as well as on his own website.

Kenneth Michael Dubroff is a single dad and experienced iOS developer. He currently works with several talented iOS and Android developers, managing releases for the adaptive fitness app JRNY. He also works as a tech editor for the server-side Swift team at raywenderlich.com. Kenny also recently finished editing a book with raywenderlich.com entitled Real-World iOS, which focuses on best practices for mid-level developers. Kenny previously assisted various private clients through freelance contracts, sometimes managing apps from start to release, sometimes adding new features, and always wanting to refactor.

I would like to thank my daughter, son, dad, and grandparents. None of my accomplishments would be possible without your past and continued support!

It was a pleasure editing Test-Driven iOS Development with Swift. The team put in a lot of hard work and I hope you find it as insightful as I have!

Table of Contents

Preface

Section 1 –The Basics of Test-Driven iOS Development

Chapter 1: Your First Unit Tests

Technical requirements

Building your first automatic unit test

What are unit tests?

Implementing a unit test example

Disabling slow UI tests

Assert functions in the XCTest framework

Custom assert functions

Understanding the difference from other kinds of tests

Integration tests

UI tests

Snapshot tests

Manual tests

Summary

Exercises

Chapter 2: Understanding Test-Driven Development

The origin of TDD

The TDD workflow – red, green, refactor

Red

Green

Refactor

The advantages of TDD

The disadvantages of TDD

What to test

Summary

Chapter 3: Test-Driven Development in Xcode

Technical requirements

An example of TDD

Capitalize headline – red

Capitalize headline – green

Capitalize headline – refactor

Capitalize headline 2 – red

Capitalize headline 2 – green

Capitalize headline 2 – refactor

A recap

Finding information about tests in Xcode

Test navigator

Test overview

Running tests

Running one specific test

Running all tests in a test case

Running a group of tests

Setting up and tearing down

Debugging tests

A breakpoint that breaks on test failure

The test again feature

Summary

Exercises

Section 2 –The Data Model

Chapter 4: The App We Are Going to Build

Technical requirements

A list of to-do items

A view for the details of a to-do item

A view to add to-do items

The structure of the app

The table view controller, the delegate, and the data source

Table view cells

The model

Other views

The development strategy

Getting started in Xcode

Setting up useful Xcode behaviors for testing

Useful build behaviors

Testing behaviors

Summary

Exercises

Chapter 5: Building a Structure for ToDo Items

Technical requirements

Implementing the ToDoItem struct

Adding a title property

Adding an itemDescription property

Removing a hidden source of bugs

Adding a timestamp property

Dealing with optional values in unit tests

Adding a location property

Implementing the Location struct

Adding a coordinate property

Summary

Exercises

Chapter 6: Testing, Loading, and Saving Data

Technical requirements

Publishing changes with Combine

Testing asynchronous Combine code

Making ToDoItem equatable

Checking items

Storing and loading ToDoItems

Implementing storing and loading

Cleaning up the code

Summary

Exercises

Section 3 –Views and View Controllers

Chapter 7: Building a Table View Controller for the To-Do Items

Technical requirements

Adding the table view for the to-do items

Testing the data source of a table view

Adding a test double

Using test doubles to implement a number of rows

Using test doubles to implement setting up the to-do item cell

Refactoring to a diffable data source

Presenting two sections

Implementing the delegate of a table view

Summary

Exercises

Chapter 8: Building a Simple Detail View

Technical requirements

Adding labels, a button, and a map

Filling in the data

Checking the to-do item

Summary

Exercises

Chapter 9: Test-Driven Input View in SwiftUI

Technical requirement

Adding the ViewInspector package

Using ViewInspector to test a simple view

Adding a title text field

Adding a DatePicker

Improving the test code and the implementation

Adding another text field

Improving the user interface

Adding an address text field and a button

Testing button actions with ViewInspector

Summary

Exercises

Section 4 –Networking and Navigation

Chapter 10: Testing Networking Code

Mocking CLGeoCoder

Cleaning your project

Preparations for the tests

Creating the first test

Testing async/await code that communicates with URLSession

Handling errors

Summary

Exercises

Chapter 11: Easy Navigation with Coordinators

Technical requirement

Testing the app's setup

Navigating to the details

Navigating to a modal view

Adding missing parts

Making the cells visible

Dismissing the input view

Making the due date visible in the details

Fixing the wrong item being selected

Fixing the layout of the table view

Summary

Exercises

Why subscribe?

Other Books You May Enjoy

Packt is searching for authors like you

Preface

Automatic tests are an essential part of agile software development, especially unit tests, with their quick and reliable feedback helping developers to keep projects maintainable and clean. Test-driven development (TDD) methodology gives developers clear rules about how to build scalable, maintainable, and – as such – agile projects. Often, once the initial aversion to writing tests before the code is overcome, developers stick to TDD because they feel that their code is better and they are more confident in the result.

In this book, we will explore how to write unit tests for many different aspects of iOS development for iOS 15+. All that will be done in the context of test-driven development. The book starts with an introduction to testing in general and TDD in iOS apps and continues with building a complete app throughout the book. It covers basic UI structures, the Combine framework, async/await, and even SwiftUI.

After you've worked through the book and challenged yourself in the exercises, you will be able to write tests for a variety of code in iOS development, and you will have the tools to decide what to learn next in your journey to become an expert in test-driven iOS development.

Who this book is for

TDD is a proven way to find software bugs early. Writing tests before you code improves the structure and maintainability of your apps. This book will guide you through the steps for creating a complete app using TDD and cover the core elements of iOS apps: view controllers, views, navigation, networking, Combine, and SwiftUI.

If you have already made your first small iOS apps and want to learn how to improve your work using automated unit tests, then this book is for you.

What this book covers

Chapter 1, Your First Unit Tests, sees the first unit tests at work. We write real tests for a fictional blogging app and explore the different kinds of assertions in XCTest, a testing framework from Apple.

Chapter 2, Understanding Test-Driven Development, looks at test-driven development and how it can help us developers to write maintainable code.

Chapter 3, Test-Driven Development in Xcode, brings the insights from the first two chapters together and looks at how test-driven development works in Xcode. You'll learn some tricks and configurations that make Xcode a valuable testing tool.

Chapter 4, The App We Are Going To Build, discusses the app we are going to build in the rest of the book. This chapter ends with setting up the project for the app in Xcode.

Chapter 5, Building a Structure for ToDo Items, shows how to build the model layer of our app. By working on it, you will learn how to write tests for Combine code.

Chapter 6, Testing, Loading, and Saving Data, addresses the fact that the data used in the app needs to be saved and loaded in the file system of the iOS device. In this chapter, we build the class that is responsible for this task.

Chapter 7, Building a Table View Controller for the To-Do Items, shows how to write tests for a table view with a diffable data source. You will learn how to test updates of table view cells and the selection of cells.

Chapter 8, Building a Simple Detail View, explores how to test user interface elements such as labels, buttons, and maps. We also take a look at how to test actions of the user that change the data in the model layer.

Chapter 9, Test-Driven Input View in SwiftUI, shows how to build and test a view created using SwiftUI. In order to be able to test SwiftUI code, we add a third-party testing library to the testing target.

Chapter 10, Testing Networking Code, looks at writing tests for the new async/await APIs of URLSession. This will allow you to write clean tests that simulate the network communication with a fast mock object.

Chapter 11, Easy Navigation with Coordinators, the final chapter, shows how to write tests for navigation between the view controllers of our app. This allows us, finally, to see our small app running on the simulator. We fix the last bugs using TDD and end up with a working app.

To get the most out of this book

You need the latest version of Xcode installed on your Mac. The code in this book has been tested with Xcode 13 and Swift 5.5 but it should also work with newer versions of Xcode and Swift.

If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book's GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

You should try to do all the exercises in the book. They are designed to give you more insight and strengthen your experience.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Test-Driven-iOS-Development-with-Swift-Fourth-Edition. If there's an update to the code, it will be updated in the GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots and diagrams used in this book. You can download it here: http:https://static.packt-cdn.com/downloads/9781803232485_ColorImages.pdf.

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "A table view is usually represented by UITableViewController, which is also the data source and delegate for the table view."

A block of code is set as follows:

// APIClient.swift

lazy var geoCoder: GeoCoderProtocol

  = CLGeocoder()

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

mkdir src/client/apollo touch src/client/apollo/index.js

Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: "From the Details screen, the user will be able to check an item."

Tips or Important Notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Share Your Thoughts

Once you've read Test-Driven iOS Development with Swift Fourth Edition, we'd love to hear your thoughts! Please click here to go straight to the Amazon review pagefor this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we're delivering excellent quality content.

Section 1 –The Basics of Test-Driven iOS Development

Without a good understanding of the basics, learning is hard and frustrating. In this section, we will learn what unit tests are, how they are connected to test-driven development, and how they look and work in Xcode.

In this section, we will cover the following chapters:

Chapter 1, Your First Unit TestsChapter 2, Understanding Test-Driven DevelopmentChapter 3, Test-Driven Development in Xcode